MultiUsersSalesSystem / backend /controller /reportController.js
mahmoud
system update
b5eea9b
Raw History Blame
16.4 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";
// ─── shared helpers ───────────────────────────────────────────────────────────
const isWithinRange = (value, start, end) => {
const date = new Date(value);
return date >= start && date <= end;
};
const toNumber = (value) => Number(value || 0);
/**
* Build a { data, pagination } envelope β€” used everywhere for consistent shape.
*/
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.setDate(start.getDate() - 29);
}
start.setHours(0, 0, 0, 0);
end.setHours(23, 59, 59, 999);
return { start, end };
};
const buildDailyBreakdown = (days, invoices, expenses) => {
const points = [];
for (let i = days - 1; i >= 0; i--) {
const day = new Date();
day.setDate(day.getDate() - i);
day.setHours(0, 0, 0, 0);
const endOfDay = new Date(day);
endOfDay.setHours(23, 59, 59, 999);
const sales = invoices
.filter((inv) => isWithinRange(inv.createdAt, day, endOfDay))
.reduce((sum, inv) => sum + toNumber(inv.totalAmount), 0);
const collections = invoices.reduce((sum, inv) => {
const payments = (inv.payments || []).filter((p) => isWithinRange(p.date, day, endOfDay));
return sum + payments.reduce((s, p) => s + toNumber(p.amount), 0);
}, 0);
const dayExpenses = expenses
.filter((e) => isWithinRange(e.date, day, endOfDay))
.reduce((sum, e) => sum + toNumber(e.amount), 0);
points.push({
date: day.toISOString(),
label: day.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
sales,
collections,
expenses: dayExpenses,
});
}
return points;
};
// ─── GET /reports/overview ────────────────────────────────────────────────────
// Query params supported:
// start, end β€” ISO date strings (default: last 30 days)
// limit β€” rows per page (default: 5)
// lowStockPage
// customersPage
// paymentsPage
// invoicesPage
// ─────────────────────────────────────────────────────────────────────────────
export const getDashboardOverview = async (req, res) => {
try {
const tenantId = req.user.tenant._id;
const { start, end } = createRange(req);
const limit = parseInt(req.query.limit) || 5;
// ── fetch all data in parallel ────────────────────────────────────────
const [invoices, expenses, incomes, products, customers, suppliers, supplierInvoices, users] =
await Promise.all([
Invoice.find({ tenant: tenantId }).populate("customer", "name"),
Expense.find({ tenant: tenantId }).sort({ date: -1 }),
Income.find({ tenant: tenantId }).sort({ date: -1 }),
Product.find({ tenant: tenantId }).sort({ stock: 1, createdAt: -1 }),
Customer.find({ tenant: tenantId }).sort({ createdAt: -1 }),
Supplier.find({ tenant: tenantId }).sort({ createdAt: -1 }),
SupplierInvoice.find({ tenant: tenantId }).populate("supplier", "name"),
User.find({ tenant: tenantId }).sort({ createdAt: -1 }),
]);
// ── date-range filters ────────────────────────────────────────────────
const rangeInvoices = invoices.filter((inv) => isWithinRange(inv.createdAt, start, end));
const rangeExpenses = expenses.filter((exp) => isWithinRange(exp.date, start, end));
// ── aggregate metrics ─────────────────────────────────────────────────
const salesInRange = rangeInvoices.reduce((s, inv) => s + toNumber(inv.totalAmount), 0);
const collectionsInRange = invoices.reduce((sum, inv) => {
const payments = (inv.payments || []).filter((p) => isWithinRange(p.date, start, end));
return sum + payments.reduce((s, p) => s + toNumber(p.amount), 0);
}, 0);
const expensesInRange = rangeExpenses.reduce((s, e) => s + toNumber(e.amount), 0);
const incomeInRange = incomes.filter((inc) => isWithinRange(inc.date, start, end)).reduce((s, inc) => s + toNumber(inc.amount), 0);
const outstandingReceivables = invoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
const supplierOutstanding = supplierInvoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
const lowStockThresholdDefault = req.user.tenant.settings?.lowStockThreshold || 5;
const lowStockItems = products.filter(
(p) => toNumber(p.stock) <= toNumber(p.lowStockThreshold || lowStockThresholdDefault)
);
const inventoryValue = products.reduce(
(s, p) => s + toNumber(p.stock) * toNumber(p.costPrice || p.price), 0
);
const inventoryRetailValue = products.reduce(
(s, p) => s + toNumber(p.stock) * toNumber(p.price), 0
);
// ── top customers (aggregated from invoices) ──────────────────────────
const topCustomersMap = invoices.reduce((acc, inv) => {
const key = inv.customer?._id?.toString() || "unknown";
const current = acc.get(key) || {
customerId: inv.customer?._id || null,
customerName: inv.customer?.name || "Walk-in customer",
sales: 0,
outstanding: 0,
invoices: 0,
};
current.sales += toNumber(inv.totalAmount);
current.outstanding += toNumber(inv.remainingAmount);
current.invoices += 1;
acc.set(key, current);
return acc;
}, new Map());
const topCustomersAll = [...topCustomersMap.values()].sort((a, b) => b.sales - a.sales);
// ── recent payments (within range, sorted newest first) ───────────────
const allRecentPayments = invoices
.flatMap((inv) =>
(inv.payments || []).map((p) => ({
amount: toNumber(p.amount),
date: p.date,
method: p.method || "cash",
customerName: inv.customer?.name || "Walk-in customer",
customerId: inv.customer?._id || null,
invoiceNumber: inv.invoiceNumber,
}))
)
.filter((p) => isWithinRange(p.date, start, end))
.sort((a, b) => new Date(b.date) - new Date(a.date));
const recentIncome = incomes
.filter((inc) => isWithinRange(inc.date, start, end))
.sort((a, b) => new Date(b.date) - new Date(a.date))
.slice(0, 8)
.map((inc) => ({
_id: inc._id,
title: inc.title,
amount: toNumber(inc.amount),
date: inc.date,
}));
// ── recent invoices (within range, sorted newest first) ───────────────
const allRecentInvoices = [...rangeInvoices]
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
.map((inv) => ({
_id: inv._id,
invoiceNumber: inv.invoiceNumber,
customerName: inv.customer?.name || "Walk-in customer",
totalAmount: toNumber(inv.totalAmount),
remainingAmount: toNumber(inv.remainingAmount),
status: inv.status,
createdAt: inv.createdAt,
}));
// ── paginate ──────────────────────────────────────────────────────────
const paginatedLowStock = paginate(lowStockItems.map((p) => ({
_id: p._id,
name: p.name,
stock: toNumber(p.stock),
lowStockThreshold: toNumber(p.lowStockThreshold),
price: toNumber(p.price),
unit: p.unit,
})), req.query.lowStockPage, limit);
const paginatedTopCustomers = paginate(topCustomersAll, req.query.customersPage, limit);
const paginatedPayments = paginate(allRecentPayments, req.query.paymentsPage, limit);
const paginatedInvoices = paginate(allRecentInvoices, req.query.invoicesPage, limit);
// ── respond ───────────────────────────────────────────────────────────
res.status(200).json({
dateRange: { start, end },
metrics: {
salesInRange,
collectionsInRange,
incomeInRange,
expensesInRange,
netCashFlow: collectionsInRange + incomeInRange - expensesInRange,
outstandingReceivables,
supplierOutstanding,
customersCount: customers.length,
suppliersCount: suppliers.length,
usersCount: users.length,
invoicesCount: invoices.length,
invoicesInRange: rangeInvoices.length,
paidInvoicesCount: invoices.filter((i) => i.status === "paid").length,
partialInvoicesCount: invoices.filter((i) => i.status === "partial").length,
averageInvoiceValue: invoices.length
? invoices.reduce((s, i) => s + toNumber(i.totalAmount), 0) / invoices.length
: 0,
inventoryUnits: products.reduce((s, p) => s + toNumber(p.stock), 0),
inventoryValue,
inventoryRetailValue,
lowStockCount: lowStockItems.length,
},
trends: {
last7Days: buildDailyBreakdown(7, invoices, expenses),
},
lowStockItems: paginatedLowStock,
topCustomers: paginatedTopCustomers,
recentPayments: paginatedPayments,
recentInvoices: paginatedInvoices,
recentExpenses: rangeExpenses.slice(0, 8).map((e) => ({
_id: e._id,
title: e.title,
amount: toNumber(e.amount),
date: e.date,
})),
recentIncome,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// ─── GET /reports/daily ───────────────────────────────────────────────────────
// Query params supported:
// limit β€” rows per page (default: 5)
// paymentsPage β€” page for recentPayments
// expensesPage β€” page for expensesList
// ─────────────────────────────────────────────────────────────────────────────
export const getDailyReport = async (req, res) => {
try {
const tenantId = req.user.tenant._id;
const limit = parseInt(req.query.limit) || 5;
const startOfDay = new Date();
startOfDay.setHours(0, 0, 0, 0);
const endOfDay = new Date();
endOfDay.setHours(23, 59, 59, 999);
// ── fetch ─────────────────────────────────────────────────────────────
const [invoices, expenses, incomes] = await Promise.all([
Invoice.find({ tenant: tenantId }).populate("customer", "name"),
Expense.find({
tenant: tenantId,
date: { $gte: startOfDay, $lte: endOfDay },
}).sort({ date: -1 }),
Income.find({
tenant: tenantId,
date: { $gte: startOfDay, $lte: endOfDay },
}).sort({ date: -1 }),
]);
// ── aggregate ─────────────────────────────────────────────────────────
let totalCashCollected = 0;
let totalSalesToday = 0;
let newInvoicesCount = 0;
const dailyPaymentsList = [];
invoices.forEach((invoice) => {
// cash collected today
(invoice.payments || []).forEach((payment) => {
if (isWithinRange(payment.date, startOfDay, endOfDay)) {
totalCashCollected += toNumber(payment.amount);
dailyPaymentsList.push({
amount: toNumber(payment.amount),
date: payment.date,
method: payment.method || "cash",
customerName: invoice.customer?.name || "Deleted customer",
customerId: invoice.customer?._id || null,
invoiceNumber: invoice.invoiceNumber,
});
}
});
// sales (items sold today)
(invoice.items || []).forEach((item) => {
const itemDate = item.date ? new Date(item.date) : new Date(invoice.createdAt);
if (isWithinRange(itemDate, startOfDay, endOfDay)) {
totalSalesToday += toNumber(item.total);
}
});
// new invoices created today
if (isWithinRange(invoice.createdAt, startOfDay, endOfDay)) {
newInvoicesCount += 1;
}
});
dailyPaymentsList.sort((a, b) => new Date(b.date) - new Date(a.date));
const totalExpenses = expenses.reduce((s, e) => s + toNumber(e.amount), 0);
const totalIncome = incomes.reduce((s, inc) => s + toNumber(inc.amount), 0);
// ── paginate both lists ───────────────────────────────────────────────
const paginatedPayments = paginate(dailyPaymentsList, req.query.paymentsPage, limit);
const paginatedExpenses = paginate(
expenses.map((e) => ({
_id: e._id,
title: e.title,
amount: toNumber(e.amount),
date: e.date,
})),
req.query.expensesPage,
limit
);
const paginatedIncome = paginate(
incomes.map((inc) => ({
_id: inc._id,
title: inc.title,
amount: toNumber(inc.amount),
date: inc.date,
})),
req.query.incomePage,
limit
);
// ── respond ───────────────────────────────────────────────────────────
res.status(200).json({
totalCashCollected,
totalSalesToday,
totalIncome,
newInvoicesCount,
totalExpenses,
netCashInDrawer: totalCashCollected + totalIncome - totalExpenses,
recentPayments: paginatedPayments, // { data: [...], pagination: {...} }
expensesList: paginatedExpenses, // { data: [...], pagination: {...} }
incomeList: paginatedIncome,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};