import Service from "../models/ServiceModel.js"; import Product from "../models/ProductModel.js"; /** * Validate and process invoice items (products + services) */ export const validateInvoiceItems = async (items, tenantId, branchId) => { if (!Array.isArray(items) || items.length === 0) { throw new Error("يجب إضافة صنف واحد على الأقل"); } const processedItems = []; let hasServices = false; for (const item of items) { if (!item.name || !item.price || !item.quantity) { throw new Error("كل صنف يجب أن يحتوي على اسم وسعر وكمية"); } if (item.type === "service" && item.serviceId) { const service = await Service.findOne({ _id: item.serviceId, tenant: tenantId, isDeleted: false, }); if (!service) throw new Error(`الخدمة غير موجودة: ${item.name}`); hasServices = true; processedItems.push({ ...item, type: "service", serviceId: item.serviceId }); } else if (item.type === "product" && item.productId) { const product = await Product.findOne({ _id: item.productId, tenant: tenantId, branch: branchId, }); if (!product) throw new Error(`المنتج غير موجود: ${item.name}`); if (product.stock < Number(item.quantity)) { throw new Error(`المخزون غير كافٍ للصنف ${item.name}. المتاح: ${product.stock}`); } processedItems.push({ ...item, type: "product", productId: item.productId }); } else if (item.type === "catalog" && item.catalogItemId) { // ✅ new branch const catalogItem = await CatalogItem.findOne({ _id: item.catalogItemId, tenant: tenantId, isActive: true, }); if (!catalogItem) throw new Error(`عنصر الكتالوج غير موجود: ${item.name}`); processedItems.push({ ...item, type: "catalog", catalogItemId: item.catalogItemId }); } else { throw new Error(`نوع الصنف غير صحيح أو معرف مفقود: ${item.name}`); } } return { processedItems, hasServices }; }; /** * Apply items to invoice and update stock for products */ export const applyInvoiceItemsAndStock = async (invoice, items, tenantId, branchId) => { let serviceRevenue = 0; let productRevenue = 0; let catalogRevenue = 0; // ✅ add catalog tracking for (const item of items) { const quantity = Number(item.quantity || 1); const price = Number(item.price || 0); const total = quantity * price; const invoiceItem = { name: item.name, quantity, price, total, type: item.type || "product", date: new Date(), }; if (item.type === "service" && item.serviceId) { invoiceItem.serviceId = item.serviceId; serviceRevenue += total; } else if (item.type === "product" && item.productId) { invoiceItem.productId = item.productId; productRevenue += total; await Product.findOneAndUpdate( { _id: item.productId, tenant: tenantId, branch: branchId }, { $inc: { stock: -quantity } } ); } else if (item.type === "catalog" && item.catalogItemId) { // ✅ new branch invoiceItem.catalogItemId = item.catalogItemId; catalogRevenue += total; } invoice.items.push(invoiceItem); } invoice.serviceRevenue = serviceRevenue; invoice.productRevenue = productRevenue; invoice.catalogRevenue = catalogRevenue; // ✅ now tracked invoice.hasServices = serviceRevenue > 0; }; /** * Create income records for different revenue types */ export const createIncomeRecords = async ({ tenantId, branchId, invoice, customer, userId, date = new Date(), }) => { const incomeRecords = []; if (invoice.serviceRevenue > 0) { incomeRecords.push({ tenant: tenantId, branch: branchId, title: `Service income - ${invoice.invoiceNumber}`, category: "service_income", amount: invoice.serviceRevenue, paymentMethod: "cash", notes: `Service revenue from invoice ${invoice.invoiceNumber}`, sourceType: "invoice_payment", relatedInvoice: invoice._id, relatedCustomer: customer?._id || null, date, createdBy: userId || null, }); } if (invoice.productRevenue > 0) { incomeRecords.push({ tenant: tenantId, branch: branchId, title: `Product sales - ${invoice.invoiceNumber}`, category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment", amount: invoice.productRevenue, paymentMethod: "cash", notes: `Product revenue from invoice ${invoice.invoiceNumber}`, sourceType: "invoice_payment", relatedInvoice: invoice._id, relatedCustomer: customer?._id || null, date, createdBy: userId || null, }); } if (invoice.catalogRevenue > 0) { incomeRecords.push({ tenant: tenantId, branch: branchId, title: `Catalog sales - ${invoice.invoiceNumber}`, category: "catalog_sale", amount: invoice.catalogRevenue, paymentMethod: "cash", notes: `Catalog revenue from invoice ${invoice.invoiceNumber}`, sourceType: "invoice_payment", relatedInvoice: invoice._id, relatedCustomer: customer?._id || null, date, createdBy: userId || null, }); } return incomeRecords; };