// تهيئة البيانات من التخزين المحلي
let inventory = JSON.parse(localStorage.getItem('adv_inventory')) || [];
let salesHistory = JSON.parse(localStorage.getItem('adv_sales')) || [];
let purchaseHistory = JSON.parse(localStorage.getItem('adv_purchases')) || [];
let purchaseItems = [];
let cart = [];
// التعديل: سحب سعر الصرف المحفوظ أو تعيين 1 كقيمة افتراضية
let currentUsdRate = parseFloat(localStorage.getItem('adv_usd_rate')) || 1;
// التعديل: دوال حساب سعر الدولار وحفظه
function saveUsdRate() {
currentUsdRate = parseFloat(document.getElementById('usdRate').value) || 1;
localStorage.setItem('adv_usd_rate', currentUsdRate);
calcLiraCost(); // تحديث الحقل مباشرة إذا كان المستخدم يكتب منتجاً جديداً
}
function calcLiraCost() {
const usdCost = parseFloat(document.getElementById('pCostUSD').value) || 0;
document.getElementById('pCost').value = (usdCost * currentUsdRate).toFixed(2);
}
// التنقل بين الأقسام
function showSection(id, btn) {
document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
document.getElementById(id).classList.add('active');
document.querySelectorAll('.nav-link').forEach(l => l.classList.remove('active'));
if(btn) btn.classList.add('active');
// السطر الجديد: تصفير اسم الزبون عند الدخول لقسم نقطة البيع
if(id === 'pos') {
document.getElementById('customerName').value = '';
}
renderData();
}
// تحديث وعرض كافة البيانات
function renderData() {
// التعديل: تحديث حقل الدولار في واجهة الرئيسية
const usdInput = document.getElementById('usdRate');
if(usdInput) usdInput.value = currentUsdRate;
// 1. تحديث جدول المخزون
const invTable = document.getElementById('inventoryTable');
if (invTable) {
invTable.innerHTML = '';
let lowStock = 0;
inventory.forEach((item, index) => {
if (item.qty < 5) lowStock++;
const usdDisplay = item.costUSD !== undefined ? item.costUSD : '-'; // للمنتجات القديمة
// التعديل: إضافة حقل عرض الدولار للجدول
invTable.innerHTML += `
| ${item.name} |
${item.qty} |
${usdDisplay} |
${item.cost} |
${item.retail} |
${item.wholesale} |
|
`;
});
document.getElementById('dash-items').innerText = inventory.length;
document.getElementById('dash-alert').innerText = lowStock;
}
// 2. تحديث السجل والداشبورد
const salesTable = document.getElementById('salesHistoryTable');
if (salesTable) {
let totalSales = 0;
salesTable.innerHTML = '';
salesHistory.forEach((s, index) => {
totalSales += s.total;
salesTable.innerHTML += `| ${s.date} | ${s.customer || 'عام'} | ${s.type === 'retail' ? 'مفرق' : 'جملة'} | ${s.total.toFixed(2)} |
`;
});
document.getElementById('dash-sales').innerText = totalSales.toFixed(2);
}
const purchaseTable = document.getElementById('purchaseHistoryTable');
if (purchaseTable) {
let totalPurchases = 0;
purchaseTable.innerHTML = '';
purchaseHistory.forEach((p, index) => {
totalPurchases += p.total;
purchaseTable.innerHTML += `| ${p.date} | ${p.supplier} | ${p.invoiceRef || '-'} | ${p.total.toFixed(2)} |
`;
});
const dashPurchases = document.getElementById('dash-purchases');
if (dashPurchases) dashPurchases.innerText = totalPurchases.toFixed(2);
}
updatePurchaseProductOptions();
renderPurchaseItems();
filterProducts();
localStorage.setItem('adv_inventory', JSON.stringify(inventory));
localStorage.setItem('adv_sales', JSON.stringify(salesHistory));
localStorage.setItem('adv_purchases', JSON.stringify(purchaseHistory));
}
function filterProducts() {
const searchInput = document.getElementById('posSearch');
if (!searchInput) return;
const searchText = searchInput.value.toLowerCase();
const posSelect = document.getElementById('posSelect');
const currentValue = posSelect.value;
posSelect.innerHTML = '';
// سحب نوع البيع الحالي لمعرفة أي سعر نعرضه للمستخدم
const priceType = document.getElementById('priceType').value;
inventory.forEach((item, index) => {
if (item.name.toLowerCase().includes(searchText)) {
// جلب السعر بالدولار من المخزن بناءً على نوع البيع
const basePriceUSD = priceType === 'retail' ? item.retail : item.wholesale;
// حساب السعر بالليرة (السعر بالدولار × سعر الصرف الحالي)
const livePriceLira = (basePriceUSD * currentUsdRate).toFixed(2);
const option = document.createElement('option');
option.value = index;
option.text = `${item.name} (متوفر: ${item.qty}) - السعر المباشر: ${livePriceLira} ل.س`;
if (item.qty <= 0) option.disabled = true;
posSelect.appendChild(option);
}
});
if (currentValue && Array.from(posSelect.options).some(opt => opt.value === currentValue)) {
posSelect.value = currentValue;
}
}
// التعديل: إضافة منتج جديد مع سعر الدولار
const invForm = document.getElementById('inventoryForm');
if (invForm) {
invForm.onsubmit = (e) => {
e.preventDefault();
inventory.push({
name: document.getElementById('pName').value,
qty: parseInt(document.getElementById('pQty').value),
costUSD: parseFloat(document.getElementById('pCostUSD').value),
cost: parseFloat(document.getElementById('pCost').value),
retail: parseFloat(document.getElementById('pRetail').value),
wholesale: parseFloat(document.getElementById('pWholesale').value)
});
e.target.reset();
renderData();
};
}
function filterPurchaseProducts() {
const searchInput = document.getElementById('purchaseSearch');
const select = document.getElementById('purchaseProductSelect');
if (!select) return;
const searchText = searchInput?.value.toLowerCase() || '';
const currentValue = select.value;
if (searchText) {
select.innerHTML = '';
} else {
select.innerHTML = '';
}
inventory.forEach((item, index) => {
if (!searchText || item.name.toLowerCase().includes(searchText)) {
const option = document.createElement('option');
option.value = index;
option.text = `${item.name} (متوفر: ${item.qty})`;
select.appendChild(option);
}
});
if (currentValue && Array.from(select.options).some(opt => opt.value === currentValue)) {
select.value = currentValue;
} else {
select.value = '';
prefillPurchasePrice();
}
}
function updatePurchaseProductOptions() {
const select = document.getElementById('purchaseProductSelect');
if (!select) return;
const searchInput = document.getElementById('purchaseSearch');
const currentValue = select.value;
if (searchInput && searchInput.value.trim()) {
filterPurchaseProducts();
return;
}
select.innerHTML = '';
inventory.forEach((item, index) => {
const option = document.createElement('option');
option.value = index;
option.text = `${item.name} (متوفر: ${item.qty})`;
select.appendChild(option);
});
if (currentValue) select.value = currentValue;
prefillPurchasePrice();
}
function copyProductNameToSearch(select, searchId) {
if (!select || !searchId) return;
const idx = select.value;
if (!idx) return;
const item = inventory[idx];
if (!item) return;
const searchInput = document.getElementById(searchId);
if (!searchInput) return;
searchInput.value = item.name;
if (searchId === 'posSearch') {
filterProducts();
} else if (searchId === 'purchaseSearch') {
filterPurchaseProducts();
}
}
function initProductCopyOnDblClick() {
const posSelect = document.getElementById('posSelect');
if (posSelect) posSelect.ondblclick = () => copyProductNameToSearch(posSelect, 'posSearch');
const purchaseSelect = document.getElementById('purchaseProductSelect');
if (purchaseSelect) purchaseSelect.ondblclick = () => copyProductNameToSearch(purchaseSelect, 'purchaseSearch');
}
function prefillPurchasePrice() {
const idx = document.getElementById('purchaseProductSelect').value;
const priceInput = document.getElementById('purchasePrice');
if (!priceInput) return;
if (idx === '') {
priceInput.value = '0.00';
return;
}
const item = inventory[idx];
if (!item) {
priceInput.value = '0.00';
return;
}
const oldPrice = item.costUSD !== undefined ? item.costUSD : ((item.cost || 0) / currentUsdRate);
priceInput.value = parseFloat(oldPrice || 0).toFixed(2);
}
function renderPurchaseItems() {
const list = document.getElementById('purchaseItemsList');
if (!list) return;
list.innerHTML = '';
if (purchaseItems.length === 0) {
list.innerHTML = 'لا توجد أصناف مضافة';
calcPurchaseTotal();
return;
}
let itemsSum = 0;
purchaseItems.forEach((p, i) => {
const subtotal = p.unitPrice * p.qty;
itemsSum += subtotal;
list.innerHTML += `
${p.name}
${p.qty} × ${p.unitPrice.toFixed(2)} = ${subtotal.toFixed(2)}
`;
});
document.getElementById('purchaseAmount').value = itemsSum.toFixed(2);
calcPurchaseTotal();
}
function addPurchaseItem() {
const idx = document.getElementById('purchaseProductSelect').value;
const qty = parseInt(document.getElementById('purchaseQty').value) || 0;
const unitPrice = parseFloat(document.getElementById('purchasePrice').value) || 0;
if (idx === '' || qty <= 0) {
alert('اختر المنتج والكمية الصحيحة');
return;
}
if (unitPrice <= 0) {
alert('أدخل سعر وحدة صالح');
return;
}
const item = inventory[idx];
if (!item) return;
const existing = purchaseItems.find(p => p.index == idx);
if (existing) {
existing.qty += qty;
existing.unitPrice = unitPrice;
} else {
purchaseItems.push({ index: parseInt(idx), name: item.name, qty: qty, unitPrice: unitPrice });
}
document.getElementById('purchaseSearch').value = '';
filterPurchaseProducts();
renderPurchaseItems();
}
function removePurchaseItem(i) {
purchaseItems.splice(i, 1);
renderPurchaseItems();
}
function calcPurchaseTotal() {
const baseAmount = purchaseItems.reduce((sum, item) => sum + (item.qty * item.unitPrice), 0);
const shipping = parseFloat(document.getElementById('shippingCost').value) || 0;
const additional = parseFloat(document.getElementById('additionalCost').value) || 0;
document.getElementById('purchaseAmount').value = baseAmount.toFixed(2);
document.getElementById('purchaseTotal').value = (baseAmount + shipping + additional).toFixed(2);
}
const purchaseForm = document.getElementById('purchaseForm');
if (purchaseForm) {
purchaseForm.onsubmit = (e) => {
e.preventDefault();
const supplier = document.getElementById('supplierName').value;
const invoiceRef = document.getElementById('invoiceRef').value;
const details = document.getElementById('purchaseDetails').value;
if (purchaseItems.length === 0) {
alert('أضف صنفاً واحداً على الأقل إلى الفاتورة');
return;
}
const amount = purchaseItems.reduce((sum, item) => sum + (item.qty * item.unitPrice), 0);
const shipping = parseFloat(document.getElementById('shippingCost').value) || 0;
const additional = parseFloat(document.getElementById('additionalCost').value) || 0;
const total = amount + shipping + additional;
purchaseItems.forEach(p => {
const invItem = inventory[p.index];
if (!invItem) return;
const oldQty = invItem.qty || 0;
const oldCost = invItem.cost !== undefined ? parseFloat(invItem.cost) : ((invItem.costUSD || 0) * currentUsdRate);
const newQty = p.qty;
const newPrice = p.unitPrice;
const totalQty = oldQty + newQty;
const weightedCost = totalQty > 0 ? ((oldCost * oldQty) + (newPrice * newQty)) / totalQty : newPrice;
invItem.qty = totalQty;
invItem.cost = parseFloat(weightedCost.toFixed(2));
if (currentUsdRate > 0) invItem.costUSD = parseFloat((weightedCost / currentUsdRate).toFixed(2));
});
purchaseHistory.push({
date: new Date().toLocaleString('ar-EG'),
supplier: supplier,
invoiceRef: invoiceRef,
details: details,
amount: amount,
shipping: shipping,
additional: additional,
total: total,
items: purchaseItems.map(p => ({ name: p.name, qty: p.qty, unitPrice: p.unitPrice })),
type: 'purchase'
});
purchaseItems = [];
renderPurchaseItems();
e.target.reset();
document.getElementById('purchaseTotal').value = '0.00';
renderData();
alert('تم حفظ فاتورة المشتريات بنجاح');
};
}
// إضافة المنتج للسلة بالليرة بناءً على سعر الصرف
function addToCart() {
const idx = document.getElementById('posSelect').value;
const qty = parseInt(document.getElementById('posQty').value);
const type = document.getElementById('priceType').value;
if (idx === "" || qty <= 0) return;
const item = inventory[idx];
if (item.qty < qty) { alert("الكمية غير كافية!"); return; }
// السعر الأساسي بالدولار
const priceUSD = (type === 'retail') ? item.retail : item.wholesale;
// حساب القيمة النهائية بالليرة التي ستسجل في الفاتورة
const finalPriceLira = priceUSD * currentUsdRate;
cart.push({ index: idx, name: item.name, qty: qty, price: finalPriceLira, type: type });
document.getElementById('posSearch').value = '';
filterProducts();
renderCart();
}
function renderCart() {
const list = document.getElementById('cartList');
let total = 0;
list.innerHTML = '';
cart.forEach((c, i) => {
total += c.price * c.qty;
list.innerHTML += `
${c.name} (${c.qty} × ${c.price})
${(c.price * c.qty).toFixed(2)}
`;
});
document.getElementById('cartTotal').innerText = total.toFixed(2);
}
function removeCartItem(i) {
cart.splice(i, 1);
renderCart();
}
function checkout() {
if (cart.length === 0) return;
cart.forEach(c => { inventory[c.index].qty -= c.qty; });
const total = parseFloat(document.getElementById('cartTotal').innerText);
const summary = cart.map(i => `${i.name} (${i.qty})`).join(', ');
salesHistory.push({
date: new Date().toLocaleString('ar-EG'),
customer: document.getElementById('customerName').value || 'عام',
summary: summary,
total: total,
type: cart[0].type,
details: cart.map(c => ({ name: c.name, qty: c.qty, price: c.price }))
});
cart = [];
renderCart();
renderData();
alert("تمت العملية بنجاح");
}
function viewInvoice(index) {
const s = salesHistory[index];
if (!s) return;
const items = s.details || [];
let itemsHtml = items.length ? items.map(d => `
| ${d.name} |
${d.qty} |
${d.price.toFixed(2)} |
${(d.qty * d.price).toFixed(2)} |
`).join('') : `| لا توجد تفاصيل لهذه الفاتورة |
`;
document.getElementById('modalBody').innerHTML = `
الزبون: ${s.customer || 'زبون عام'}
نوع البيع: ${s.type}
| الصنف | الكمية | السعر | الإجمالي |
${itemsHtml}
الإجمالي النهائي: ${s.total.toFixed(2)}
`;
// إظهار المودال
var myModal = new bootstrap.Modal(document.getElementById('invoiceModal'));
myModal.show();
}
function viewPurchaseInvoice(index) {
const p = purchaseHistory[index];
if (!p) return;
const items = p.items || [];
const itemsHtml = items.length ? items.map(i => `
| ${i.name} |
${i.qty} |
`).join('') : `| لا توجد أصناف مدرجة |
`;
document.getElementById('modalBody').innerHTML = `
المورد: ${p.supplier}
رقم الفاتورة: ${p.invoiceRef || '-'}
تفاصيل: ${p.details || '-'}
| قيمة الفاتورة | ${p.amount.toFixed(2)} |
| تكلفة الشحن | ${p.shipping.toFixed(2)} |
| التكاليف الإضافية | ${p.additional.toFixed(2)} |
| المجموع النهائي | ${p.total.toFixed(2)} |
`;
var myModal = new bootstrap.Modal(document.getElementById('invoiceModal'));
myModal.show();
}
// دالة تنفيذ الطباعة
function printInvoice() {
window.print();
}
// excel
function exportData() {
// التأكد من أن المكتبة محملة في المتصفح
if (typeof XLSX === 'undefined') {
alert("خطأ: مكتبة الإكسل لم يتم تحميلها بعد. يرجى التأكد من اتصال الإنترنت أو تحديث الصفحة.");
return;
}
try {
if (inventory.length === 0 && salesHistory.length === 0 && purchaseHistory.length === 0) {
alert("لا توجد بيانات لتصديرها.");
return;
}
// التعديل: تحويل بيانات المخزن (بما فيها الدولار)
const wsInv = XLSX.utils.json_to_sheet(inventory.map(item => ({
"المنتج": item.name,
"الكمية": item.qty,
"شراء $": item.costUSD || 0,
"شراء بالليرة": item.cost,
"المفرق": item.retail,
"الجملة": item.wholesale
})));
// تحويل بيانات المبيعات
const wsSales = XLSX.utils.json_to_sheet(salesHistory.map(s => ({
"التاريخ": s.date,
"الزبون": s.customer || "زبون عام",
"النوع": s.type === 'retail' ? 'مفرق' : 'جملة',
"الإجمالي": s.total,
"الأصناف": s.details ? s.details.map(d => `${d.name}(${d.qty})`).join(' - ') : ""
})));
const wsPurchases = XLSX.utils.json_to_sheet(purchaseHistory.map(p => ({
"التاريخ": p.date,
"المورد": p.supplier,
"رقم الفاتورة": p.invoiceRef,
"الأصناف": p.items ? p.items.map(i => `${i.name}(${i.qty})`).join(' - ') : '',
"قيمة الفاتورة": p.amount,
"الشحن": p.shipping,
"تكاليف إضافية": p.additional,
"الإجمالي": p.total
})));
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, wsInv, "المخزن");
XLSX.utils.book_append_sheet(wb, wsSales, "المبيعات");
XLSX.utils.book_append_sheet(wb, wsPurchases, "المشتريات");
// تنفيذ عملية التحميل
XLSX.writeFile(wb, "تقرير_المتجر.xlsx");
} catch (err) {
console.error(err);
alert("حدث خطأ تقني أثناء التصدير: " + err.message);
}
}
function deleteItem(i) { if (confirm("حذف؟")) { inventory.splice(i, 1); renderData(); } }
// التشغيل الأولي
renderData();
initProductCopyOnDblClick();