Spaces:
Running
Running
Commit ·
ec62259
1
Parent(s): 385d733
feat: implement business date utility and financial reporting system including expense tracking, platform sales, and profit-loss analysis endpoints
Browse files- src/controllers/expenseController.js +36 -0
- src/controllers/orderController.js +28 -15
- src/controllers/platformSaleController.js +87 -0
- src/controllers/reportController.js +328 -32
- src/models/PlatformSale.js +17 -0
- src/models/Setting.js +11 -0
- src/routes/expenses.js +1 -0
- src/routes/platformSales.js +11 -0
- src/routes/reports.js +3 -0
- src/server.js +2 -0
- src/utils/businessDate.js +86 -0
src/controllers/expenseController.js
CHANGED
|
@@ -31,6 +31,42 @@ exports.createExpense = async (req, res) => {
|
|
| 31 |
res.status(201).json(expense);
|
| 32 |
};
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
// PUT /api/expenses/:id
|
| 35 |
exports.updateExpense = async (req, res) => {
|
| 36 |
const expense = await Expense.findById(req.params.id);
|
|
|
|
| 31 |
res.status(201).json(expense);
|
| 32 |
};
|
| 33 |
|
| 34 |
+
// POST /api/expenses/bulk — create multiple expenses in one go
|
| 35 |
+
exports.createBulkExpenses = async (req, res) => {
|
| 36 |
+
const { expenses, date } = req.body;
|
| 37 |
+
if (!Array.isArray(expenses) || expenses.length === 0) {
|
| 38 |
+
return res.status(400).json({ message: 'Array of expenses is required' });
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
const defaultDate = date ? new Date(date) : new Date();
|
| 42 |
+
const docsToInsert = expenses
|
| 43 |
+
.filter((e) => e.title && e.title.trim() && !isNaN(Number(e.amount)) && Number(e.amount) >= 0)
|
| 44 |
+
.map((e) => ({
|
| 45 |
+
title: e.title.trim(),
|
| 46 |
+
category: e.category || 'Misc',
|
| 47 |
+
amount: Number(e.amount),
|
| 48 |
+
date: e.date ? new Date(e.date) : defaultDate,
|
| 49 |
+
note: e.note || '',
|
| 50 |
+
recurring: Boolean(e.recurring),
|
| 51 |
+
frequency: e.recurring ? e.frequency || 'monthly' : null,
|
| 52 |
+
createdBy: req.user._id,
|
| 53 |
+
}));
|
| 54 |
+
|
| 55 |
+
if (docsToInsert.length === 0) {
|
| 56 |
+
return res.status(400).json({ message: 'No valid expense entries provided' });
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
const created = await Expense.insertMany(docsToInsert);
|
| 60 |
+
const totalAmount = created.reduce((s, e) => s + e.amount, 0);
|
| 61 |
+
|
| 62 |
+
log(req.user, 'BULK_EXPENSE', {
|
| 63 |
+
entity: 'Expense',
|
| 64 |
+
detail: `Added ${created.length} expenses totalling Rs.${totalAmount}`,
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
res.status(201).json({ count: created.length, expenses: created });
|
| 68 |
+
};
|
| 69 |
+
|
| 70 |
// PUT /api/expenses/:id
|
| 71 |
exports.updateExpense = async (req, res) => {
|
| 72 |
const expense = await Expense.findById(req.params.id);
|
src/controllers/orderController.js
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
const Order = require('../models/Order');
|
| 2 |
const { log } = require('../utils/activityLogger');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
// POST /api/orders — create single order
|
| 5 |
exports.createOrder = async (req, res) => {
|
|
@@ -41,7 +47,7 @@ exports.bulkSync = async (req, res) => {
|
|
| 41 |
res.json({ results });
|
| 42 |
};
|
| 43 |
|
| 44 |
-
// GET /api/orders — owner sees all with filters; cashier sees
|
| 45 |
exports.getOrders = async (req, res) => {
|
| 46 |
const isOwner = req.user.role === 'owner';
|
| 47 |
const { from, to, status, orderType, page = 1, limit = 100 } = req.query;
|
|
@@ -53,19 +59,26 @@ exports.getOrders = async (req, res) => {
|
|
| 53 |
if (status) filter.status = status;
|
| 54 |
if (orderType) filter.orderType = orderType;
|
| 55 |
if (from || to) {
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
}
|
| 60 |
} else {
|
| 61 |
-
// Cashier:
|
| 62 |
if (from || to) {
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
} else {
|
| 67 |
-
const
|
| 68 |
-
const end = new Date(); end.setHours(23, 59, 59, 999);
|
| 69 |
filter.createdAt = { $gte: start, $lte: end };
|
| 70 |
}
|
| 71 |
if (status) filter.status = status;
|
|
@@ -109,16 +122,16 @@ exports.voidOrder = async (req, res) => {
|
|
| 109 |
res.json(order);
|
| 110 |
};
|
| 111 |
|
| 112 |
-
// PUT /api/orders/:id/cancel — cashier cancel (
|
| 113 |
exports.cancelOrder = async (req, res) => {
|
| 114 |
const order = await Order.findById(req.params.id);
|
| 115 |
if (!order) return res.status(404).json({ message: 'Order not found' });
|
| 116 |
if (order.status === 'voided') return res.status(400).json({ message: 'Order already cancelled' });
|
| 117 |
|
| 118 |
-
// Cashiers can only cancel
|
| 119 |
-
const
|
| 120 |
-
if (order.createdAt <
|
| 121 |
-
return res.status(403).json({ message: 'Cannot cancel orders from previous
|
| 122 |
}
|
| 123 |
|
| 124 |
order.status = 'voided';
|
|
|
|
| 1 |
const Order = require('../models/Order');
|
| 2 |
const { log } = require('../utils/activityLogger');
|
| 3 |
+
const {
|
| 4 |
+
getBusinessDate,
|
| 5 |
+
getBusinessDayRange,
|
| 6 |
+
getBusinessDateRange,
|
| 7 |
+
getCurrentBusinessDayRange,
|
| 8 |
+
} = require('../utils/businessDate');
|
| 9 |
|
| 10 |
// POST /api/orders — create single order
|
| 11 |
exports.createOrder = async (req, res) => {
|
|
|
|
| 47 |
res.json({ results });
|
| 48 |
};
|
| 49 |
|
| 50 |
+
// GET /api/orders — owner sees all with filters; cashier sees active shift's orders only
|
| 51 |
exports.getOrders = async (req, res) => {
|
| 52 |
const isOwner = req.user.role === 'owner';
|
| 53 |
const { from, to, status, orderType, page = 1, limit = 100 } = req.query;
|
|
|
|
| 59 |
if (status) filter.status = status;
|
| 60 |
if (orderType) filter.orderType = orderType;
|
| 61 |
if (from || to) {
|
| 62 |
+
if (from && to && from === to) {
|
| 63 |
+
const { from: start, to: end } = getBusinessDayRange(from);
|
| 64 |
+
filter.createdAt = { $gte: start, $lte: end };
|
| 65 |
+
} else {
|
| 66 |
+
const { from: start, to: end } = getBusinessDateRange(from, to);
|
| 67 |
+
filter.createdAt = { $gte: start, $lte: end };
|
| 68 |
+
}
|
| 69 |
}
|
| 70 |
} else {
|
| 71 |
+
// Cashier: active business shift orders by default, or specific date range if passed
|
| 72 |
if (from || to) {
|
| 73 |
+
if (from && to && from === to) {
|
| 74 |
+
const { from: start, to: end } = getBusinessDayRange(from);
|
| 75 |
+
filter.createdAt = { $gte: start, $lte: end };
|
| 76 |
+
} else {
|
| 77 |
+
const { from: start, to: end } = getBusinessDateRange(from, to);
|
| 78 |
+
filter.createdAt = { $gte: start, $lte: end };
|
| 79 |
+
}
|
| 80 |
} else {
|
| 81 |
+
const { from: start, to: end } = getCurrentBusinessDayRange();
|
|
|
|
| 82 |
filter.createdAt = { $gte: start, $lte: end };
|
| 83 |
}
|
| 84 |
if (status) filter.status = status;
|
|
|
|
| 122 |
res.json(order);
|
| 123 |
};
|
| 124 |
|
| 125 |
+
// PUT /api/orders/:id/cancel — cashier cancel (current shift's orders only, no PIN required)
|
| 126 |
exports.cancelOrder = async (req, res) => {
|
| 127 |
const order = await Order.findById(req.params.id);
|
| 128 |
if (!order) return res.status(404).json({ message: 'Order not found' });
|
| 129 |
if (order.status === 'voided') return res.status(400).json({ message: 'Order already cancelled' });
|
| 130 |
|
| 131 |
+
// Cashiers can only cancel orders from the active business shift
|
| 132 |
+
const { from: currentShiftStart } = getCurrentBusinessDayRange();
|
| 133 |
+
if (order.createdAt < currentShiftStart) {
|
| 134 |
+
return res.status(403).json({ message: 'Cannot cancel orders from previous shifts. Ask the owner to void it.' });
|
| 135 |
}
|
| 136 |
|
| 137 |
order.status = 'voided';
|
src/controllers/platformSaleController.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const PlatformSale = require('../models/PlatformSale');
|
| 2 |
+
const { log } = require('../utils/activityLogger');
|
| 3 |
+
|
| 4 |
+
// GET /api/platform-sales?month=YYYY-MM or ?from=...&to=...
|
| 5 |
+
exports.getPlatformSales = async (req, res) => {
|
| 6 |
+
const { month, from, to, platform } = req.query;
|
| 7 |
+
const filter = {};
|
| 8 |
+
|
| 9 |
+
if (platform) filter.platform = platform;
|
| 10 |
+
|
| 11 |
+
if (month) {
|
| 12 |
+
const [y, m] = month.split('-').map(Number);
|
| 13 |
+
const start = new Date(y, m - 1, 1, 0, 0, 0, 0);
|
| 14 |
+
const end = new Date(y, m, 0, 23, 59, 59, 999);
|
| 15 |
+
filter.date = { $gte: start, $lte: end };
|
| 16 |
+
} else if (from || to) {
|
| 17 |
+
filter.date = {};
|
| 18 |
+
if (from) filter.date.$gte = new Date(from);
|
| 19 |
+
if (to) filter.date.$lte = new Date(new Date(to).setHours(23, 59, 59, 999));
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
const sales = await PlatformSale.find(filter)
|
| 23 |
+
.populate('createdBy', 'name username')
|
| 24 |
+
.sort({ date: -1 });
|
| 25 |
+
|
| 26 |
+
const total = sales.reduce((s, item) => s + item.amount, 0);
|
| 27 |
+
|
| 28 |
+
res.json({ sales, total });
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
// POST /api/platform-sales
|
| 32 |
+
exports.createPlatformSale = async (req, res) => {
|
| 33 |
+
const { platform = 'Foodpanda', date, amount, note } = req.body;
|
| 34 |
+
if (!date || amount === undefined || isNaN(Number(amount))) {
|
| 35 |
+
return res.status(400).json({ message: 'Date and valid amount are required' });
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
const sale = await PlatformSale.create({
|
| 39 |
+
platform,
|
| 40 |
+
date: new Date(date),
|
| 41 |
+
amount: Number(amount),
|
| 42 |
+
note: note || '',
|
| 43 |
+
createdBy: req.user._id,
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
log(req.user, 'ADD_PLATFORM_SALE', {
|
| 47 |
+
entity: 'PlatformSale',
|
| 48 |
+
entityId: sale._id,
|
| 49 |
+
detail: `${platform} Rs.${sale.amount} (${date})`,
|
| 50 |
+
});
|
| 51 |
+
|
| 52 |
+
res.status(201).json(sale);
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
// PUT /api/platform-sales/:id
|
| 56 |
+
exports.updatePlatformSale = async (req, res) => {
|
| 57 |
+
const sale = await PlatformSale.findById(req.params.id);
|
| 58 |
+
if (!sale) return res.status(404).json({ message: 'Platform sale entry not found' });
|
| 59 |
+
|
| 60 |
+
if (req.body.date) req.body.date = new Date(req.body.date);
|
| 61 |
+
if (req.body.amount !== undefined) req.body.amount = Number(req.body.amount);
|
| 62 |
+
|
| 63 |
+
Object.assign(sale, req.body);
|
| 64 |
+
await sale.save();
|
| 65 |
+
|
| 66 |
+
log(req.user, 'EDIT_PLATFORM_SALE', {
|
| 67 |
+
entity: 'PlatformSale',
|
| 68 |
+
entityId: sale._id,
|
| 69 |
+
detail: `${sale.platform} Rs.${sale.amount}`,
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
res.json(sale);
|
| 73 |
+
};
|
| 74 |
+
|
| 75 |
+
// DELETE /api/platform-sales/:id
|
| 76 |
+
exports.deletePlatformSale = async (req, res) => {
|
| 77 |
+
const sale = await PlatformSale.findByIdAndDelete(req.params.id);
|
| 78 |
+
if (!sale) return res.status(404).json({ message: 'Platform sale entry not found' });
|
| 79 |
+
|
| 80 |
+
log(req.user, 'DELETE_PLATFORM_SALE', {
|
| 81 |
+
entity: 'PlatformSale',
|
| 82 |
+
entityId: sale._id,
|
| 83 |
+
detail: `${sale.platform} Rs.${sale.amount}`,
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
res.json({ message: 'Platform sale entry deleted' });
|
| 87 |
+
};
|
src/controllers/reportController.js
CHANGED
|
@@ -1,27 +1,55 @@
|
|
| 1 |
const Order = require('../models/Order');
|
| 2 |
const Expense = require('../models/Expense');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
// ── Helpers ──────────────────────────────────────────────────
|
| 5 |
|
| 6 |
-
const dayRange = (dateStr) => {
|
| 7 |
-
const d = new Date(dateStr);
|
| 8 |
-
const from = new Date(d.setHours(0, 0, 0, 0));
|
| 9 |
-
const to = new Date(d.setHours(23, 59, 59, 999));
|
| 10 |
-
return { from, to };
|
| 11 |
-
};
|
| 12 |
-
|
| 13 |
const buildOrderFilter = (from, to, extra = {}) => ({
|
| 14 |
status: 'completed',
|
| 15 |
createdAt: { $gte: from, $lte: to },
|
| 16 |
...extra,
|
| 17 |
});
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
// ── Daily Sales Summary ───────────────────────────────────────
|
| 20 |
|
| 21 |
-
// GET /api/reports/daily?date=
|
| 22 |
exports.dailySummary = async (req, res) => {
|
| 23 |
-
const { date
|
| 24 |
-
const { from, to } =
|
| 25 |
|
| 26 |
const orders = await Order.find(buildOrderFilter(from, to));
|
| 27 |
|
|
@@ -34,27 +62,26 @@ exports.dailySummary = async (req, res) => {
|
|
| 34 |
return acc;
|
| 35 |
}, {});
|
| 36 |
|
| 37 |
-
res.json({ date, totalSales, orderCount, avgOrderValue, byType });
|
| 38 |
};
|
| 39 |
|
| 40 |
// ── Date-Range Report ─────────────────────────────────────────
|
| 41 |
|
| 42 |
-
// GET /api/reports/range?from=
|
| 43 |
exports.rangeReport = async (req, res) => {
|
| 44 |
const { from, to } = req.query;
|
| 45 |
if (!from || !to) return res.status(400).json({ message: 'from and to dates required' });
|
| 46 |
|
| 47 |
-
const fromDate
|
| 48 |
-
const toDate = new Date(new Date(to).setHours(23, 59, 59, 999));
|
| 49 |
|
| 50 |
const orders = await Order.find(buildOrderFilter(fromDate, toDate));
|
| 51 |
const totalSales = orders.reduce((s, o) => s + o.netTotal, 0);
|
| 52 |
const orderCount = orders.length;
|
| 53 |
|
| 54 |
-
// Group by day
|
| 55 |
const byDay = {};
|
| 56 |
for (const o of orders) {
|
| 57 |
-
const day = o.createdAt
|
| 58 |
if (!byDay[day]) byDay[day] = { sales: 0, count: 0 };
|
| 59 |
byDay[day].sales += o.netTotal;
|
| 60 |
byDay[day].count += 1;
|
|
@@ -69,10 +96,10 @@ exports.rangeReport = async (req, res) => {
|
|
| 69 |
exports.topItems = async (req, res) => {
|
| 70 |
const { from, to, limit = 10 } = req.query;
|
| 71 |
const matchStage = { status: 'completed' };
|
|
|
|
| 72 |
if (from || to) {
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
if (to) matchStage.createdAt.$lte = new Date(new Date(to).setHours(23, 59, 59, 999));
|
| 76 |
}
|
| 77 |
|
| 78 |
const results = await Order.aggregate([
|
|
@@ -101,15 +128,23 @@ exports.profitLoss = async (req, res) => {
|
|
| 101 |
const { from, to } = req.query;
|
| 102 |
if (!from || !to) return res.status(400).json({ message: 'from and to dates required' });
|
| 103 |
|
| 104 |
-
const fromDate
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
-
const [orders, expenses] = await Promise.all([
|
| 108 |
Order.find(buildOrderFilter(fromDate, toDate)),
|
| 109 |
-
Expense.find({ date: { $gte:
|
|
|
|
| 110 |
]);
|
| 111 |
|
| 112 |
-
const
|
|
|
|
|
|
|
| 113 |
const totalExpenses = expenses.reduce((s, e) => s + e.amount, 0);
|
| 114 |
const netProfit = totalSales - totalExpenses;
|
| 115 |
|
|
@@ -118,22 +153,278 @@ exports.profitLoss = async (req, res) => {
|
|
| 118 |
return acc;
|
| 119 |
}, {});
|
| 120 |
|
| 121 |
-
res.json({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
};
|
| 123 |
|
| 124 |
// ── CSV Export ────────────────────────────────────────────────
|
| 125 |
|
| 126 |
-
// GET /api/reports/export/csv?type=orders|expenses&from=...&to=...
|
| 127 |
exports.exportCSV = async (req, res) => {
|
| 128 |
-
const { type = 'orders', from, to } = req.query;
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
if (type === 'orders') {
|
| 133 |
const orders = await Order.find(buildOrderFilter(fromDate, toDate)).populate('cashier', 'name');
|
| 134 |
const rows = [
|
| 135 |
-
['Date', 'Order Type', 'Items', 'Subtotal', 'Discount', 'Delivery Fee', 'Net Total', 'Cash Received', 'Change', 'Status', 'Cashier'],
|
| 136 |
...orders.map((o) => [
|
|
|
|
| 137 |
o.createdAt.toISOString(),
|
| 138 |
o.orderType,
|
| 139 |
o.items.map((i) => `${i.menuItemName} (${i.variantLabel}) x${i.qty}`).join(' | '),
|
|
@@ -153,7 +444,12 @@ exports.exportCSV = async (req, res) => {
|
|
| 153 |
}
|
| 154 |
|
| 155 |
if (type === 'expenses') {
|
| 156 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
const rows = [
|
| 158 |
['Date', 'Title', 'Category', 'Amount', 'Note', 'Created By'],
|
| 159 |
...expenses.map((e) => [e.date.toISOString().split('T')[0], e.title, e.category, e.amount, e.note, e.createdBy?.name || '']),
|
|
@@ -163,5 +459,5 @@ exports.exportCSV = async (req, res) => {
|
|
| 163 |
return res.send(rows.map((r) => r.join(',')).join('\n'));
|
| 164 |
}
|
| 165 |
|
| 166 |
-
res.status(400).json({ message: 'type must be orders or
|
| 167 |
};
|
|
|
|
| 1 |
const Order = require('../models/Order');
|
| 2 |
const Expense = require('../models/Expense');
|
| 3 |
+
const PlatformSale = require('../models/PlatformSale');
|
| 4 |
+
const Setting = require('../models/Setting');
|
| 5 |
+
const {
|
| 6 |
+
getBusinessDate,
|
| 7 |
+
getBusinessDayRange,
|
| 8 |
+
getBusinessDateRange,
|
| 9 |
+
getCurrentBusinessDayRange,
|
| 10 |
+
} = require('../utils/businessDate');
|
| 11 |
|
| 12 |
// ── Helpers ──────────────────────────────────────────────────
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
const buildOrderFilter = (from, to, extra = {}) => ({
|
| 15 |
status: 'completed',
|
| 16 |
createdAt: { $gte: from, $lte: to },
|
| 17 |
...extra,
|
| 18 |
});
|
| 19 |
|
| 20 |
+
// Default financial report settings
|
| 21 |
+
const DEFAULT_FINANCIAL_SETTINGS = {
|
| 22 |
+
chefSharePercent: 30,
|
| 23 |
+
directorsSharePercent: 70,
|
| 24 |
+
directorCount: 3,
|
| 25 |
+
directorAdjustments: [],
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
// ── Settings Endpoints ────────────────────────────────────────
|
| 29 |
+
|
| 30 |
+
// GET /api/reports/settings
|
| 31 |
+
exports.getSettings = async (req, res) => {
|
| 32 |
+
const doc = await Setting.findOne({ key: 'financial_settings' });
|
| 33 |
+
res.json(doc ? doc.value : DEFAULT_FINANCIAL_SETTINGS);
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
// PUT /api/reports/settings
|
| 37 |
+
exports.updateSettings = async (req, res) => {
|
| 38 |
+
const updatedValue = { ...DEFAULT_FINANCIAL_SETTINGS, ...req.body };
|
| 39 |
+
const doc = await Setting.findOneAndUpdate(
|
| 40 |
+
{ key: 'financial_settings' },
|
| 41 |
+
{ value: updatedValue },
|
| 42 |
+
{ upsert: true, new: true, setDefaultsOnInsert: true }
|
| 43 |
+
);
|
| 44 |
+
res.json(doc.value);
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
// ── Daily Sales Summary ───────────────────────────────────────
|
| 48 |
|
| 49 |
+
// GET /api/reports/daily?date=2026-07-17
|
| 50 |
exports.dailySummary = async (req, res) => {
|
| 51 |
+
const { date } = req.query;
|
| 52 |
+
const { from, to, businessDate } = getBusinessDayRange(date);
|
| 53 |
|
| 54 |
const orders = await Order.find(buildOrderFilter(from, to));
|
| 55 |
|
|
|
|
| 62 |
return acc;
|
| 63 |
}, {});
|
| 64 |
|
| 65 |
+
res.json({ date: businessDate, totalSales, orderCount, avgOrderValue, byType });
|
| 66 |
};
|
| 67 |
|
| 68 |
// ── Date-Range Report ─────────────────────────────────────────
|
| 69 |
|
| 70 |
+
// GET /api/reports/range?from=2026-07-01&to=2026-07-31
|
| 71 |
exports.rangeReport = async (req, res) => {
|
| 72 |
const { from, to } = req.query;
|
| 73 |
if (!from || !to) return res.status(400).json({ message: 'from and to dates required' });
|
| 74 |
|
| 75 |
+
const { from: fromDate, to: toDate } = getBusinessDateRange(from, to);
|
|
|
|
| 76 |
|
| 77 |
const orders = await Order.find(buildOrderFilter(fromDate, toDate));
|
| 78 |
const totalSales = orders.reduce((s, o) => s + o.netTotal, 0);
|
| 79 |
const orderCount = orders.length;
|
| 80 |
|
| 81 |
+
// Group by business day (orders 00:00-05:00 belong to previous day)
|
| 82 |
const byDay = {};
|
| 83 |
for (const o of orders) {
|
| 84 |
+
const day = getBusinessDate(o.createdAt);
|
| 85 |
if (!byDay[day]) byDay[day] = { sales: 0, count: 0 };
|
| 86 |
byDay[day].sales += o.netTotal;
|
| 87 |
byDay[day].count += 1;
|
|
|
|
| 96 |
exports.topItems = async (req, res) => {
|
| 97 |
const { from, to, limit = 10 } = req.query;
|
| 98 |
const matchStage = { status: 'completed' };
|
| 99 |
+
|
| 100 |
if (from || to) {
|
| 101 |
+
const { from: fromDate, to: toDate } = getBusinessDateRange(from, to);
|
| 102 |
+
matchStage.createdAt = { $gte: fromDate, $lte: toDate };
|
|
|
|
| 103 |
}
|
| 104 |
|
| 105 |
const results = await Order.aggregate([
|
|
|
|
| 128 |
const { from, to } = req.query;
|
| 129 |
if (!from || !to) return res.status(400).json({ message: 'from and to dates required' });
|
| 130 |
|
| 131 |
+
const { from: fromDate, to: toDate } = getBusinessDateRange(from, to);
|
| 132 |
+
|
| 133 |
+
// Calendar dates for expenses
|
| 134 |
+
const [fy, fm, fd] = from.split('-').map(Number);
|
| 135 |
+
const expenseFrom = new Date(fy, fm - 1, fd, 0, 0, 0, 0);
|
| 136 |
+
const [ty, tm, td] = to.split('-').map(Number);
|
| 137 |
+
const expenseTo = new Date(ty, tm - 1, td, 23, 59, 59, 999);
|
| 138 |
|
| 139 |
+
const [orders, expenses, platformSales] = await Promise.all([
|
| 140 |
Order.find(buildOrderFilter(fromDate, toDate)),
|
| 141 |
+
Expense.find({ date: { $gte: expenseFrom, $lte: expenseTo } }),
|
| 142 |
+
PlatformSale.find({ date: { $gte: expenseFrom, $lte: expenseTo } }),
|
| 143 |
]);
|
| 144 |
|
| 145 |
+
const posSales = orders.reduce((s, o) => s + o.netTotal, 0);
|
| 146 |
+
const platformTotal = platformSales.reduce((s, p) => s + p.amount, 0);
|
| 147 |
+
const totalSales = posSales + platformTotal;
|
| 148 |
const totalExpenses = expenses.reduce((s, e) => s + e.amount, 0);
|
| 149 |
const netProfit = totalSales - totalExpenses;
|
| 150 |
|
|
|
|
| 153 |
return acc;
|
| 154 |
}, {});
|
| 155 |
|
| 156 |
+
res.json({
|
| 157 |
+
from,
|
| 158 |
+
to,
|
| 159 |
+
posSales,
|
| 160 |
+
platformSales: platformTotal,
|
| 161 |
+
totalSales,
|
| 162 |
+
totalExpenses,
|
| 163 |
+
netProfit,
|
| 164 |
+
expensesByCategory,
|
| 165 |
+
});
|
| 166 |
+
};
|
| 167 |
+
|
| 168 |
+
// ── Monthly Accounting Sheet (Exact Spreadsheet Format) ────────
|
| 169 |
+
|
| 170 |
+
// GET /api/reports/monthly-sheet?month=2026-07
|
| 171 |
+
exports.monthlySheet = async (req, res) => {
|
| 172 |
+
const monthParam = req.query.month || getBusinessDate().substring(0, 7); // "YYYY-MM"
|
| 173 |
+
const [yearStr, monthStr] = monthParam.split('-');
|
| 174 |
+
const year = Number(yearStr);
|
| 175 |
+
const monthNum = Number(monthStr);
|
| 176 |
+
|
| 177 |
+
if (isNaN(year) || isNaN(monthNum) || monthNum < 1 || monthNum > 12) {
|
| 178 |
+
return res.status(400).json({ message: 'Invalid month format, expected YYYY-MM' });
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
// Days in month
|
| 182 |
+
const totalDays = new Date(year, monthNum, 0).getDate();
|
| 183 |
+
|
| 184 |
+
// 1. Business date range for the whole month
|
| 185 |
+
// Month starts on Day 1 at 05:00 AM
|
| 186 |
+
const monthStart = new Date(year, monthNum - 1, 1, 5, 0, 0, 0);
|
| 187 |
+
// Month ends on Day (totalDays + 1) at 04:59:59.999 AM
|
| 188 |
+
const monthEnd = new Date(year, monthNum - 1, totalDays + 1, 4, 59, 59, 999);
|
| 189 |
+
|
| 190 |
+
// Calendar date range for expenses and platform sales
|
| 191 |
+
const calendarStart = new Date(year, monthNum - 1, 1, 0, 0, 0, 0);
|
| 192 |
+
const calendarEnd = new Date(year, monthNum, 0, 23, 59, 59, 999);
|
| 193 |
+
|
| 194 |
+
// 2. Fetch all data in parallel
|
| 195 |
+
const [orders, expenses, platformSales, settingsDoc] = await Promise.all([
|
| 196 |
+
Order.find(buildOrderFilter(monthStart, monthEnd)),
|
| 197 |
+
Expense.find({ date: { $gte: calendarStart, $lte: calendarEnd } }).populate('createdBy', 'name'),
|
| 198 |
+
PlatformSale.find({ date: { $gte: calendarStart, $lte: calendarEnd } }).populate('createdBy', 'name'),
|
| 199 |
+
Setting.findOne({ key: 'financial_settings' }),
|
| 200 |
+
]);
|
| 201 |
+
|
| 202 |
+
const settings = settingsDoc ? settingsDoc.value : DEFAULT_FINANCIAL_SETTINGS;
|
| 203 |
+
|
| 204 |
+
// 3. Aggregate daily POS sales by business date
|
| 205 |
+
const dailySalesMap = {};
|
| 206 |
+
for (const o of orders) {
|
| 207 |
+
const bDate = getBusinessDate(o.createdAt);
|
| 208 |
+
dailySalesMap[bDate] = (dailySalesMap[bDate] || 0) + o.netTotal;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
// 4. Aggregate daily expenses (excluding salaries) and separate salary expenses
|
| 212 |
+
const dailyExpensesMap = {};
|
| 213 |
+
const salaryExpenses = [];
|
| 214 |
+
|
| 215 |
+
for (const e of expenses) {
|
| 216 |
+
if (e.category === 'Salary') {
|
| 217 |
+
salaryExpenses.push({
|
| 218 |
+
_id: e._id,
|
| 219 |
+
title: e.title,
|
| 220 |
+
amount: e.amount,
|
| 221 |
+
date: e.date,
|
| 222 |
+
note: e.note,
|
| 223 |
+
addedBy: e.createdBy?.name || '',
|
| 224 |
+
});
|
| 225 |
+
} else {
|
| 226 |
+
const dayNum = new Date(e.date).getDate();
|
| 227 |
+
const bDate = `${year}-${String(monthNum).padStart(2, '0')}-${String(dayNum).padStart(2, '0')}`;
|
| 228 |
+
dailyExpensesMap[bDate] = (dailyExpensesMap[bDate] || 0) + e.amount;
|
| 229 |
+
}
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
// 5. Build daily rows with running cumulative totals
|
| 233 |
+
let runningSale = 0;
|
| 234 |
+
let runningProfit = 0;
|
| 235 |
+
|
| 236 |
+
const rows = [];
|
| 237 |
+
for (let d = 1; d <= totalDays; d++) {
|
| 238 |
+
const dayPadded = String(d).padStart(2, '0');
|
| 239 |
+
const monthPadded = String(monthNum).padStart(2, '0');
|
| 240 |
+
const dateKey = `${year}-${monthPadded}-${dayPadded}`;
|
| 241 |
+
const displayDate = `${dayPadded}/${monthPadded}`;
|
| 242 |
+
|
| 243 |
+
const exp = dailyExpensesMap[dateKey] || 0;
|
| 244 |
+
const sale = dailySalesMap[dateKey] || 0;
|
| 245 |
+
const profitLoss = sale - exp;
|
| 246 |
+
|
| 247 |
+
runningSale += sale;
|
| 248 |
+
runningProfit += profitLoss;
|
| 249 |
+
|
| 250 |
+
rows.push({
|
| 251 |
+
day: d,
|
| 252 |
+
date: displayDate,
|
| 253 |
+
fullDate: dateKey,
|
| 254 |
+
expenses: exp,
|
| 255 |
+
sale,
|
| 256 |
+
profitLoss,
|
| 257 |
+
totalSale: runningSale,
|
| 258 |
+
totalProfit: runningProfit,
|
| 259 |
+
});
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
// 6. Platform Sales (e.g. Foodpanda)
|
| 263 |
+
const foodpandaTotal = platformSales.reduce((s, p) => s + p.amount, 0);
|
| 264 |
+
|
| 265 |
+
// 7. Subtotal (S. Total)
|
| 266 |
+
const totalDailyExpenses = rows.reduce((s, r) => s + r.expenses, 0);
|
| 267 |
+
const totalDailySales = rows.reduce((s, r) => s + r.sale, 0);
|
| 268 |
+
const subtotalSale = totalDailySales + foodpandaTotal;
|
| 269 |
+
const subtotalExpenses = totalDailyExpenses;
|
| 270 |
+
const subtotalProfit = subtotalSale - subtotalExpenses;
|
| 271 |
+
|
| 272 |
+
// 8. Salaries Total
|
| 273 |
+
const salariesTotal = salaryExpenses.reduce((s, e) => s + e.amount, 0);
|
| 274 |
+
|
| 275 |
+
// 9. Grand Total (G. Total)
|
| 276 |
+
const grandTotalExpenses = subtotalExpenses + salariesTotal;
|
| 277 |
+
const grandTotalSale = subtotalSale;
|
| 278 |
+
const netProfit = grandTotalSale - grandTotalExpenses;
|
| 279 |
+
|
| 280 |
+
// 10. Profit Sharing Calculations
|
| 281 |
+
const chefSharePercent = Number(settings.chefSharePercent) || 30;
|
| 282 |
+
const directorsSharePercent = Number(settings.directorsSharePercent) || 70;
|
| 283 |
+
const directorCount = Number(settings.directorCount) || 3;
|
| 284 |
+
|
| 285 |
+
const chefShare = Math.round((netProfit * chefSharePercent) / 100);
|
| 286 |
+
const directorsShare = netProfit - chefShare;
|
| 287 |
+
const eachDirectorShare = directorCount > 0 ? Math.round(directorsShare / directorCount) : 0;
|
| 288 |
+
|
| 289 |
+
res.json({
|
| 290 |
+
month: monthParam,
|
| 291 |
+
year,
|
| 292 |
+
monthNum,
|
| 293 |
+
monthName: new Date(year, monthNum - 1, 1).toLocaleString('en-US', { month: 'long', year: 'numeric' }),
|
| 294 |
+
rows,
|
| 295 |
+
platformSales: {
|
| 296 |
+
platform: 'Foodpanda',
|
| 297 |
+
entries: platformSales,
|
| 298 |
+
total: foodpandaTotal,
|
| 299 |
+
},
|
| 300 |
+
subtotal: {
|
| 301 |
+
expenses: subtotalExpenses,
|
| 302 |
+
sale: subtotalSale,
|
| 303 |
+
profit: subtotalProfit,
|
| 304 |
+
},
|
| 305 |
+
salaries: {
|
| 306 |
+
entries: salaryExpenses,
|
| 307 |
+
total: salariesTotal,
|
| 308 |
+
},
|
| 309 |
+
grandTotal: {
|
| 310 |
+
expenses: grandTotalExpenses,
|
| 311 |
+
sale: grandTotalSale,
|
| 312 |
+
netProfit,
|
| 313 |
+
},
|
| 314 |
+
profitDistribution: {
|
| 315 |
+
chefSharePercent,
|
| 316 |
+
directorsSharePercent,
|
| 317 |
+
directorCount,
|
| 318 |
+
chefShare,
|
| 319 |
+
directorsShare,
|
| 320 |
+
eachDirectorShare,
|
| 321 |
+
directorAdjustments: settings.directorAdjustments || [],
|
| 322 |
+
},
|
| 323 |
+
});
|
| 324 |
};
|
| 325 |
|
| 326 |
// ── CSV Export ────────────────────────────────────────────────
|
| 327 |
|
| 328 |
+
// GET /api/reports/export/csv?type=orders|expenses|monthly-sheet&from=...&to=...&month=...
|
| 329 |
exports.exportCSV = async (req, res) => {
|
| 330 |
+
const { type = 'orders', from, to, month } = req.query;
|
| 331 |
+
|
| 332 |
+
if (type === 'monthly-sheet') {
|
| 333 |
+
const monthParam = month || getBusinessDate().substring(0, 7);
|
| 334 |
+
const [yStr, mStr] = monthParam.split('-');
|
| 335 |
+
const year = Number(yStr);
|
| 336 |
+
const monthNum = Number(mStr);
|
| 337 |
+
const totalDays = new Date(year, monthNum, 0).getDate();
|
| 338 |
+
|
| 339 |
+
const monthStart = new Date(year, monthNum - 1, 1, 5, 0, 0, 0);
|
| 340 |
+
const monthEnd = new Date(year, monthNum - 1, totalDays + 1, 4, 59, 59, 999);
|
| 341 |
+
const calendarStart = new Date(year, monthNum - 1, 1, 0, 0, 0, 0);
|
| 342 |
+
const calendarEnd = new Date(year, monthNum, 0, 23, 59, 59, 999);
|
| 343 |
+
|
| 344 |
+
const [orders, expenses, platformSales, settingsDoc] = await Promise.all([
|
| 345 |
+
Order.find(buildOrderFilter(monthStart, monthEnd)),
|
| 346 |
+
Expense.find({ date: { $gte: calendarStart, $lte: calendarEnd } }),
|
| 347 |
+
PlatformSale.find({ date: { $gte: calendarStart, $lte: calendarEnd } }),
|
| 348 |
+
Setting.findOne({ key: 'financial_settings' }),
|
| 349 |
+
]);
|
| 350 |
+
|
| 351 |
+
const settings = settingsDoc ? settingsDoc.value : DEFAULT_FINANCIAL_SETTINGS;
|
| 352 |
+
const dailySalesMap = {};
|
| 353 |
+
for (const o of orders) {
|
| 354 |
+
const bDate = getBusinessDate(o.createdAt);
|
| 355 |
+
dailySalesMap[bDate] = (dailySalesMap[bDate] || 0) + o.netTotal;
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
const dailyExpensesMap = {};
|
| 359 |
+
let salariesTotal = 0;
|
| 360 |
+
for (const e of expenses) {
|
| 361 |
+
if (e.category === 'Salary') {
|
| 362 |
+
salariesTotal += e.amount;
|
| 363 |
+
} else {
|
| 364 |
+
const dayNum = new Date(e.date).getDate();
|
| 365 |
+
const bDate = `${year}-${String(monthNum).padStart(2, '0')}-${String(dayNum).padStart(2, '0')}`;
|
| 366 |
+
dailyExpensesMap[bDate] = (dailyExpensesMap[bDate] || 0) + e.amount;
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
const fpTotal = platformSales.reduce((s, p) => s + p.amount, 0);
|
| 371 |
+
|
| 372 |
+
const rows = [
|
| 373 |
+
[`Monthly Report - ${monthParam}`],
|
| 374 |
+
['Date', 'Expenses', 'Sale', 'Profit/Loss', 'Total Sale', 'Total Profit'],
|
| 375 |
+
];
|
| 376 |
+
|
| 377 |
+
let rSale = 0;
|
| 378 |
+
let rProf = 0;
|
| 379 |
+
let totExp = 0;
|
| 380 |
+
let totSale = 0;
|
| 381 |
+
|
| 382 |
+
for (let d = 1; d <= totalDays; d++) {
|
| 383 |
+
const dayP = String(d).padStart(2, '0');
|
| 384 |
+
const monP = String(monthNum).padStart(2, '0');
|
| 385 |
+
const dKey = `${year}-${monP}-${dayP}`;
|
| 386 |
+
const exp = dailyExpensesMap[dKey] || 0;
|
| 387 |
+
const sale = dailySalesMap[dKey] || 0;
|
| 388 |
+
const pl = sale - exp;
|
| 389 |
+
rSale += sale;
|
| 390 |
+
rProf += pl;
|
| 391 |
+
totExp += exp;
|
| 392 |
+
totSale += sale;
|
| 393 |
+
rows.push([`${dayP}/${monP}`, exp, sale, pl, rSale, rProf]);
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
// Platform Sales
|
| 397 |
+
rows.push(['Foodpanda', '', fpTotal, fpTotal, totSale + fpTotal, rProf + fpTotal]);
|
| 398 |
+
// Subtotal
|
| 399 |
+
rows.push(['S. Total', totExp, totSale + fpTotal, (totSale + fpTotal) - totExp, '', '']);
|
| 400 |
+
// Salaries
|
| 401 |
+
rows.push(['Salaries', salariesTotal, '', '', '', '']);
|
| 402 |
+
// Grand Total
|
| 403 |
+
const gNet = (totSale + fpTotal) - (totExp + salariesTotal);
|
| 404 |
+
rows.push(['G. Total', totExp + salariesTotal, totSale + fpTotal, gNet, '', '']);
|
| 405 |
+
|
| 406 |
+
const chefShare = Math.round((gNet * (settings.chefSharePercent || 30)) / 100);
|
| 407 |
+
const dirShare = gNet - chefShare;
|
| 408 |
+
const eachDir = Math.round(dirShare / (settings.directorCount || 3));
|
| 409 |
+
|
| 410 |
+
rows.push([]);
|
| 411 |
+
rows.push(['Share of Chef (30%)', chefShare]);
|
| 412 |
+
rows.push(['Directors Share (70%)', dirShare]);
|
| 413 |
+
rows.push(['Each Director Share', eachDir]);
|
| 414 |
+
|
| 415 |
+
res.setHeader('Content-Type', 'text/csv');
|
| 416 |
+
res.setHeader('Content-Disposition', `attachment; filename="monthly_sheet_${monthParam}.csv"`);
|
| 417 |
+
return res.send(rows.map((r) => r.join(',')).join('\n'));
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
const { from: fromDate, to: toDate } = getBusinessDateRange(from, to);
|
| 421 |
|
| 422 |
if (type === 'orders') {
|
| 423 |
const orders = await Order.find(buildOrderFilter(fromDate, toDate)).populate('cashier', 'name');
|
| 424 |
const rows = [
|
| 425 |
+
['Business Date', 'Created At', 'Order Type', 'Items', 'Subtotal', 'Discount', 'Delivery Fee', 'Net Total', 'Cash Received', 'Change', 'Status', 'Cashier'],
|
| 426 |
...orders.map((o) => [
|
| 427 |
+
getBusinessDate(o.createdAt),
|
| 428 |
o.createdAt.toISOString(),
|
| 429 |
o.orderType,
|
| 430 |
o.items.map((i) => `${i.menuItemName} (${i.variantLabel}) x${i.qty}`).join(' | '),
|
|
|
|
| 444 |
}
|
| 445 |
|
| 446 |
if (type === 'expenses') {
|
| 447 |
+
const [fy, fm, fd] = from ? from.split('-').map(Number) : [1970, 1, 1];
|
| 448 |
+
const [ty, tm, td] = to ? to.split('-').map(Number) : [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()];
|
| 449 |
+
const expStart = new Date(fy, fm - 1, fd, 0, 0, 0, 0);
|
| 450 |
+
const expEnd = new Date(ty, tm - 1, td, 23, 59, 59, 999);
|
| 451 |
+
|
| 452 |
+
const expenses = await Expense.find({ date: { $gte: expStart, $lte: expEnd } }).populate('createdBy', 'name');
|
| 453 |
const rows = [
|
| 454 |
['Date', 'Title', 'Category', 'Amount', 'Note', 'Created By'],
|
| 455 |
...expenses.map((e) => [e.date.toISOString().split('T')[0], e.title, e.category, e.amount, e.note, e.createdBy?.name || '']),
|
|
|
|
| 459 |
return res.send(rows.map((r) => r.join(',')).join('\n'));
|
| 460 |
}
|
| 461 |
|
| 462 |
+
res.status(400).json({ message: 'type must be orders, expenses, or monthly-sheet' });
|
| 463 |
};
|
src/models/PlatformSale.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const mongoose = require('mongoose');
|
| 2 |
+
|
| 3 |
+
const platformSaleSchema = new mongoose.Schema(
|
| 4 |
+
{
|
| 5 |
+
platform: { type: String, default: 'Foodpanda', trim: true }, // e.g. 'Foodpanda', 'Cheetay', etc.
|
| 6 |
+
date: { type: Date, required: true },
|
| 7 |
+
amount: { type: Number, required: true, min: 0 },
|
| 8 |
+
note: { type: String, default: '' },
|
| 9 |
+
createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
|
| 10 |
+
},
|
| 11 |
+
{ timestamps: true }
|
| 12 |
+
);
|
| 13 |
+
|
| 14 |
+
platformSaleSchema.index({ date: -1 });
|
| 15 |
+
platformSaleSchema.index({ platform: 1, date: -1 });
|
| 16 |
+
|
| 17 |
+
module.exports = mongoose.model('PlatformSale', platformSaleSchema);
|
src/models/Setting.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const mongoose = require('mongoose');
|
| 2 |
+
|
| 3 |
+
const settingSchema = new mongoose.Schema(
|
| 4 |
+
{
|
| 5 |
+
key: { type: String, required: true, unique: true },
|
| 6 |
+
value: { type: mongoose.Schema.Types.Mixed, required: true },
|
| 7 |
+
},
|
| 8 |
+
{ timestamps: true }
|
| 9 |
+
);
|
| 10 |
+
|
| 11 |
+
module.exports = mongoose.model('Setting', settingSchema);
|
src/routes/expenses.js
CHANGED
|
@@ -4,6 +4,7 @@ const authGuard = require('../middleware/authGuard');
|
|
| 4 |
const { requireRole } = require('../middleware/roleGuard');
|
| 5 |
|
| 6 |
router.get('/', authGuard, requireRole('owner'), ctrl.getExpenses);
|
|
|
|
| 7 |
router.post('/', authGuard, requireRole('owner'), ctrl.createExpense);
|
| 8 |
router.put('/:id', authGuard, requireRole('owner'), ctrl.updateExpense);
|
| 9 |
router.delete('/:id', authGuard, requireRole('owner'), ctrl.deleteExpense);
|
|
|
|
| 4 |
const { requireRole } = require('../middleware/roleGuard');
|
| 5 |
|
| 6 |
router.get('/', authGuard, requireRole('owner'), ctrl.getExpenses);
|
| 7 |
+
router.post('/bulk', authGuard, requireRole('owner'), ctrl.createBulkExpenses);
|
| 8 |
router.post('/', authGuard, requireRole('owner'), ctrl.createExpense);
|
| 9 |
router.put('/:id', authGuard, requireRole('owner'), ctrl.updateExpense);
|
| 10 |
router.delete('/:id', authGuard, requireRole('owner'), ctrl.deleteExpense);
|
src/routes/platformSales.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const router = require('express').Router();
|
| 2 |
+
const ctrl = require('../controllers/platformSaleController');
|
| 3 |
+
const authGuard = require('../middleware/authGuard');
|
| 4 |
+
const { requireRole } = require('../middleware/roleGuard');
|
| 5 |
+
|
| 6 |
+
router.get('/', authGuard, requireRole('owner'), ctrl.getPlatformSales);
|
| 7 |
+
router.post('/', authGuard, requireRole('owner'), ctrl.createPlatformSale);
|
| 8 |
+
router.put('/:id', authGuard, requireRole('owner'), ctrl.updatePlatformSale);
|
| 9 |
+
router.delete('/:id', authGuard, requireRole('owner'), ctrl.deletePlatformSale);
|
| 10 |
+
|
| 11 |
+
module.exports = router;
|
src/routes/reports.js
CHANGED
|
@@ -7,6 +7,9 @@ router.get('/daily', authGuard, requireRole('owner'), ctrl.dailySummary);
|
|
| 7 |
router.get('/range', authGuard, requireRole('owner'), ctrl.rangeReport);
|
| 8 |
router.get('/top-items', authGuard, requireRole('owner'), ctrl.topItems);
|
| 9 |
router.get('/profit-loss', authGuard, requireRole('owner'), ctrl.profitLoss);
|
|
|
|
|
|
|
|
|
|
| 10 |
router.get('/export/csv', authGuard, requireRole('owner'), ctrl.exportCSV);
|
| 11 |
|
| 12 |
module.exports = router;
|
|
|
|
| 7 |
router.get('/range', authGuard, requireRole('owner'), ctrl.rangeReport);
|
| 8 |
router.get('/top-items', authGuard, requireRole('owner'), ctrl.topItems);
|
| 9 |
router.get('/profit-loss', authGuard, requireRole('owner'), ctrl.profitLoss);
|
| 10 |
+
router.get('/monthly-sheet', authGuard, requireRole('owner'), ctrl.monthlySheet);
|
| 11 |
+
router.get('/settings', authGuard, requireRole('owner'), ctrl.getSettings);
|
| 12 |
+
router.put('/settings', authGuard, requireRole('owner'), ctrl.updateSettings);
|
| 13 |
router.get('/export/csv', authGuard, requireRole('owner'), ctrl.exportCSV);
|
| 14 |
|
| 15 |
module.exports = router;
|
src/server.js
CHANGED
|
@@ -13,6 +13,7 @@ const orderRoutes = require('./routes/orders');
|
|
| 13 |
const expenseRoutes = require('./routes/expenses');
|
| 14 |
const reportRoutes = require('./routes/reports');
|
| 15 |
const userRoutes = require('./routes/users');
|
|
|
|
| 16 |
|
| 17 |
const app = express();
|
| 18 |
|
|
@@ -26,6 +27,7 @@ app.use('/api/auth', authRoutes);
|
|
| 26 |
app.use('/api/menu', menuRoutes);
|
| 27 |
app.use('/api/orders', orderRoutes);
|
| 28 |
app.use('/api/expenses', expenseRoutes);
|
|
|
|
| 29 |
app.use('/api/reports', reportRoutes);
|
| 30 |
app.use('/api/users', userRoutes);
|
| 31 |
|
|
|
|
| 13 |
const expenseRoutes = require('./routes/expenses');
|
| 14 |
const reportRoutes = require('./routes/reports');
|
| 15 |
const userRoutes = require('./routes/users');
|
| 16 |
+
const platformSaleRoutes = require('./routes/platformSales');
|
| 17 |
|
| 18 |
const app = express();
|
| 19 |
|
|
|
|
| 27 |
app.use('/api/menu', menuRoutes);
|
| 28 |
app.use('/api/orders', orderRoutes);
|
| 29 |
app.use('/api/expenses', expenseRoutes);
|
| 30 |
+
app.use('/api/platform-sales', platformSaleRoutes);
|
| 31 |
app.use('/api/reports', reportRoutes);
|
| 32 |
app.use('/api/users', userRoutes);
|
| 33 |
|
src/utils/businessDate.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Business Date Utility for Golden Wok
|
| 3 |
+
* Restaurant night shift rule:
|
| 4 |
+
* Operating day runs from 05:00:00 to 04:59:59.999 the following morning.
|
| 5 |
+
* Any order created between 00:00:00 (midnight) and 04:59:59.999 is counted in the previous calendar day's sales.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
/**
|
| 9 |
+
* Returns the business date string (YYYY-MM-DD) for a given date/timestamp.
|
| 10 |
+
* @param {Date|string|number} [d=new Date()]
|
| 11 |
+
* @returns {string} YYYY-MM-DD
|
| 12 |
+
*/
|
| 13 |
+
function getBusinessDate(d = new Date()) {
|
| 14 |
+
const date = new Date(d);
|
| 15 |
+
if (isNaN(date.getTime())) return new Date().toISOString().split('T')[0];
|
| 16 |
+
|
| 17 |
+
// If before 5 AM (0, 1, 2, 3, 4), roll back 1 calendar day
|
| 18 |
+
if (date.getHours() < 5) {
|
| 19 |
+
date.setDate(date.getDate() - 1);
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
const year = date.getFullYear();
|
| 23 |
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
| 24 |
+
const day = String(date.getDate()).padStart(2, '0');
|
| 25 |
+
return `${year}-${month}-${day}`;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
/**
|
| 29 |
+
* Returns { from, to } Date objects representing the 5:00 AM to 04:59:59.999 AM window for a business date string (YYYY-MM-DD).
|
| 30 |
+
* @param {string} [dateStr] - e.g. "2026-07-01"
|
| 31 |
+
* @returns {{ from: Date, to: Date, businessDate: string }}
|
| 32 |
+
*/
|
| 33 |
+
function getBusinessDayRange(dateStr) {
|
| 34 |
+
const targetDateStr = dateStr && typeof dateStr === 'string' && dateStr.includes('-')
|
| 35 |
+
? dateStr.trim()
|
| 36 |
+
: getBusinessDate();
|
| 37 |
+
|
| 38 |
+
const [y, m, d] = targetDateStr.split('-').map(Number);
|
| 39 |
+
const from = new Date(y, m - 1, d, 5, 0, 0, 0);
|
| 40 |
+
const to = new Date(y, m - 1, d + 1, 4, 59, 59, 999);
|
| 41 |
+
|
| 42 |
+
return { from, to, businessDate: targetDateStr };
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/**
|
| 46 |
+
* Returns { from, to } Date objects for a multi-day business date range.
|
| 47 |
+
* Range starts at 05:00:00 on fromStr and ends at 04:59:59.999 on (toStr + 1 day).
|
| 48 |
+
* @param {string} fromStr - "YYYY-MM-DD"
|
| 49 |
+
* @param {string} toStr - "YYYY-MM-DD"
|
| 50 |
+
* @returns {{ from: Date, to: Date }}
|
| 51 |
+
*/
|
| 52 |
+
function getBusinessDateRange(fromStr, toStr) {
|
| 53 |
+
let from, to;
|
| 54 |
+
|
| 55 |
+
if (fromStr && typeof fromStr === 'string' && fromStr.includes('-')) {
|
| 56 |
+
const [fy, fm, fd] = fromStr.trim().split('-').map(Number);
|
| 57 |
+
from = new Date(fy, fm - 1, fd, 5, 0, 0, 0);
|
| 58 |
+
} else {
|
| 59 |
+
from = new Date(0);
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
if (toStr && typeof toStr === 'string' && toStr.includes('-')) {
|
| 63 |
+
const [ty, tm, td] = toStr.trim().split('-').map(Number);
|
| 64 |
+
to = new Date(ty, tm - 1, td + 1, 4, 59, 59, 999);
|
| 65 |
+
} else {
|
| 66 |
+
to = new Date();
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
return { from, to };
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/**
|
| 73 |
+
* Returns { from, to, businessDate } for the currently active shift.
|
| 74 |
+
* @returns {{ from: Date, to: Date, businessDate: string }}
|
| 75 |
+
*/
|
| 76 |
+
function getCurrentBusinessDayRange() {
|
| 77 |
+
const bizDate = getBusinessDate(new Date());
|
| 78 |
+
return getBusinessDayRange(bizDate);
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
module.exports = {
|
| 82 |
+
getBusinessDate,
|
| 83 |
+
getBusinessDayRange,
|
| 84 |
+
getBusinessDateRange,
|
| 85 |
+
getCurrentBusinessDayRange,
|
| 86 |
+
};
|