File size: 16,381 Bytes
66821dd
 
b5eea9b
66821dd
 
 
 
 
 
8903e5f
 
66821dd
 
 
 
 
 
 
8903e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66821dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8903e5f
66821dd
8903e5f
66821dd
 
 
 
 
 
8903e5f
 
66821dd
8903e5f
 
 
66821dd
 
 
8903e5f
 
66821dd
 
 
 
 
 
 
 
 
 
 
 
 
8903e5f
 
 
 
 
 
 
 
 
66821dd
 
 
 
8903e5f
66821dd
8903e5f
b5eea9b
8903e5f
 
 
b5eea9b
8903e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66821dd
 
8903e5f
b5eea9b
8903e5f
 
 
 
66821dd
8903e5f
66821dd
8903e5f
66821dd
8903e5f
66821dd
 
8903e5f
66821dd
 
8903e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66821dd
8903e5f
 
 
 
 
 
 
 
66821dd
 
8903e5f
66821dd
 
b5eea9b
 
 
 
 
 
 
 
 
 
 
8903e5f
66821dd
 
8903e5f
 
 
 
 
 
 
 
66821dd
 
8903e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66821dd
8903e5f
66821dd
 
 
b5eea9b
66821dd
b5eea9b
66821dd
 
 
 
 
 
 
8903e5f
 
 
 
 
 
66821dd
 
 
 
 
 
 
8903e5f
 
 
 
 
 
 
 
 
66821dd
b5eea9b
66821dd
 
 
 
 
 
8903e5f
 
 
 
 
 
66821dd
 
8903e5f
 
 
66821dd
 
 
 
 
8903e5f
b5eea9b
8903e5f
 
 
 
 
b5eea9b
 
 
 
8903e5f
66821dd
8903e5f
66821dd
 
 
 
 
 
8903e5f
 
66821dd
 
 
 
 
8903e5f
66821dd
 
 
 
 
 
 
8903e5f
 
66821dd
 
 
 
 
 
8903e5f
66821dd
 
 
 
 
 
 
8903e5f
b5eea9b
66821dd
8903e5f
 
 
 
 
 
 
 
 
 
 
 
b5eea9b
 
 
 
 
 
 
 
 
 
66821dd
8903e5f
66821dd
 
 
b5eea9b
66821dd
 
b5eea9b
8903e5f
 
b5eea9b
66821dd
 
 
 
8903e5f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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 });
   }
};