Spaces:
Sleeping
Sleeping
Download controller/reportController.js from Mahmoud7456/MultiUsersSalesSystem: direct link, hf CLI and curl.
- Browser
- Download file 40.5 kB
-
https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/controller/reportController.js
- Command line
-
hf download hf://spaces/Mahmoud7456/MultiUsersSalesSystem/controller/reportController.js
-
curl -L -o reportController.js https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/controller/reportController.js
40.5 kB
| import Invoice from "../models/InvoiceModel.js"; | |
| import Expense from "../models/ExpenseModel.js"; | |
| import Income from "../models/IncomeModel.js"; | |
| import Product from "../models/ProductModel.js"; | |
| import Customer from "../models/CustomerModel.js"; | |
| import Supplier from "../models/SupplierModel.js"; | |
| import SupplierInvoice from "../models/SupplierInvoiceModel.js"; | |
| import User from "../models/UserModel.js"; | |
| import CatalogItem from "../models/CatalogItemModel.js"; | |
| import { resolveScopedBranch } from "../utils/branchContext.js"; | |
| const isWithinRange = (value, start, end) => { | |
| const date = new Date(value); | |
| return date >= start && date <= end; | |
| }; | |
| const toNumber = (value) => Number(value || 0); | |
| const paginate = (array, page, limit) => { | |
| const safePage = Math.max(1, parseInt(page) || 1); | |
| const safeLimit = Math.max(1, parseInt(limit) || 5); | |
| const skip = (safePage - 1) * safeLimit; | |
| return { | |
| data: array.slice(skip, skip + safeLimit), | |
| pagination: { | |
| total: array.length, | |
| page: safePage, | |
| limit: safeLimit, | |
| totalPages: Math.ceil(array.length / safeLimit), | |
| }, | |
| }; | |
| }; | |
| const createRange = (req) => { | |
| const end = req.query.end ? new Date(req.query.end) : new Date(); | |
| const start = req.query.start ? new Date(req.query.start) : new Date(end); | |
| if (!req.query.start) { | |
| start.setMonth(start.getMonth() - 1); | |
| } | |
| start.setHours(0, 0, 0, 0); | |
| end.setHours(23, 59, 59, 999); | |
| return { start, end }; | |
| }; | |
| const startOfDay = (value) => { | |
| const date = new Date(value); | |
| date.setHours(0, 0, 0, 0); | |
| return date; | |
| }; | |
| const endOfDay = (value) => { | |
| const date = new Date(value); | |
| date.setHours(23, 59, 59, 999); | |
| return date; | |
| }; | |
| const startOfWeek = (value) => { | |
| const date = startOfDay(value); | |
| const diff = (date.getDay() + 6) % 7; | |
| date.setDate(date.getDate() - diff); | |
| return date; | |
| }; | |
| const endOfWeek = (value) => { | |
| const date = startOfWeek(value); | |
| date.setDate(date.getDate() + 6); | |
| date.setHours(23, 59, 59, 999); | |
| return date; | |
| }; | |
| const startOfMonth = (value) => { | |
| const date = new Date(value); | |
| date.setDate(1); | |
| date.setHours(0, 0, 0, 0); | |
| return date; | |
| }; | |
| const endOfMonth = (value) => { | |
| const date = startOfMonth(value); | |
| date.setMonth(date.getMonth() + 1); | |
| date.setMilliseconds(-1); | |
| return date; | |
| }; | |
| const buildDailyBreakdown = (days, invoices, expenses) => { | |
| const points = []; | |
| for (let i = days - 1; i >= 0; i -= 1) { | |
| const day = new Date(); | |
| day.setDate(day.getDate() - i); | |
| day.setHours(0, 0, 0, 0); | |
| const dayEnd = endOfDay(day); | |
| const sales = invoices | |
| .filter((inv) => isWithinRange(inv.createdAt, day, dayEnd)) | |
| .reduce((sum, inv) => sum + toNumber(inv.totalAmount), 0); | |
| const collections = invoices.reduce((sum, inv) => { | |
| const payments = (inv.payments || []).filter( | |
| (payment) => isWithinRange(payment.date, day, dayEnd) && payment.confirmed !== false | |
| ); | |
| return sum + payments.reduce((acc, payment) => acc + toNumber(payment.amount), 0); | |
| }, 0); | |
| const dayExpenses = expenses | |
| .filter((expense) => isWithinRange(expense.date, day, dayEnd)) | |
| .reduce((sum, expense) => sum + toNumber(expense.amount), 0); | |
| points.push({ | |
| date: day.toISOString(), | |
| label: day.toLocaleDateString("en-US", { month: "short", day: "numeric" }), | |
| sales, | |
| collections, | |
| expenses: dayExpenses, | |
| }); | |
| } | |
| return points; | |
| }; | |
| const aggregateInvoicePayments = (invoices, start, end) => | |
| invoices.reduce((sum, invoice) => { | |
| const payments = (invoice.payments || []).filter( | |
| (payment) => isWithinRange(payment.date, start, end) && payment.confirmed !== false | |
| ); | |
| return sum + payments.reduce((acc, payment) => acc + toNumber(payment.amount), 0); | |
| }, 0); | |
| // βββ Transfer Payment Helpers βββββββββββββββββββββββββββββββββββββββββββββββ | |
| const aggregateCashPayments = (invoices, start, end) => | |
| invoices.reduce((sum, invoice) => { | |
| const payments = (invoice.payments || []).filter( | |
| (payment) => isWithinRange(payment.date, start, end) && payment.method === "cash" | |
| ); | |
| return sum + payments.reduce((acc, payment) => acc + toNumber(payment.amount), 0); | |
| }, 0); | |
| const aggregateTransferPayments = (invoices, start, end, confirmedOnly = false) => | |
| invoices.reduce((sum, invoice) => { | |
| const payments = (invoice.payments || []).filter( | |
| (payment) => | |
| isWithinRange(payment.date, start, end) && | |
| payment.method === "transfer" && | |
| (!confirmedOnly || payment.confirmed) | |
| ); | |
| return sum + payments.reduce((acc, payment) => acc + toNumber(payment.amount), 0); | |
| }, 0); | |
| const getTransferBreakdown = (invoices, start, end) => { | |
| const breakdown = { | |
| instapay: 0, | |
| vodafone_cash: 0, | |
| bank_transfer: 0, | |
| total: 0, | |
| }; | |
| invoices.forEach((invoice) => { | |
| (invoice.payments || []).forEach((payment) => { | |
| if (isWithinRange(payment.date, start, end) && payment.method === "transfer" && payment.confirmed) { | |
| const type = payment.transferType || "bank_transfer"; | |
| if (breakdown[type] !== undefined) { | |
| breakdown[type] += toNumber(payment.amount); | |
| breakdown.total += toNumber(payment.amount); | |
| } | |
| } | |
| }); | |
| }); | |
| return breakdown; | |
| }; | |
| const getPendingTransfers = (invoices, confirmedOnly = false) => { | |
| const pending = []; | |
| invoices.forEach((invoice) => { | |
| (invoice.payments || []).forEach((payment, index) => { | |
| if (payment.method === "transfer" && !payment.confirmed) { | |
| pending.push({ | |
| invoiceId: invoice._id, | |
| invoiceNumber: invoice.invoiceNumber, | |
| paymentIndex: index, | |
| amount: toNumber(payment.amount), | |
| date: payment.date, | |
| transferType: payment.transferType || "bank_transfer", | |
| customerName: invoice.customer?.name || "Walking-in Customer", | |
| customerId: invoice.customer?._id || null, | |
| }); | |
| } | |
| }); | |
| }); | |
| return pending.sort((a, b) => new Date(b.date) - new Date(a.date)); | |
| }; | |
| const getManualIncomes = (incomes) => incomes.filter((income) => income.sourceType !== "invoice_payment"); | |
| const buildRecentPayments = (invoices, start, end) => | |
| invoices | |
| .flatMap((invoice) => | |
| (invoice.payments || []).map((payment) => ({ | |
| amount: toNumber(payment.amount), | |
| date: payment.date, | |
| method: payment.method || "cash", | |
| transferType: payment.transferType || null, | |
| confirmed: payment.confirmed || (payment.method === "cash"), | |
| customerName: invoice.customer?.name || "Walking-in Customer", | |
| customerId: invoice.customer?._id || null, | |
| invoiceNumber: invoice.invoiceNumber, | |
| isWalkIn: Boolean(invoice.customer?.isWalkIn), | |
| })) | |
| ) | |
| .filter((payment) => isWithinRange(payment.date, start, end)) | |
| .sort((a, b) => new Date(b.date) - new Date(a.date)); | |
| const buildSalesSeries = (invoices, mode) => { | |
| const buckets = []; | |
| const now = new Date(); | |
| const steps = mode === "day" ? 14 : 12; | |
| for (let i = steps - 1; i >= 0; i -= 1) { | |
| let bucketStart; | |
| let bucketEnd; | |
| let label; | |
| if (mode === "day") { | |
| bucketStart = startOfDay(now); | |
| bucketStart.setDate(bucketStart.getDate() - i); | |
| bucketEnd = endOfDay(bucketStart); | |
| label = bucketStart.toLocaleDateString("en-US", { month: "short", day: "numeric" }); | |
| } else if (mode === "week") { | |
| bucketStart = startOfWeek(now); | |
| bucketStart.setDate(bucketStart.getDate() - i * 7); | |
| bucketEnd = endOfWeek(bucketStart); | |
| label = `${bucketStart.toLocaleDateString("en-US", { month: "short", day: "numeric" })}`; | |
| } else { | |
| bucketStart = startOfMonth(now); | |
| bucketStart.setMonth(bucketStart.getMonth() - i); | |
| bucketEnd = endOfMonth(bucketStart); | |
| label = bucketStart.toLocaleDateString("en-US", { month: "short", year: "2-digit" }); | |
| } | |
| const totalSales = invoices | |
| .filter((invoice) => isWithinRange(invoice.createdAt, bucketStart, bucketEnd)) | |
| .reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0); | |
| const totalInvoices = invoices.filter((invoice) => isWithinRange(invoice.createdAt, bucketStart, bucketEnd)).length; | |
| buckets.push({ | |
| key: bucketStart.toISOString(), | |
| label, | |
| totalSales, | |
| totalInvoices, | |
| }); | |
| } | |
| return buckets; | |
| }; | |
| const buildBestSellingProducts = (invoices) => { | |
| const products = new Map(); | |
| invoices.forEach((invoice) => { | |
| (invoice.items || []).forEach((item) => { | |
| const key = item.catalogItemId?.toString() || item.productId?.toString() || item.name; | |
| const existing = products.get(key) || { | |
| productId: item.productId || null, | |
| catalogItemId: item.catalogItemId || null, | |
| name: item.name, | |
| quantitySold: 0, | |
| revenue: 0, | |
| averagePrice: 0, | |
| invoicesCount: 0, | |
| type: item.type || "product", | |
| }; | |
| existing.quantitySold += toNumber(item.quantity); | |
| existing.revenue += toNumber(item.total); | |
| existing.invoicesCount += 1; | |
| existing.averagePrice = existing.quantitySold > 0 ? existing.revenue / existing.quantitySold : 0; | |
| products.set(key, existing); | |
| }); | |
| }); | |
| return [...products.values()].sort((a, b) => b.quantitySold - a.quantitySold); | |
| }; | |
| const buildCustomerAging = (invoices) => { | |
| const today = startOfDay(new Date()); | |
| const aging = new Map(); | |
| invoices | |
| .filter((invoice) => toNumber(invoice.remainingAmount) > 0 && !invoice.customer?.isWalkIn) | |
| .forEach((invoice) => { | |
| const customerId = invoice.customer?._id?.toString() || invoice.customer?.toString(); | |
| if (!customerId) { | |
| return; | |
| } | |
| const ageInDays = Math.floor((today - startOfDay(invoice.createdAt)) / (1000 * 60 * 60 * 24)); | |
| const bucket = ageInDays <= 30 ? "current" : ageInDays <= 60 ? "days31To60" : ageInDays <= 90 ? "days61To90" : "over90"; | |
| const entry = aging.get(customerId) || { | |
| customerId, | |
| customerName: invoice.customer?.name || "Unknown customer", | |
| current: 0, | |
| days31To60: 0, | |
| days61To90: 0, | |
| over90: 0, | |
| totalOutstanding: 0, | |
| invoicesCount: 0, | |
| }; | |
| entry[bucket] += toNumber(invoice.remainingAmount); | |
| entry.totalOutstanding += toNumber(invoice.remainingAmount); | |
| entry.invoicesCount += 1; | |
| aging.set(customerId, entry); | |
| }); | |
| return [...aging.values()].sort((a, b) => b.totalOutstanding - a.totalOutstanding); | |
| }; | |
| const buildInventoryInsights = (products, invoices, rangeStart, rangeEnd) => { | |
| const soldUnitsInRange = invoices.reduce( | |
| (sum, invoice) => | |
| sum + | |
| (invoice.items || []).reduce((acc, item) => { | |
| const itemDate = item.date ? new Date(item.date) : new Date(invoice.createdAt); | |
| return isWithinRange(itemDate, rangeStart, rangeEnd) ? acc + toNumber(item.quantity) : acc; | |
| }, 0), | |
| 0 | |
| ); | |
| const soldCostInRange = invoices.reduce( | |
| (sum, invoice) => | |
| sum + | |
| (invoice.items || []).reduce((acc, item) => { | |
| const product = products.find((candidate) => candidate._id.toString() === item.productId?.toString()); | |
| const itemDate = item.date ? new Date(item.date) : new Date(invoice.createdAt); | |
| if (!isWithinRange(itemDate, rangeStart, rangeEnd)) { | |
| return acc; | |
| } | |
| return acc + toNumber(item.quantity) * toNumber(product?.costPrice || 0); | |
| }, 0), | |
| 0 | |
| ); | |
| const inventoryCostValue = products.reduce( | |
| (sum, product) => sum + toNumber(product.stock) * toNumber(product.costPrice || product.price), | |
| 0 | |
| ); | |
| const inventoryRetailValue = products.reduce( | |
| (sum, product) => sum + toNumber(product.stock) * toNumber(product.price), | |
| 0 | |
| ); | |
| const averageInventoryCost = inventoryCostValue + soldCostInRange / 2; | |
| const stockTurnoverRatio = averageInventoryCost > 0 ? soldCostInRange / averageInventoryCost : 0; | |
| const productTurnover = products | |
| .map((product) => { | |
| const soldQuantity = invoices.reduce( | |
| (sum, invoice) => | |
| sum + | |
| (invoice.items || []).reduce((acc, item) => { | |
| const itemDate = item.date ? new Date(item.date) : new Date(invoice.createdAt); | |
| if (!isWithinRange(itemDate, rangeStart, rangeEnd)) { | |
| return acc; | |
| } | |
| return item.productId?.toString() === product._id.toString() ? acc + toNumber(item.quantity) : acc; | |
| }, 0), | |
| 0 | |
| ); | |
| return { | |
| productId: product._id, | |
| name: product.name, | |
| stockOnHand: toNumber(product.stock), | |
| inventoryCostValue: toNumber(product.stock) * toNumber(product.costPrice || product.price), | |
| soldQuantity, | |
| turnoverRatio: toNumber(product.stock) > 0 ? soldQuantity / Math.max(toNumber(product.stock), 1) : soldQuantity, | |
| }; | |
| }) | |
| .sort((a, b) => b.turnoverRatio - a.turnoverRatio); | |
| return { | |
| summary: { | |
| inventoryCostValue, | |
| inventoryRetailValue, | |
| soldUnitsInRange, | |
| soldCostInRange, | |
| stockTurnoverRatio, | |
| }, | |
| products: productTurnover, | |
| }; | |
| }; | |
| export const getDashboardOverview = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { start, end } = createRange(req); | |
| const limit = parseInt(req.query.limit) || 5; | |
| const [invoices, expenses, incomes, products, catalogItems, customers, suppliers, supplierInvoices, users] = await Promise.all([ | |
| Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn phone"), | |
| Expense.find({ tenant: tenantId, ...branchFilter }).sort({ date: -1 }), | |
| Income.find({ tenant: tenantId, ...branchFilter }).sort({ date: -1 }), | |
| Product.find({ tenant: tenantId, ...branchFilter }).sort({ stock: 1, createdAt: -1 }), | |
| CatalogItem.find({ tenant: tenantId, ...branchFilter }).sort({ createdAt: -1 }), | |
| Customer.find({ tenant: tenantId, ...branchFilter, isDeleted: false, isWalkIn: { $ne: true } }).sort({ createdAt: -1 }), | |
| Supplier.find({ tenant: tenantId, ...branchFilter }).sort({ createdAt: -1 }), | |
| SupplierInvoice.find({ tenant: tenantId, ...branchFilter }).populate("supplier", "name"), | |
| User.find({ tenant: tenantId }).sort({ createdAt: -1 }), | |
| ]); | |
| const manualIncomes = getManualIncomes(incomes); | |
| const rangeInvoices = invoices.filter((invoice) => isWithinRange(invoice.createdAt, start, end)); | |
| const rangeExpenses = expenses.filter((expense) => isWithinRange(expense.date, start, end)); | |
| const rangeManualIncomes = manualIncomes.filter((income) => isWithinRange(income.date, start, end)); | |
| const rangeServiceIncomes = incomes.filter( | |
| (income) => income.category === "service_income" && isWithinRange(income.date, start, end) | |
| ); | |
| const rangeCatalogIncomes = incomes.filter( | |
| (income) => income.category === "catalog_sale" && isWithinRange(income.date, start, end) | |
| ); | |
| const salesInRange = rangeInvoices.reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0); | |
| const catalogSalesInRange = rangeInvoices.reduce((sum, invoice) => sum + toNumber(invoice.catalogRevenue), 0); | |
| const taxInRange = rangeInvoices | |
| .filter((invoice) => invoice.restaurantData?.orderType === "dine-in") | |
| .reduce((sum, invoice) => sum + toNumber(invoice.taxAmount || 0), 0); | |
| const deliveryChargesInRange = rangeInvoices | |
| .filter((invoice) => invoice.restaurantData?.orderType === "delivery") | |
| .reduce((sum, invoice) => sum + toNumber(invoice.deliveryCharge || 0), 0); | |
| const collectionsInRange = aggregateInvoicePayments(invoices, start, end); | |
| const cashCollectionsInRange = aggregateCashPayments(invoices, start, end); | |
| const transferCollectionsInRange = aggregateTransferPayments(invoices, start, end, false); | |
| const confirmedTransfersInRange = aggregateTransferPayments(invoices, start, end, true); | |
| const pendingTransfersInRange = transferCollectionsInRange - confirmedTransfersInRange; | |
| const transferBreakdown = getTransferBreakdown(invoices, start, end); | |
| const pendingTransfers = getPendingTransfers(invoices); | |
| const expensesInRange = rangeExpenses.reduce((sum, expense) => sum + toNumber(expense.amount), 0); | |
| const incomeInRange = rangeManualIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0); | |
| const serviceIncomeInRange = rangeServiceIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0); | |
| const catalogIncomeInRange = rangeCatalogIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0); | |
| const outstandingReceivables = invoices.reduce( | |
| (sum, invoice) => sum + (invoice.customer?.isWalkIn ? 0 : toNumber(invoice.remainingAmount)), | |
| 0 | |
| ); | |
| const supplierOutstanding = supplierInvoices.reduce((sum, invoice) => sum + toNumber(invoice.remainingAmount), 0); | |
| const lowStockThresholdDefault = req.user.tenant.settings?.lowStockThreshold || 5; | |
| const lowStockItems = products.filter( | |
| (product) => toNumber(product.stock) <= toNumber(product.lowStockThreshold || lowStockThresholdDefault) | |
| ); | |
| const inventoryValue = products.reduce( | |
| (sum, product) => sum + toNumber(product.stock) * toNumber(product.costPrice || product.price), | |
| 0 | |
| ); | |
| const inventoryRetailValue = products.reduce( | |
| (sum, product) => sum + toNumber(product.stock) * toNumber(product.price), | |
| 0 | |
| ); | |
| const topCustomersMap = invoices.reduce((acc, invoice) => { | |
| const key = invoice.customer?._id?.toString() || "unknown"; | |
| const current = acc.get(key) || { | |
| customerId: invoice.customer?._id || null, | |
| customerName: invoice.customer?.name || "Walking-in Customer", | |
| phone: invoice.customer?.phone || null, | |
| sales: 0, | |
| outstanding: 0, | |
| invoices: 0, | |
| isWalkIn: Boolean(invoice.customer?.isWalkIn), | |
| }; | |
| current.sales += toNumber(invoice.totalAmount); | |
| current.outstanding += invoice.customer?.isWalkIn ? 0 : toNumber(invoice.remainingAmount); | |
| current.invoices += 1; | |
| acc.set(key, current); | |
| return acc; | |
| }, new Map()); | |
| const topCustomersAll = [...topCustomersMap.values()].sort((a, b) => b.sales - a.sales); | |
| const allRecentPayments = buildRecentPayments(invoices, start, end); | |
| const recentIncome = rangeManualIncomes | |
| .sort((a, b) => new Date(b.date) - new Date(a.date)) | |
| .slice(0, 8) | |
| .map((income) => ({ | |
| _id: income._id, | |
| title: income.title, | |
| amount: toNumber(income.amount), | |
| date: income.date, | |
| })); | |
| const allRecentInvoices = [...rangeInvoices] | |
| .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)) | |
| .map((invoice) => ({ | |
| _id: invoice._id, | |
| invoiceNumber: invoice.invoiceNumber, | |
| customerName: invoice.customer?.name || "Walking-in Customer", | |
| totalAmount: toNumber(invoice.totalAmount), | |
| remainingAmount: invoice.customer?.isWalkIn ? 0 : toNumber(invoice.remainingAmount), | |
| status: invoice.status, | |
| createdAt: invoice.createdAt, | |
| isWalkIn: Boolean(invoice.customer?.isWalkIn), | |
| })); | |
| const paginatedLowStock = paginate( | |
| lowStockItems.map((product) => ({ | |
| _id: product._id, | |
| name: product.name, | |
| stock: toNumber(product.stock), | |
| lowStockThreshold: toNumber(product.lowStockThreshold), | |
| price: toNumber(product.price), | |
| unit: product.unit, | |
| })), | |
| req.query.lowStockPage, | |
| limit | |
| ); | |
| res.status(200).json({ | |
| dateRange: { start, end }, | |
| metrics: { | |
| salesInRange, | |
| catalogSalesInRange, | |
| serviceIncomeInRange, | |
| catalogIncomeInRange, | |
| taxInRange, | |
| deliveryChargesInRange, | |
| collectionsInRange, | |
| cashCollectionsInRange, | |
| transferCollectionsInRange, | |
| confirmedTransfersInRange, | |
| pendingTransfersInRange, | |
| incomeInRange, | |
| expensesInRange, | |
| netCashFlow: cashCollectionsInRange + confirmedTransfersInRange + incomeInRange - expensesInRange, | |
| outstandingReceivables, | |
| supplierOutstanding, | |
| customersCount: customers.length, | |
| productsCount: products.length + catalogItems.length, | |
| stockProductsCount: products.length, | |
| catalogItemsCount: catalogItems.length, | |
| suppliersCount: suppliers.length, | |
| usersCount: users.length, | |
| invoicesCount: invoices.length, | |
| invoicesInRange: rangeInvoices.length, | |
| paidInvoicesCount: invoices.filter((invoice) => invoice.status === "paid").length, | |
| partialInvoicesCount: invoices.filter((invoice) => invoice.status === "partial").length, | |
| averageInvoiceValue: invoices.length | |
| ? invoices.reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0) / invoices.length | |
| : 0, | |
| inventoryUnits: products.reduce((sum, product) => sum + toNumber(product.stock), 0), | |
| inventoryValue, | |
| inventoryRetailValue, | |
| lowStockCount: lowStockItems.length, | |
| walkInSalesInRange: rangeInvoices | |
| .filter((invoice) => invoice.customer?.isWalkIn) | |
| .reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0), | |
| }, | |
| transfers: { | |
| breakdown: transferBreakdown, | |
| pendingCount: pendingTransfers.length, | |
| }, | |
| trends: { | |
| last7Days: buildDailyBreakdown(7, invoices, expenses), | |
| }, | |
| lowStockItems: paginatedLowStock, | |
| topCustomers: paginate(topCustomersAll, req.query.customersPage, limit), | |
| recentPayments: paginate(allRecentPayments, req.query.paymentsPage, limit), | |
| pendingTransfers: paginate(pendingTransfers, req.query.transfersPage, limit), | |
| recentInvoices: paginate(allRecentInvoices, req.query.invoicesPage, limit), | |
| recentExpenses: rangeExpenses.slice(0, 8).map((expense) => ({ | |
| _id: expense._id, | |
| title: expense.title, | |
| amount: toNumber(expense.amount), | |
| date: expense.date, | |
| })), | |
| recentIncome, | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| export const getDailyReport = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const limit = parseInt(req.query.limit) || 5; | |
| const todayStart = startOfDay(new Date()); | |
| const todayEnd = endOfDay(new Date()); | |
| const [invoices, expenses, incomes] = await Promise.all([ | |
| Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn phone"), | |
| Expense.find({ tenant: tenantId, ...branchFilter, date: { $gte: todayStart, $lte: todayEnd } }).sort({ date: -1 }), | |
| Income.find({ tenant: tenantId, ...branchFilter, date: { $gte: todayStart, $lte: todayEnd } }).sort({ date: -1 }), | |
| ]); | |
| const manualIncomes = getManualIncomes(incomes); | |
| const dailyPaymentsList = buildRecentPayments(invoices, todayStart, todayEnd); | |
| const totalCashCollected = dailyPaymentsList | |
| .filter((p) => p.confirmed !== false) | |
| .reduce((sum, payment) => sum + toNumber(payment.amount), 0); | |
| const totalSalesToday = invoices | |
| .filter((invoice) => isWithinRange(invoice.createdAt, todayStart, todayEnd)) | |
| .reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0); | |
| const totalTaxToday = invoices | |
| .filter((invoice) => isWithinRange(invoice.createdAt, todayStart, todayEnd) && invoice.restaurantData?.orderType === "dine-in") | |
| .reduce((sum, invoice) => sum + toNumber(invoice.taxAmount || 0), 0); | |
| const totalDeliveryChargesToday = invoices | |
| .filter((invoice) => isWithinRange(invoice.createdAt, todayStart, todayEnd) && invoice.restaurantData?.orderType === "delivery") | |
| .reduce((sum, invoice) => sum + toNumber(invoice.deliveryCharge || 0), 0); | |
| const totalExpenses = expenses.reduce((sum, expense) => sum + toNumber(expense.amount), 0); | |
| const totalIncome = manualIncomes.reduce((sum, income) => sum + toNumber(income.amount), 0); | |
| const totalServiceIncome = incomes | |
| .filter((income) => income.category === "service_income") | |
| .reduce((sum, income) => sum + toNumber(income.amount), 0); | |
| const newInvoicesCount = invoices.filter((invoice) => isWithinRange(invoice.createdAt, todayStart, todayEnd)).length; | |
| res.status(200).json({ | |
| totalCashCollected, | |
| totalSalesToday, | |
| totalTaxToday, | |
| totalDeliveryChargesToday, | |
| totalIncome, | |
| totalServiceIncome, | |
| newInvoicesCount, | |
| totalExpenses, | |
| netCashInDrawer: totalCashCollected + totalIncome + totalServiceIncome - totalExpenses, | |
| recentPayments: paginate(dailyPaymentsList, req.query.paymentsPage, limit), | |
| expensesList: paginate( | |
| expenses.map((expense) => ({ | |
| _id: expense._id, | |
| title: expense.title, | |
| amount: toNumber(expense.amount), | |
| date: expense.date, | |
| })), | |
| req.query.expensesPage, | |
| limit | |
| ), | |
| incomeList: paginate( | |
| manualIncomes.map((income) => ({ | |
| _id: income._id, | |
| title: income.title, | |
| amount: toNumber(income.amount), | |
| date: income.date, | |
| })), | |
| req.query.incomePage, | |
| limit | |
| ), | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| export const getReportAnalytics = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { start, end } = createRange(req); | |
| const [invoices, products] = await Promise.all([ | |
| Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn phone"), | |
| Product.find({ tenant: tenantId, ...branchFilter }).sort({ createdAt: -1 }), | |
| ]); | |
| const rangeInvoices = invoices.filter((invoice) => isWithinRange(invoice.createdAt, start, end)); | |
| const bestSellingProducts = buildBestSellingProducts(rangeInvoices).slice(0, 10); | |
| const customerAging = buildCustomerAging(invoices); | |
| const inventoryInsights = buildInventoryInsights(products, rangeInvoices, start, end); | |
| res.status(200).json({ | |
| dateRange: { start, end }, | |
| salesByPeriod: { | |
| day: buildSalesSeries(invoices, "day"), | |
| week: buildSalesSeries(invoices, "week"), | |
| month: buildSalesSeries(invoices, "month"), | |
| }, | |
| bestSellingProducts, | |
| customerPaymentAging: customerAging, | |
| inventoryInsights, | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| export const getPendingTransfersReport = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const limit = parseInt(req.query.limit) || 10; | |
| const invoices = await Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn phone"); | |
| const pendingTransfers = getPendingTransfers(invoices); | |
| res.status(200).json(paginate(pendingTransfers, req.query.page, limit)); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| // βββ Get transfer payments detailed report ββββββββββββββββββββββββββββββββββ | |
| export const getTransferPaymentsReport = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { start, end } = createRange(req); | |
| const invoices = await Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn phone"); | |
| const allTransfers = []; | |
| invoices.forEach((invoice) => { | |
| (invoice.payments || []).forEach((payment, index) => { | |
| if (payment.method === "transfer" && isWithinRange(payment.date, start, end)) { | |
| allTransfers.push({ | |
| invoiceId: invoice._id, | |
| invoiceNumber: invoice.invoiceNumber, | |
| paymentIndex: index, | |
| amount: toNumber(payment.amount), | |
| date: payment.date, | |
| transferType: payment.transferType || "bank_transfer", | |
| confirmed: payment.confirmed, | |
| customerName: invoice.customer?.name || "Walking-in Customer", | |
| customerId: invoice.customer?._id || null, | |
| confirmedAt: payment.confirmedAt || null, | |
| }); | |
| } | |
| }); | |
| }); | |
| // Calculate breakdown | |
| const breakdown = { | |
| instapay: allTransfers | |
| .filter((t) => t.transferType === "instapay") | |
| .reduce((sum, t) => sum + t.amount, 0), | |
| vodafone_cash: allTransfers | |
| .filter((t) => t.transferType === "vodafone_cash") | |
| .reduce((sum, t) => sum + t.amount, 0), | |
| bank_transfer: allTransfers | |
| .filter((t) => t.transferType === "bank_transfer") | |
| .reduce((sum, t) => sum + t.amount, 0), | |
| }; | |
| breakdown.total = Object.values(breakdown).reduce((sum, val) => sum + val, 0); | |
| const confirmed = allTransfers.filter((t) => t.confirmed); | |
| const pending = allTransfers.filter((t) => !t.confirmed); | |
| res.json({ | |
| dateRange: { start, end }, | |
| summary: { | |
| totalTransfers: allTransfers.length, | |
| totalAmount: breakdown.total, | |
| confirmedAmount: confirmed.reduce((sum, t) => sum + t.amount, 0), | |
| pendingAmount: pending.reduce((sum, t) => sum + t.amount, 0), | |
| confirmedCount: confirmed.length, | |
| pendingCount: pending.length, | |
| }, | |
| breakdown, | |
| transfers: { | |
| all: allTransfers.sort((a, b) => new Date(b.date) - new Date(a.date)), | |
| confirmed: confirmed.sort((a, b) => new Date(b.date) - new Date(a.date)), | |
| pending: pending.sort((a, b) => new Date(b.date) - new Date(a.date)), | |
| }, | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| // βββ Filter payments by method ββββββββββββββββββββββββββββββββββββββββββββββ | |
| export const getPaymentsByMethod = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { method } = req.query; // 'cash' or 'transfer' | |
| const { start, end } = createRange(req); | |
| if (!method || !["cash", "transfer"].includes(method)) { | |
| return res.status(400).json({ message: "Invalid payment method. Use 'cash' or 'transfer'" }); | |
| } | |
| const invoices = await Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn phone"); | |
| const payments = []; | |
| invoices.forEach((invoice) => { | |
| (invoice.payments || []).forEach((payment) => { | |
| if ( | |
| payment.method === method && | |
| isWithinRange(payment.date, start, end) | |
| ) { | |
| payments.push({ | |
| amount: toNumber(payment.amount), | |
| date: payment.date, | |
| method: payment.method, | |
| transferType: payment.transferType || null, | |
| confirmed: payment.confirmed || false, | |
| customerName: invoice.customer?.name || "Walking-in Customer", | |
| customerId: invoice.customer?._id || null, | |
| invoiceNumber: invoice.invoiceNumber, | |
| isWalkIn: Boolean(invoice.customer?.isWalkIn), | |
| }); | |
| } | |
| }); | |
| }); | |
| const totalAmount = payments.reduce((sum, p) => sum + p.amount, 0); | |
| res.json({ | |
| dateRange: { start, end }, | |
| method, | |
| count: payments.length, | |
| totalAmount, | |
| payments: payments.sort((a, b) => new Date(b.date) - new Date(a.date)), | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| // βββ Get customer transfer history ββββββββββββββββββββββββββββββββββββββββββ | |
| export const getCustomerTransferHistory = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { customerId } = req.params; | |
| const invoices = await Invoice.find({ | |
| tenant: tenantId, | |
| ...branchFilter, | |
| customer: customerId, | |
| }).populate("customer", "name isWalkIn phone"); | |
| const transfers = []; | |
| invoices.forEach((invoice) => { | |
| (invoice.payments || []).forEach((payment, index) => { | |
| if (payment.method === "transfer") { | |
| transfers.push({ | |
| invoiceId: invoice._id, | |
| invoiceNumber: invoice.invoiceNumber, | |
| paymentIndex: index, | |
| amount: toNumber(payment.amount), | |
| date: payment.date, | |
| transferType: payment.transferType || "bank_transfer", | |
| confirmed: payment.confirmed, | |
| confirmedAt: payment.confirmedAt || null, | |
| }); | |
| } | |
| }); | |
| }); | |
| const summary = { | |
| totalTransfers: transfers.length, | |
| totalAmount: transfers.reduce((sum, t) => sum + t.amount, 0), | |
| confirmedAmount: transfers | |
| .filter((t) => t.confirmed) | |
| .reduce((sum, t) => sum + t.amount, 0), | |
| pendingAmount: transfers | |
| .filter((t) => !t.confirmed) | |
| .reduce((sum, t) => sum + t.amount, 0), | |
| }; | |
| res.json({ | |
| customerId, | |
| customerName: invoices[0]?.customer?.name || "Unknown", | |
| summary, | |
| transfers: transfers.sort((a, b) => new Date(b.date) - new Date(a.date)), | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |
| // βββ Get transfer statistics βββββββββββββββββββββββββββββββββββββββββββββββ | |
| export const getTransferStatistics = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { start, end } = createRange(req); | |
| const invoices = await Invoice.find({ tenant: tenantId, ...branchFilter }).populate("customer", "name isWalkIn phone"); | |
| // Overall stats | |
| const allTransfers = []; | |
| invoices.forEach((invoice) => { | |
| (invoice.payments || []).forEach((payment) => { | |
| if (payment.method === "transfer") { | |
| allTransfers.push({ | |
| amount: toNumber(payment.amount), | |
| date: payment.date, | |
| transferType: payment.transferType || "bank_transfer", | |
| confirmed: payment.confirmed, | |
| isInRange: isWithinRange(payment.date, start, end), | |
| }); | |
| } | |
| }); | |
| }); | |
| const inRange = allTransfers.filter((t) => t.isInRange); | |
| const inRangeConfirmed = inRange.filter((t) => t.confirmed); | |
| // By transfer type | |
| const byType = { | |
| instapay: { | |
| total: 0, | |
| confirmed: 0, | |
| pending: 0, | |
| count: 0, | |
| avgAmount: 0, | |
| }, | |
| vodafone_cash: { | |
| total: 0, | |
| confirmed: 0, | |
| pending: 0, | |
| count: 0, | |
| avgAmount: 0, | |
| }, | |
| bank_transfer: { | |
| total: 0, | |
| confirmed: 0, | |
| pending: 0, | |
| count: 0, | |
| avgAmount: 0, | |
| }, | |
| }; | |
| inRange.forEach((t) => { | |
| const type = t.transferType; | |
| byType[type].total += t.amount; | |
| byType[type].count += 1; | |
| if (t.confirmed) { | |
| byType[type].confirmed += t.amount; | |
| } else { | |
| byType[type].pending += t.amount; | |
| } | |
| }); | |
| Object.keys(byType).forEach((type) => { | |
| if (byType[type].count > 0) { | |
| byType[type].avgAmount = byType[type].total / byType[type].count; | |
| } | |
| }); | |
| // Daily breakdown (last 7 days) | |
| const dailyBreakdown = {}; | |
| for (let i = 6; i >= 0; i--) { | |
| const date = new Date(end); | |
| date.setDate(date.getDate() - i); | |
| date.setHours(0, 0, 0, 0); | |
| const dateStr = date.toISOString().split("T")[0]; | |
| dailyBreakdown[dateStr] = { | |
| total: 0, | |
| confirmed: 0, | |
| pending: 0, | |
| count: 0, | |
| }; | |
| } | |
| inRange.forEach((t) => { | |
| const dateStr = new Date(t.date).toISOString().split("T")[0]; | |
| if (dailyBreakdown[dateStr]) { | |
| dailyBreakdown[dateStr].total += t.amount; | |
| dailyBreakdown[dateStr].count += 1; | |
| if (t.confirmed) { | |
| dailyBreakdown[dateStr].confirmed += t.amount; | |
| } else { | |
| dailyBreakdown[dateStr].pending += t.amount; | |
| } | |
| } | |
| }); | |
| res.json({ | |
| dateRange: { start, end }, | |
| overview: { | |
| totalTransfers: inRange.length, | |
| totalAmount: inRange.reduce((sum, t) => sum + t.amount, 0), | |
| confirmedAmount: inRangeConfirmed.reduce((sum, t) => sum + t.amount, 0), | |
| pendingAmount: inRange | |
| .filter((t) => !t.confirmed) | |
| .reduce((sum, t) => sum + t.amount, 0), | |
| confirmationRate: inRange.length | |
| ? ((inRangeConfirmed.length / inRange.length) * 100).toFixed(2) | |
| : 0, | |
| }, | |
| byType, | |
| dailyBreakdown, | |
| }); | |
| } catch (error) { | |
| res.status(500).json({ message: error.message }); | |
| } | |
| }; | |