MultiUsersSalesSystem / utils /invoiceService.js
Mahmoud7456's picture
Upload 72 files
0330133 verified
Raw History Blame Contribute Delete
5.89 kB
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;
};