mahmoud commited on
Commit
8903e5f
ยท
1 Parent(s): 66821dd

add some updates

Browse files
backend/.dockerignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ node_modules
2
+ npm-debug.log
3
+ Dockerfile
4
+ .dockerignore
5
+ .env
backend/.env CHANGED
@@ -1,5 +1,5 @@
1
  PORT = 5000
2
  NODE_ENV = development
3
- DB_URL=mongodb://127.0.0.1:27017/sales_system
4
- # DB_URL=mongodb+srv://mahmoudshalaby:SNipxrdETGSJWVw0@salsesmultiuserscluster.rv1c8at.mongodb.net/Sales_MultiUsers_DB
5
- FRONTEND_URL=http://localhost:5173
 
1
  PORT = 5000
2
  NODE_ENV = development
3
+ # DB_URL=mongodb://127.0.0.1:27017/sales_system
4
+ DB_URL=mongodb+srv://mahmoudshalaby:SNipxrdETGSJWVw0@salsesmultiuserscluster.rv1c8at.mongodb.net/Sales_MultiUsers_DB
5
+ FRONTEND_URL= https://salessystem-tau.vercel.app
backend/Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Node.js LTS version
2
+ FROM node:20-alpine
3
+
4
+ # Set working directory
5
+ WORKDIR /app
6
+
7
+ # Copy package.json and package-lock.json first for caching
8
+ COPY package*.json ./
9
+
10
+ # Install dependencies
11
+ RUN npm install --production
12
+
13
+ # Copy the rest of your code
14
+ COPY . .
15
+
16
+ # Set environment variable for port (Railway will provide it)
17
+ ENV PORT=5000
18
+
19
+ # Expose port (Railway uses the container's port)
20
+ EXPOSE 5000
21
+
22
+ # Command to run your app
23
+ CMD ["node", "index.js"]
backend/controller/customerController.js CHANGED
@@ -127,14 +127,36 @@ export const getCustomerById = async (req, res) => {
127
  return res.status(404).json({ message: "Customer not found" });
128
  }
129
 
130
- const invoice = await Invoice.findOne({
 
 
 
 
 
 
 
131
  customer: customer._id,
132
  tenant: req.user.tenant._id,
133
  });
134
 
 
 
 
 
 
 
 
 
 
135
  res.status(200).json({
136
  ...customer.toObject(),
137
- invoice,
 
 
 
 
 
 
138
  });
139
  } catch (error) {
140
  res.status(500).json({ message: error.message });
 
127
  return res.status(404).json({ message: "Customer not found" });
128
  }
129
 
130
+ // Pagination & Sorting
131
+ const page = parseInt(req.query.page) || 1;
132
+ const limit = parseInt(req.query.limit) || 5;
133
+ const sortField = req.query.sortField || "createdAt";
134
+ const sortOrder = req.query.sortOrder === "asc" ? 1 : -1;
135
+ const skip = (page - 1) * limit;
136
+
137
+ const totalInvoices = await Invoice.countDocuments({
138
  customer: customer._id,
139
  tenant: req.user.tenant._id,
140
  });
141
 
142
+ const invoices = await Invoice.find({
143
+ customer: customer._id,
144
+ tenant: req.user.tenant._id,
145
+ })
146
+ .populate("items.productId", "name price")
147
+ .sort({ [sortField]: sortOrder })
148
+ .skip(skip)
149
+ .limit(limit);
150
+
151
  res.status(200).json({
152
  ...customer.toObject(),
153
+ invoices,
154
+ pagination: {
155
+ total: totalInvoices,
156
+ page,
157
+ limit,
158
+ totalPages: Math.ceil(totalInvoices / limit),
159
+ },
160
  });
161
  } catch (error) {
162
  res.status(500).json({ message: error.message });
backend/controller/invoiceController.js CHANGED
@@ -1,10 +1,17 @@
1
  import Invoice from "../models/InvoiceModel.js";
2
- import Product from "../models/ProductModel.js";
3
  import Customer from "../models/CustomerModel.js";
 
 
4
 
 
5
  const generateInvoiceNumber = async (tenantId) => {
6
- const count = await Invoice.countDocuments({ tenant: tenantId });
7
- return `INV-${String(count + 1).padStart(5, "0")}`;
 
 
 
 
 
8
  };
9
 
10
  export const addItemToInvoice = async (req, res) => {
@@ -12,24 +19,22 @@ export const addItemToInvoice = async (req, res) => {
12
  const { customerId } = req.params;
13
  const { items } = req.body;
14
  const tenantId = req.user.tenant?._id;
15
- if (!tenantId) {
16
- return res.status(403).json({ message: "No tenant associated with this account" });
17
- }
18
- if (!Array.isArray(items) || items.length === 0) {
19
  return res.status(400).json({ message: "At least one item is required" });
20
- }
21
 
22
  const customer = await Customer.findOne({ _id: customerId, tenant: tenantId });
23
- if (!customer) {
24
- return res.status(404).json({ message: "Customer not found" });
25
- }
26
 
 
27
  let invoice = await Invoice.findOne({
28
  customer: customerId,
29
  tenant: tenantId,
30
  status: { $in: ["open", "partial"] },
31
  });
32
 
 
33
  if (!invoice) {
34
  invoice = new Invoice({
35
  tenant: tenantId,
@@ -39,20 +44,19 @@ export const addItemToInvoice = async (req, res) => {
39
  });
40
  }
41
 
 
42
  for (const item of items) {
43
  if (item.productId) {
44
  const product = await Product.findOne({ _id: item.productId, tenant: tenantId });
45
- if (!product) {
46
- return res.status(404).json({ message: `Product not found: ${item.name}` });
47
- }
48
- if (product.stock < Number(item.quantity)) {
49
  return res.status(400).json({
50
  message: `Not enough stock for ${item.name}. Available: ${product.stock}`,
51
  });
52
- }
53
  }
54
  }
55
 
 
56
  for (const item of items) {
57
  const quantity = Number(item.quantity || 0);
58
  const price = Number(item.price || 0);
@@ -73,15 +77,16 @@ export const addItemToInvoice = async (req, res) => {
73
  );
74
  }
75
  }
 
 
76
  await invoice.save();
77
  res.status(200).json(invoice);
78
  } catch (err) {
79
- console.log('โŒ ERROR:', err.message);
80
- console.log('โŒ STACK:', err.stack);
81
  res.status(500).json({ message: err.message });
82
  }
83
  };
84
-
85
  export const getInvoices = async (req, res) => {
86
  try {
87
  const page = parseInt(req.query.page) || 1;
@@ -137,7 +142,10 @@ export const getInvoiceById = async (req, res) => {
137
  tenant: req.user.tenant._id,
138
  })
139
  .populate("customer", "name")
140
- .populate("items");
 
 
 
141
 
142
  if (!invoice) {
143
  return res.status(404).json({ message: "Invoice not found" });
 
1
  import Invoice from "../models/InvoiceModel.js";
 
2
  import Customer from "../models/CustomerModel.js";
3
+ import Product from "../models/ProductModel.js";
4
+ import Counter from "../models/CounterModel.js";
5
 
6
+ // Safe invoice number generator
7
  const generateInvoiceNumber = async (tenantId) => {
8
+ const counter = await Counter.findOneAndUpdate(
9
+ { tenant: tenantId },
10
+ { $inc: { invoiceNumber: 1 } },
11
+ { new: true, upsert: true }
12
+ );
13
+
14
+ return `INV-${String(counter.invoiceNumber).padStart(5, "0")}`;
15
  };
16
 
17
  export const addItemToInvoice = async (req, res) => {
 
19
  const { customerId } = req.params;
20
  const { items } = req.body;
21
  const tenantId = req.user.tenant?._id;
22
+
23
+ if (!tenantId) return res.status(403).json({ message: "No tenant associated with this account" });
24
+ if (!Array.isArray(items) || items.length === 0)
 
25
  return res.status(400).json({ message: "At least one item is required" });
 
26
 
27
  const customer = await Customer.findOne({ _id: customerId, tenant: tenantId });
28
+ if (!customer) return res.status(404).json({ message: "Customer not found" });
 
 
29
 
30
+ // Find open/partial invoice
31
  let invoice = await Invoice.findOne({
32
  customer: customerId,
33
  tenant: tenantId,
34
  status: { $in: ["open", "partial"] },
35
  });
36
 
37
+ // If no invoice exists, create new with safe invoice number
38
  if (!invoice) {
39
  invoice = new Invoice({
40
  tenant: tenantId,
 
44
  });
45
  }
46
 
47
+ // Check stock availability
48
  for (const item of items) {
49
  if (item.productId) {
50
  const product = await Product.findOne({ _id: item.productId, tenant: tenantId });
51
+ if (!product) return res.status(404).json({ message: `Product not found: ${item.name}` });
52
+ if (product.stock < Number(item.quantity))
 
 
53
  return res.status(400).json({
54
  message: `Not enough stock for ${item.name}. Available: ${product.stock}`,
55
  });
 
56
  }
57
  }
58
 
59
+ // Add items to invoice and update stock
60
  for (const item of items) {
61
  const quantity = Number(item.quantity || 0);
62
  const price = Number(item.price || 0);
 
77
  );
78
  }
79
  }
80
+
81
+ // Save invoice with updated totals
82
  await invoice.save();
83
  res.status(200).json(invoice);
84
  } catch (err) {
85
+ console.log("โŒ ERROR:", err.message);
86
+ console.log("โŒ STACK:", err.stack);
87
  res.status(500).json({ message: err.message });
88
  }
89
  };
 
90
  export const getInvoices = async (req, res) => {
91
  try {
92
  const page = parseInt(req.query.page) || 1;
 
142
  tenant: req.user.tenant._id,
143
  })
144
  .populate("customer", "name")
145
+ .populate({
146
+ path: "items.productId",
147
+ select: "name price", // fields from Product you want
148
+ });
149
 
150
  if (!invoice) {
151
  return res.status(404).json({ message: "Invoice not found" });
backend/controller/reportController.js CHANGED
@@ -6,6 +6,8 @@ import Supplier from "../models/SupplierModel.js";
6
  import SupplierInvoice from "../models/SupplierInvoiceModel.js";
7
  import User from "../models/UserModel.js";
8
 
 
 
9
  const isWithinRange = (value, start, end) => {
10
  const date = new Date(value);
11
  return date >= start && date <= end;
@@ -13,6 +15,24 @@ const isWithinRange = (value, start, end) => {
13
 
14
  const toNumber = (value) => Number(value || 0);
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  const createRange = (req) => {
17
  const end = req.query.end ? new Date(req.query.end) : new Date();
18
  const start = req.query.start ? new Date(req.query.start) : new Date(end);
@@ -30,26 +50,26 @@ const createRange = (req) => {
30
  const buildDailyBreakdown = (days, invoices, expenses) => {
31
  const points = [];
32
 
33
- for (let index = days - 1; index >= 0; index -= 1) {
34
  const day = new Date();
35
- day.setDate(day.getDate() - index);
36
  day.setHours(0, 0, 0, 0);
37
 
38
  const endOfDay = new Date(day);
39
  endOfDay.setHours(23, 59, 59, 999);
40
 
41
  const sales = invoices
42
- .filter((invoice) => isWithinRange(invoice.createdAt, day, endOfDay))
43
- .reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0);
44
 
45
- const collections = invoices.reduce((sum, invoice) => {
46
- const payments = invoice.payments?.filter((payment) => isWithinRange(payment.date, day, endOfDay)) || [];
47
- return sum + payments.reduce((paymentSum, payment) => paymentSum + toNumber(payment.amount), 0);
48
  }, 0);
49
 
50
  const dayExpenses = expenses
51
- .filter((expense) => isWithinRange(expense.date, day, endOfDay))
52
- .reduce((sum, expense) => sum + toNumber(expense.amount), 0);
53
 
54
  points.push({
55
  date: day.toISOString(),
@@ -63,121 +83,125 @@ const buildDailyBreakdown = (days, invoices, expenses) => {
63
  return points;
64
  };
65
 
 
 
 
 
 
 
 
 
 
66
  export const getDashboardOverview = async (req, res) => {
67
  try {
68
  const tenantId = req.user.tenant._id;
69
  const { start, end } = createRange(req);
 
70
 
71
- const [invoices, expenses, products, customers, suppliers, supplierInvoices, users] = await Promise.all([
72
- Invoice.find({ tenant: tenantId }).populate("customer", "name"),
73
- Expense.find({ tenant: tenantId }).sort({ date: -1 }),
74
- Product.find({ tenant: tenantId }).sort({ stock: 1, createdAt: -1 }),
75
- Customer.find({ tenant: tenantId }).sort({ createdAt: -1 }),
76
- Supplier.find({ tenant: tenantId }).sort({ createdAt: -1 }),
77
- SupplierInvoice.find({ tenant: tenantId }).populate("supplier", "name"),
78
- User.find({ tenant: tenantId }).sort({ createdAt: -1 }),
79
- ]);
80
-
81
- const rangeInvoices = invoices.filter((invoice) => isWithinRange(invoice.createdAt, start, end));
82
- const rangeExpenses = expenses.filter((expense) => isWithinRange(expense.date, start, end));
83
-
84
- const collectionsInRange = invoices.reduce((sum, invoice) => {
85
- const payments = invoice.payments?.filter((payment) => isWithinRange(payment.date, start, end)) || [];
86
- return sum + payments.reduce((paymentSum, payment) => paymentSum + toNumber(payment.amount), 0);
 
 
 
 
 
 
87
  }, 0);
88
 
89
- const salesInRange = rangeInvoices.reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0);
90
- const expensesInRange = rangeExpenses.reduce((sum, expense) => sum + toNumber(expense.amount), 0);
91
- const outstandingReceivables = invoices.reduce((sum, invoice) => sum + toNumber(invoice.remainingAmount), 0);
92
- const supplierOutstanding = supplierInvoices.reduce(
93
- (sum, invoice) => sum + toNumber(invoice.remainingAmount),
94
- 0
95
- );
96
  const lowStockItems = products.filter(
97
- (product) => toNumber(product.stock) <= toNumber(product.lowStockThreshold || req.user.tenant.settings?.lowStockThreshold || 5)
98
  );
 
99
  const inventoryValue = products.reduce(
100
- (sum, product) => sum + toNumber(product.stock) * toNumber(product.costPrice || product.price),
101
- 0
102
  );
103
  const inventoryRetailValue = products.reduce(
104
- (sum, product) => sum + toNumber(product.stock) * toNumber(product.price),
105
- 0
106
  );
107
 
108
- const topCustomers = invoices
109
- .reduce((accumulator, invoice) => {
110
- const key = invoice.customer?._id?.toString() || invoice.customer?.toString() || "unknown";
111
- const current = accumulator.get(key) || {
112
- customerId: invoice.customer?._id || null,
113
- customerName: invoice.customer?.name || "Walk-in customer",
114
- sales: 0,
115
- outstanding: 0,
116
- invoices: 0,
117
- };
118
-
119
- current.sales += toNumber(invoice.totalAmount);
120
- current.outstanding += toNumber(invoice.remainingAmount);
121
- current.invoices += 1;
122
- accumulator.set(key, current);
123
- return accumulator;
124
- }, new Map());
125
-
126
- const limit = parseInt(req.query.limit) || 5;
127
- const lowStockPage = parseInt(req.query.lowStockPage) || 1;
128
- const customersPage = parseInt(req.query.customersPage) || 1;
129
- const paymentsPage = parseInt(req.query.paymentsPage) || 1;
130
- const invoicesPage = parseInt(req.query.invoicesPage) || 1;
131
-
132
- const lowStockSkip = (lowStockPage - 1) * limit;
133
- const paginatedLowStockItems = lowStockItems.slice(lowStockSkip, lowStockSkip + limit).map((product) => ({
134
- _id: product._id,
135
- name: product.name,
136
- stock: toNumber(product.stock),
137
- lowStockThreshold: toNumber(product.lowStockThreshold),
138
- price: toNumber(product.price),
139
- unit: product.unit,
140
- }));
141
-
142
- const topCustomersArray = [...topCustomers.values()].sort((a, b) => b.sales - a.sales);
143
- const customersSkip = (customersPage - 1) * limit;
144
- const paginatedTopCustomers = topCustomersArray.slice(customersSkip, customersSkip + limit);
145
-
146
  const allRecentPayments = invoices
147
- .flatMap((invoice) =>
148
- (invoice.payments || []).map((payment) => ({
149
- amount: toNumber(payment.amount),
150
- date: payment.date,
151
- method: payment.method || "cash",
152
- customerName: invoice.customer?.name || "Walk-in customer",
153
- customerId: invoice.customer?._id || null,
154
- invoiceNumber: invoice.invoiceNumber,
155
  }))
156
  )
157
- .filter((payment) => isWithinRange(payment.date, start, end))
158
  .sort((a, b) => new Date(b.date) - new Date(a.date));
159
- const paymentsSkip = (paymentsPage - 1) * limit;
160
- const paginatedRecentPayments = allRecentPayments.slice(paymentsSkip, paymentsSkip + limit);
161
 
 
162
  const allRecentInvoices = [...rangeInvoices]
163
  .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
164
- .map((invoice) => ({
165
- _id: invoice._id,
166
- invoiceNumber: invoice.invoiceNumber,
167
- customerName: invoice.customer?.name || "Walk-in customer",
168
- totalAmount: toNumber(invoice.totalAmount),
169
- remainingAmount: toNumber(invoice.remainingAmount),
170
- status: invoice.status,
171
- createdAt: invoice.createdAt,
172
  }));
173
- const invoicesSkip = (invoicesPage - 1) * limit;
174
- const paginatedRecentInvoices = allRecentInvoices.slice(invoicesSkip, invoicesSkip + limit);
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  res.status(200).json({
177
- dateRange: {
178
- start,
179
- end,
180
- },
181
  metrics: {
182
  salesInRange,
183
  collectionsInRange,
@@ -190,10 +214,12 @@ export const getDashboardOverview = async (req, res) => {
190
  usersCount: users.length,
191
  invoicesCount: invoices.length,
192
  invoicesInRange: rangeInvoices.length,
193
- paidInvoicesCount: invoices.filter((invoice) => invoice.status === "paid").length,
194
- partialInvoicesCount: invoices.filter((invoice) => invoice.status === "partial").length,
195
- averageInvoiceValue: invoices.length ? invoices.reduce((sum, invoice) => sum + toNumber(invoice.totalAmount), 0) / invoices.length : 0,
196
- inventoryUnits: products.reduce((sum, product) => sum + toNumber(product.stock), 0),
 
 
197
  inventoryValue,
198
  inventoryRetailValue,
199
  lowStockCount: lowStockItems.length,
@@ -201,27 +227,15 @@ export const getDashboardOverview = async (req, res) => {
201
  trends: {
202
  last7Days: buildDailyBreakdown(7, invoices, expenses),
203
  },
204
- lowStockItems: {
205
- data: paginatedLowStockItems,
206
- pagination: { total: lowStockItems.length, page: lowStockPage, limit, totalPages: Math.ceil(lowStockItems.length / limit) }
207
- },
208
- topCustomers: {
209
- data: paginatedTopCustomers,
210
- pagination: { total: topCustomersArray.length, page: customersPage, limit, totalPages: Math.ceil(topCustomersArray.length / limit) }
211
- },
212
- recentInvoices: {
213
- data: paginatedRecentInvoices,
214
- pagination: { total: allRecentInvoices.length, page: invoicesPage, limit, totalPages: Math.ceil(allRecentInvoices.length / limit) }
215
- },
216
- recentPayments: {
217
- data: paginatedRecentPayments,
218
- pagination: { total: allRecentPayments.length, page: paymentsPage, limit, totalPages: Math.ceil(allRecentPayments.length / limit) }
219
- },
220
- recentExpenses: rangeExpenses.slice(0, 8).map((expense) => ({
221
- _id: expense._id,
222
- title: expense.title,
223
- amount: toNumber(expense.amount),
224
- date: expense.date,
225
  })),
226
  });
227
  } catch (error) {
@@ -229,28 +243,46 @@ export const getDashboardOverview = async (req, res) => {
229
  }
230
  };
231
 
 
 
 
 
 
 
232
  export const getDailyReport = async (req, res) => {
233
  try {
 
 
 
234
  const startOfDay = new Date();
235
  startOfDay.setHours(0, 0, 0, 0);
236
-
237
  const endOfDay = new Date();
238
  endOfDay.setHours(23, 59, 59, 999);
239
 
240
- const invoices = await Invoice.find({ tenant: req.user.tenant._id }).populate("customer", "name");
 
 
 
 
 
 
 
241
 
 
242
  let totalCashCollected = 0;
243
  let totalSalesToday = 0;
244
  let newInvoicesCount = 0;
245
  const dailyPaymentsList = [];
246
 
247
  invoices.forEach((invoice) => {
248
- invoice.payments?.forEach((payment) => {
 
249
  if (isWithinRange(payment.date, startOfDay, endOfDay)) {
250
  totalCashCollected += toNumber(payment.amount);
251
  dailyPaymentsList.push({
252
  amount: toNumber(payment.amount),
253
  date: payment.date,
 
254
  customerName: invoice.customer?.name || "Deleted customer",
255
  customerId: invoice.customer?._id || null,
256
  invoiceNumber: invoice.invoiceNumber,
@@ -258,13 +290,15 @@ export const getDailyReport = async (req, res) => {
258
  }
259
  });
260
 
261
- invoice.items?.forEach((item) => {
 
262
  const itemDate = item.date ? new Date(item.date) : new Date(invoice.createdAt);
263
  if (isWithinRange(itemDate, startOfDay, endOfDay)) {
264
  totalSalesToday += toNumber(item.total);
265
  }
266
  });
267
 
 
268
  if (isWithinRange(invoice.createdAt, startOfDay, endOfDay)) {
269
  newInvoicesCount += 1;
270
  }
@@ -272,23 +306,32 @@ export const getDailyReport = async (req, res) => {
272
 
273
  dailyPaymentsList.sort((a, b) => new Date(b.date) - new Date(a.date));
274
 
275
- const expenses = await Expense.find({
276
- tenant: req.user.tenant._id,
277
- date: { $gte: startOfDay, $lte: endOfDay },
278
- }).sort({ date: -1 });
279
 
280
- const totalExpenses = expenses.reduce((sum, expense) => sum + toNumber(expense.amount), 0);
 
 
 
 
 
 
 
 
 
 
 
281
 
 
282
  res.status(200).json({
283
  totalCashCollected,
284
  totalSalesToday,
285
  newInvoicesCount,
286
- recentPayments: dailyPaymentsList,
287
- expensesList: expenses,
288
  totalExpenses,
289
  netCashInDrawer: totalCashCollected - totalExpenses,
 
 
290
  });
291
  } catch (error) {
292
  res.status(500).json({ message: error.message });
293
  }
294
- };
 
6
  import SupplierInvoice from "../models/SupplierInvoiceModel.js";
7
  import User from "../models/UserModel.js";
8
 
9
+ // โ”€โ”€โ”€ shared helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
10
+
11
  const isWithinRange = (value, start, end) => {
12
  const date = new Date(value);
13
  return date >= start && date <= end;
 
15
 
16
  const toNumber = (value) => Number(value || 0);
17
 
18
+ /**
19
+ * Build a { data, pagination } envelope โ€” used everywhere for consistent shape.
20
+ */
21
+ const paginate = (array, page, limit) => {
22
+ const safePage = Math.max(1, parseInt(page) || 1);
23
+ const safeLimit = Math.max(1, parseInt(limit) || 5);
24
+ const skip = (safePage - 1) * safeLimit;
25
+ return {
26
+ data: array.slice(skip, skip + safeLimit),
27
+ pagination: {
28
+ total: array.length,
29
+ page: safePage,
30
+ limit: safeLimit,
31
+ totalPages: Math.ceil(array.length / safeLimit),
32
+ },
33
+ };
34
+ };
35
+
36
  const createRange = (req) => {
37
  const end = req.query.end ? new Date(req.query.end) : new Date();
38
  const start = req.query.start ? new Date(req.query.start) : new Date(end);
 
50
  const buildDailyBreakdown = (days, invoices, expenses) => {
51
  const points = [];
52
 
53
+ for (let i = days - 1; i >= 0; i--) {
54
  const day = new Date();
55
+ day.setDate(day.getDate() - i);
56
  day.setHours(0, 0, 0, 0);
57
 
58
  const endOfDay = new Date(day);
59
  endOfDay.setHours(23, 59, 59, 999);
60
 
61
  const sales = invoices
62
+ .filter((inv) => isWithinRange(inv.createdAt, day, endOfDay))
63
+ .reduce((sum, inv) => sum + toNumber(inv.totalAmount), 0);
64
 
65
+ const collections = invoices.reduce((sum, inv) => {
66
+ const payments = (inv.payments || []).filter((p) => isWithinRange(p.date, day, endOfDay));
67
+ return sum + payments.reduce((s, p) => s + toNumber(p.amount), 0);
68
  }, 0);
69
 
70
  const dayExpenses = expenses
71
+ .filter((e) => isWithinRange(e.date, day, endOfDay))
72
+ .reduce((sum, e) => sum + toNumber(e.amount), 0);
73
 
74
  points.push({
75
  date: day.toISOString(),
 
83
  return points;
84
  };
85
 
86
+ // โ”€โ”€โ”€ GET /reports/overview โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
87
+ // Query params supported:
88
+ // start, end โ€” ISO date strings (default: last 30 days)
89
+ // limit โ€” rows per page (default: 5)
90
+ // lowStockPage
91
+ // customersPage
92
+ // paymentsPage
93
+ // invoicesPage
94
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
95
  export const getDashboardOverview = async (req, res) => {
96
  try {
97
  const tenantId = req.user.tenant._id;
98
  const { start, end } = createRange(req);
99
+ const limit = parseInt(req.query.limit) || 5;
100
 
101
+ // โ”€โ”€ fetch all data in parallel โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
102
+ const [invoices, expenses, products, customers, suppliers, supplierInvoices, users] =
103
+ await Promise.all([
104
+ Invoice.find({ tenant: tenantId }).populate("customer", "name"),
105
+ Expense.find({ tenant: tenantId }).sort({ date: -1 }),
106
+ Product.find({ tenant: tenantId }).sort({ stock: 1, createdAt: -1 }),
107
+ Customer.find({ tenant: tenantId }).sort({ createdAt: -1 }),
108
+ Supplier.find({ tenant: tenantId }).sort({ createdAt: -1 }),
109
+ SupplierInvoice.find({ tenant: tenantId }).populate("supplier", "name"),
110
+ User.find({ tenant: tenantId }).sort({ createdAt: -1 }),
111
+ ]);
112
+
113
+ // โ”€โ”€ date-range filters โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
114
+ const rangeInvoices = invoices.filter((inv) => isWithinRange(inv.createdAt, start, end));
115
+ const rangeExpenses = expenses.filter((exp) => isWithinRange(exp.date, start, end));
116
+
117
+ // โ”€โ”€ aggregate metrics โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
118
+ const salesInRange = rangeInvoices.reduce((s, inv) => s + toNumber(inv.totalAmount), 0);
119
+
120
+ const collectionsInRange = invoices.reduce((sum, inv) => {
121
+ const payments = (inv.payments || []).filter((p) => isWithinRange(p.date, start, end));
122
+ return sum + payments.reduce((s, p) => s + toNumber(p.amount), 0);
123
  }, 0);
124
 
125
+ const expensesInRange = rangeExpenses.reduce((s, e) => s + toNumber(e.amount), 0);
126
+ const outstandingReceivables = invoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
127
+ const supplierOutstanding = supplierInvoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
128
+
129
+ const lowStockThresholdDefault = req.user.tenant.settings?.lowStockThreshold || 5;
 
 
130
  const lowStockItems = products.filter(
131
+ (p) => toNumber(p.stock) <= toNumber(p.lowStockThreshold || lowStockThresholdDefault)
132
  );
133
+
134
  const inventoryValue = products.reduce(
135
+ (s, p) => s + toNumber(p.stock) * toNumber(p.costPrice || p.price), 0
 
136
  );
137
  const inventoryRetailValue = products.reduce(
138
+ (s, p) => s + toNumber(p.stock) * toNumber(p.price), 0
 
139
  );
140
 
141
+ // โ”€โ”€ top customers (aggregated from invoices) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
142
+ const topCustomersMap = invoices.reduce((acc, inv) => {
143
+ const key = inv.customer?._id?.toString() || "unknown";
144
+ const current = acc.get(key) || {
145
+ customerId: inv.customer?._id || null,
146
+ customerName: inv.customer?.name || "Walk-in customer",
147
+ sales: 0,
148
+ outstanding: 0,
149
+ invoices: 0,
150
+ };
151
+ current.sales += toNumber(inv.totalAmount);
152
+ current.outstanding += toNumber(inv.remainingAmount);
153
+ current.invoices += 1;
154
+ acc.set(key, current);
155
+ return acc;
156
+ }, new Map());
157
+
158
+ const topCustomersAll = [...topCustomersMap.values()].sort((a, b) => b.sales - a.sales);
159
+
160
+ // โ”€โ”€ recent payments (within range, sorted newest first) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  const allRecentPayments = invoices
162
+ .flatMap((inv) =>
163
+ (inv.payments || []).map((p) => ({
164
+ amount: toNumber(p.amount),
165
+ date: p.date,
166
+ method: p.method || "cash",
167
+ customerName: inv.customer?.name || "Walk-in customer",
168
+ customerId: inv.customer?._id || null,
169
+ invoiceNumber: inv.invoiceNumber,
170
  }))
171
  )
172
+ .filter((p) => isWithinRange(p.date, start, end))
173
  .sort((a, b) => new Date(b.date) - new Date(a.date));
 
 
174
 
175
+ // โ”€โ”€ recent invoices (within range, sorted newest first) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
176
  const allRecentInvoices = [...rangeInvoices]
177
  .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
178
+ .map((inv) => ({
179
+ _id: inv._id,
180
+ invoiceNumber: inv.invoiceNumber,
181
+ customerName: inv.customer?.name || "Walk-in customer",
182
+ totalAmount: toNumber(inv.totalAmount),
183
+ remainingAmount: toNumber(inv.remainingAmount),
184
+ status: inv.status,
185
+ createdAt: inv.createdAt,
186
  }));
 
 
187
 
188
+ // โ”€โ”€ paginate โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
189
+ const paginatedLowStock = paginate(lowStockItems.map((p) => ({
190
+ _id: p._id,
191
+ name: p.name,
192
+ stock: toNumber(p.stock),
193
+ lowStockThreshold: toNumber(p.lowStockThreshold),
194
+ price: toNumber(p.price),
195
+ unit: p.unit,
196
+ })), req.query.lowStockPage, limit);
197
+
198
+ const paginatedTopCustomers = paginate(topCustomersAll, req.query.customersPage, limit);
199
+ const paginatedPayments = paginate(allRecentPayments, req.query.paymentsPage, limit);
200
+ const paginatedInvoices = paginate(allRecentInvoices, req.query.invoicesPage, limit);
201
+
202
+ // โ”€โ”€ respond โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
203
  res.status(200).json({
204
+ dateRange: { start, end },
 
 
 
205
  metrics: {
206
  salesInRange,
207
  collectionsInRange,
 
214
  usersCount: users.length,
215
  invoicesCount: invoices.length,
216
  invoicesInRange: rangeInvoices.length,
217
+ paidInvoicesCount: invoices.filter((i) => i.status === "paid").length,
218
+ partialInvoicesCount: invoices.filter((i) => i.status === "partial").length,
219
+ averageInvoiceValue: invoices.length
220
+ ? invoices.reduce((s, i) => s + toNumber(i.totalAmount), 0) / invoices.length
221
+ : 0,
222
+ inventoryUnits: products.reduce((s, p) => s + toNumber(p.stock), 0),
223
  inventoryValue,
224
  inventoryRetailValue,
225
  lowStockCount: lowStockItems.length,
 
227
  trends: {
228
  last7Days: buildDailyBreakdown(7, invoices, expenses),
229
  },
230
+ lowStockItems: paginatedLowStock,
231
+ topCustomers: paginatedTopCustomers,
232
+ recentPayments: paginatedPayments,
233
+ recentInvoices: paginatedInvoices,
234
+ recentExpenses: rangeExpenses.slice(0, 8).map((e) => ({
235
+ _id: e._id,
236
+ title: e.title,
237
+ amount: toNumber(e.amount),
238
+ date: e.date,
 
 
 
 
 
 
 
 
 
 
 
 
239
  })),
240
  });
241
  } catch (error) {
 
243
  }
244
  };
245
 
246
+ // โ”€โ”€โ”€ GET /reports/daily โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
247
+ // Query params supported:
248
+ // limit โ€” rows per page (default: 5)
249
+ // paymentsPage โ€” page for recentPayments
250
+ // expensesPage โ€” page for expensesList
251
+ // โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
252
  export const getDailyReport = async (req, res) => {
253
  try {
254
+ const tenantId = req.user.tenant._id;
255
+ const limit = parseInt(req.query.limit) || 5;
256
+
257
  const startOfDay = new Date();
258
  startOfDay.setHours(0, 0, 0, 0);
 
259
  const endOfDay = new Date();
260
  endOfDay.setHours(23, 59, 59, 999);
261
 
262
+ // โ”€โ”€ fetch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
263
+ const [invoices, expenses] = await Promise.all([
264
+ Invoice.find({ tenant: tenantId }).populate("customer", "name"),
265
+ Expense.find({
266
+ tenant: tenantId,
267
+ date: { $gte: startOfDay, $lte: endOfDay },
268
+ }).sort({ date: -1 }),
269
+ ]);
270
 
271
+ // โ”€โ”€ aggregate โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
272
  let totalCashCollected = 0;
273
  let totalSalesToday = 0;
274
  let newInvoicesCount = 0;
275
  const dailyPaymentsList = [];
276
 
277
  invoices.forEach((invoice) => {
278
+ // cash collected today
279
+ (invoice.payments || []).forEach((payment) => {
280
  if (isWithinRange(payment.date, startOfDay, endOfDay)) {
281
  totalCashCollected += toNumber(payment.amount);
282
  dailyPaymentsList.push({
283
  amount: toNumber(payment.amount),
284
  date: payment.date,
285
+ method: payment.method || "cash",
286
  customerName: invoice.customer?.name || "Deleted customer",
287
  customerId: invoice.customer?._id || null,
288
  invoiceNumber: invoice.invoiceNumber,
 
290
  }
291
  });
292
 
293
+ // sales (items sold today)
294
+ (invoice.items || []).forEach((item) => {
295
  const itemDate = item.date ? new Date(item.date) : new Date(invoice.createdAt);
296
  if (isWithinRange(itemDate, startOfDay, endOfDay)) {
297
  totalSalesToday += toNumber(item.total);
298
  }
299
  });
300
 
301
+ // new invoices created today
302
  if (isWithinRange(invoice.createdAt, startOfDay, endOfDay)) {
303
  newInvoicesCount += 1;
304
  }
 
306
 
307
  dailyPaymentsList.sort((a, b) => new Date(b.date) - new Date(a.date));
308
 
309
+ const totalExpenses = expenses.reduce((s, e) => s + toNumber(e.amount), 0);
 
 
 
310
 
311
+ // โ”€โ”€ paginate both lists โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
312
+ const paginatedPayments = paginate(dailyPaymentsList, req.query.paymentsPage, limit);
313
+ const paginatedExpenses = paginate(
314
+ expenses.map((e) => ({
315
+ _id: e._id,
316
+ title: e.title,
317
+ amount: toNumber(e.amount),
318
+ date: e.date,
319
+ })),
320
+ req.query.expensesPage,
321
+ limit
322
+ );
323
 
324
+ // โ”€โ”€ respond โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
325
  res.status(200).json({
326
  totalCashCollected,
327
  totalSalesToday,
328
  newInvoicesCount,
 
 
329
  totalExpenses,
330
  netCashInDrawer: totalCashCollected - totalExpenses,
331
+ recentPayments: paginatedPayments, // { data: [...], pagination: {...} }
332
+ expensesList: paginatedExpenses, // { data: [...], pagination: {...} }
333
  });
334
  } catch (error) {
335
  res.status(500).json({ message: error.message });
336
  }
337
+ };
backend/index.js CHANGED
@@ -17,11 +17,20 @@ dotenv.config();
17
  const app = express();
18
  dbConnection();
19
 
20
- const allowedOrigin = process.env.FRONTEND_URL || 'http://localhost:5173';
 
 
 
21
 
22
  app.use(cors({
23
- origin: allowedOrigin,
24
- credentials: true,
 
 
 
 
 
 
25
  }));
26
 
27
  app.use(compression());
 
17
  const app = express();
18
  dbConnection();
19
 
20
+ const allowedOrigins = [
21
+ 'https://salessystem-tau.vercel.app',
22
+ 'http://localhost:5173'
23
+ ];
24
 
25
  app.use(cors({
26
+ origin: (origin, callback) => {
27
+ if (!origin || allowedOrigins.includes(origin)) {
28
+ callback(null, true); // allow
29
+ } else {
30
+ callback(new Error('Not allowed by CORS'));
31
+ }
32
+ },
33
+ credentials: true
34
  }));
35
 
36
  app.use(compression());
backend/models/CounterModel.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import mongoose from "mongoose";
2
+
3
+ const counterSchema = new mongoose.Schema({
4
+ tenant: { type: mongoose.Schema.Types.ObjectId, ref: "Tenant", required: true, unique: true },
5
+ invoiceNumber: { type: Number, default: 0 },
6
+ });
7
+
8
+ export default mongoose.model("Counter", counterSchema);
frontend/hook/useDebounce.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+
3
+ export function useDebounce(value, delay) {
4
+ const [debouncedValue, setDebouncedValue] = useState(value);
5
+
6
+ useEffect(() => {
7
+ // Update debounced value after delay
8
+ const handler = setTimeout(() => {
9
+ setDebouncedValue(value);
10
+ }, delay);
11
+
12
+ // Cancel the timeout if value changes (also on delay change or unmount)
13
+ return () => {
14
+ clearTimeout(handler);
15
+ };
16
+ }, [value, delay]);
17
+
18
+ return debouncedValue;
19
+ }
frontend/src/App.jsx CHANGED
@@ -10,20 +10,21 @@ axios.defaults.withCredentials = true;
10
 
11
  const queryClient = new QueryClient();
12
 
 
13
  const App = () => {
14
  return (
15
  <QueryClientProvider client={queryClient}>
16
- <AuthProvider>
17
- <RouterProvider router={routes} />
18
- <ToastContainer
19
- position="top-right"
20
- autoClose={3000}
21
- hideProgressBar={false}
22
- closeOnClick
23
- pauseOnHover
24
- rtl={true}
25
- />
26
- </AuthProvider>
27
  </QueryClientProvider>
28
  );
29
  };
 
10
 
11
  const queryClient = new QueryClient();
12
 
13
+
14
  const App = () => {
15
  return (
16
  <QueryClientProvider client={queryClient}>
17
+ <AuthProvider>
18
+ <RouterProvider router={routes} />
19
+ <ToastContainer
20
+ position="top-right"
21
+ autoClose={3000}
22
+ hideProgressBar={false}
23
+ closeOnClick
24
+ pauseOnHover
25
+ rtl={true}
26
+ />
27
+ </AuthProvider>
28
  </QueryClientProvider>
29
  );
30
  };
frontend/src/components/CustomerDetails/CustomerDetails.jsx CHANGED
@@ -14,6 +14,13 @@ import {
14
  MessageCircle,
15
  Printer,
16
  Wallet,
 
 
 
 
 
 
 
17
  } from "lucide-react";
18
  import { useState } from "react";
19
  import EditInvoiceItemModal from "./EditInvoiceItemModal";
@@ -25,101 +32,333 @@ import { buildCustomerInvoiceMessage, openWhatsAppMessage } from "../../utils/wh
25
 
26
  const apiUrl = import.meta.env.VITE_API_URL;
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  const CustomerDetails = () => {
29
  const { id } = useParams();
30
  const navigate = useNavigate();
31
  const { user } = useAuth();
32
  const permissions = getPermissions(user);
33
  const companyName = user?.tenant?.name || "ู†ุธุงู… ุฅุฏุงุฑุฉ ุงู„ู…ุจูŠุนุงุช";
 
34
  const [openEditModel, setOpenEditModel] = useState(false);
35
  const [selectedItem, setSelectedItem] = useState(null);
36
  const [openPayModal, setOpenPayModal] = useState(false);
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- const getCustomerDetails = () => axios.get(`${apiUrl}/customers/${id}`);
 
 
 
39
 
40
  const { data, isLoading } = useQuery({
41
- queryKey: ["customer", id],
42
  queryFn: getCustomerDetails,
43
  refetchOnWindowFocus: false,
 
44
  });
45
 
46
  if (isLoading) return <LodderSpinner />;
47
 
48
  const customer = data?.data;
49
- const customerID = customer?._id;
50
- const invoice = customer?.invoice;
51
- const invoiceID = customer?.invoice?._id;
 
 
 
 
 
52
 
53
- const handleShareWhatsApp = () => {
 
 
 
 
 
54
  if (!invoice) return;
55
  openWhatsAppMessage(
56
- buildCustomerInvoiceMessage({
57
- companyName,
58
- customerName: customer.name,
59
- invoice,
60
- })
61
  );
62
  };
63
 
64
- const handlePrint = () => {
65
- window.open(`/print/invoice/${customerID}`, "_blank", "width=800,height=800");
66
  };
67
 
68
- const getStatusBadge = (status) => {
69
- const map = {
70
- paid: {
71
- label: "ู…ุฏููˆุนุฉ",
72
- color: "bg-emerald-100 text-emerald-800 border-emerald-200",
73
- icon: <CheckCircle size={16} />,
74
- },
75
- unpaid: {
76
- label: "ุบูŠุฑ ู…ุฏููˆุนุฉ",
77
- color: "bg-rose-100 text-rose-800 border-rose-200",
78
- icon: <AlertCircle size={16} />,
79
- },
80
- partial: {
81
- label: "ู…ุฏููˆุนุฉ ุฌุฒุฆูŠุงู‹",
82
- color: "bg-amber-100 text-amber-800 border-amber-200",
83
- icon: <Clock size={16} />,
84
- },
85
- open: {
86
- label: "ู…ูุชูˆุญุฉ",
87
- color: "bg-rose-100 text-rose-800 border-rose-200",
88
- icon: <AlertCircle size={16} />,
89
- },
90
- };
91
-
92
- const item = map[status] || map.unpaid;
93
-
94
- return (
95
- <span className={`${item.color} border px-4 py-1.5 rounded-full text-sm font-bold flex items-center gap-2 w-fit shadow-sm`}>
96
- {item.icon}
97
- {item.label}
98
- </span>
99
- );
100
  };
101
 
102
- function handleOpenEditModel(item) {
103
- setOpenEditModel(!openEditModel);
104
- setSelectedItem(item);
105
- }
106
-
107
- function closeEditModel() {
108
- setOpenEditModel(false);
109
  setSelectedItem(null);
110
- }
 
111
 
112
  return (
113
  <div className="min-h-screen bg-slate-50 p-4 lg:p-8" dir="rtl">
114
  <div className="max-w-6xl mx-auto space-y-6">
115
- <div className="bg-white rounded-2xl p-6 md:p-8 shadow-sm shadow-slate-200/50 border border-slate-200 relative overflow-hidden">
116
- <div className="absolute top-0 right-0 w-2 h-full bg-gradient-to-b from-amber-400 to-amber-600"></div>
117
 
118
- <button onClick={() => navigate(-1)} className="flex items-center gap-2 cursor-pointer text-slate-500 hover:text-slate-900 mb-6 w-fit hover:translate-x-1 transition-transform bg-slate-50 px-4 py-2 rounded-xl border border-slate-100 font-medium">
 
 
 
 
 
 
119
  <ArrowLeft size={18} /> ุงู„ุนูˆุฏุฉ ู„ู„ู‚ุงุฆู…ุฉ
120
  </button>
121
 
122
- <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
123
  <div>
124
  <h1 className="text-3xl font-black text-slate-800 mb-2 flex items-center gap-3">
125
  <div className="w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 text-2xl shadow-inner font-bold border border-slate-200">
@@ -130,159 +369,124 @@ const CustomerDetails = () => {
130
  <div className="flex items-center gap-2 text-slate-500 mt-3 font-medium bg-slate-50 w-fit px-4 py-2 rounded-lg border border-slate-100">
131
  <Calendar size={18} className="text-amber-500" />
132
  <span>
133
- ุนู…ูŠู„ ู…ู†ุฐ <span className="text-slate-700 font-bold">{new Date(customer?.createdAt).toLocaleDateString("ar-EG")}</span>
 
 
 
134
  </span>
135
  </div>
136
  </div>
137
- </div>
138
- </div>
139
 
140
- {!invoice ? (
141
- <div className="bg-white rounded-2xl p-16 text-center shadow-sm shadow-slate-200/50 border border-slate-200 flex flex-col items-center justify-center">
142
- <div className="w-24 h-24 bg-slate-50 rounded-full flex items-center justify-center mb-6">
143
- <FileText size={48} className="text-slate-300" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  </div>
145
- <h3 className="text-2xl font-bold text-slate-700 mb-2">ู„ุง ุชูˆุฌุฏ ูุงุชูˆุฑุฉ ู†ุดุทุฉ</h3>
146
- <p className="text-slate-500 max-w-md">ู‡ุฐุง ุงู„ุนู…ูŠู„ ู„ูŠุณ ู„ุฏูŠู‡ ุฃูŠ ุจู†ูˆุฏ ูุงุชูˆุฑุฉ ู…ุณุฌู„ุฉ ุจุนุฏ.</p>
147
  </div>
148
- ) : (
149
- <div className="bg-white rounded-2xl p-6 md:p-8 shadow-sm shadow-slate-200/50 border border-slate-200 space-y-8">
150
- <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 pb-6 border-b border-slate-100">
151
- <div className="flex flex-col md:flex-row items-start md:items-center gap-4">
152
- <div className="flex items-center gap-4">
153
- <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
154
- <FileText size={24} className="text-amber-500" /> ุญุงู„ุฉ ุงู„ุญุณุงุจ
155
- </h2>
156
- {getStatusBadge(invoice.status)}
157
- </div>
158
 
159
- <div className="flex items-center gap-2 border-r-0 md:border-r border-slate-200 pr-0 md:pr-4 pt-2 md:pt-0">
160
- <button onClick={handleShareWhatsApp} className="flex items-center gap-2 px-4 py-2 bg-emerald-50 text-emerald-600 rounded-lg hover:bg-emerald-600 hover:text-white transition-colors font-bold text-sm border border-emerald-100 shadow-sm">
161
- <MessageCircle size={18} />
162
- <span className="hidden md:inline">ู…ุดุงุฑูƒุฉ ุนุจุฑ ูˆุงุชุณุงุจ</span>
163
- </button>
164
- <button onClick={handlePrint} className="flex items-center gap-2 px-4 py-2 bg-slate-50 text-slate-600 rounded-lg hover:bg-slate-800 hover:text-white transition-colors font-bold text-sm border border-slate-200 shadow-sm">
165
- <Printer size={18} />
166
- <span className="hidden md:inline">ุทุจุงุนุฉ ุงู„ูุงุชูˆุฑุฉ</span>
167
- </button>
168
- </div>
169
- </div>
170
- <span className="text-sm text-slate-500 font-medium flex items-center gap-2 bg-slate-50 px-4 py-2 rounded-lg border border-slate-100">
171
- <Clock size={16} className="text-slate-400" /> ุขุฎุฑ ุชุญุฏูŠุซ: {new Date(invoice.updatedAt).toLocaleString("ar-EG")}
 
 
 
 
 
 
172
  </span>
173
- </div>
174
-
175
- <div className="bg-slate-50 rounded-2xl p-5 md:p-6 border border-slate-100 shadow-inner">
176
- <h3 className="font-bold text-lg text-slate-800 mb-5 flex items-center gap-2">
177
- <ClipboardList size={20} className="text-amber-500" /> ุจู†ูˆุฏ ุงู„ูุงุชูˆุฑุฉ
178
- </h3>
179
-
180
- {invoice.items.length === 0 ? (
181
- <p className="text-slate-500 text-center py-8 bg-white rounded-xl border border-slate-100">ู„ุง ุชูˆุฌุฏ ุจู†ูˆุฏ ููŠ ู‡ุฐู‡ ุงู„ูุงุชูˆุฑุฉ</p>
182
- ) : (
183
- <div className="space-y-3">
184
- {invoice.items.map((item) => (
185
- <div key={item._id} className="flex flex-col md:flex-row justify-between items-start md:items-center bg-white border border-slate-200 rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow group">
186
- <div className="mb-3 md:mb-0">
187
- <span className="text-lg font-bold text-slate-800 block mb-2">{item.name}</span>
188
- <span className="text-sm font-medium text-slate-600 bg-slate-100 px-3 py-1.5 rounded-lg border border-slate-200 flex items-center gap-2 w-fit">
189
- <span>ุงู„ูƒู…ูŠุฉ: <b className="text-amber-600">{item.quantity}</b></span>
190
- <span className="w-1 h-1 bg-slate-300 rounded-full"></span>
191
- <span>ุงู„ุณุนุฑ: <b>{item.price}</b> ุฌ.ู…</span>
192
- </span>
193
- </div>
194
-
195
- <div className="flex items-center gap-4 border-t md:border-t-0 border-slate-100 pt-3 md:pt-0 w-full md:w-auto justify-between md:justify-end">
196
- <span className="font-black text-lg text-slate-800 bg-emerald-50 text-emerald-700 px-4 py-2 rounded-lg border border-emerald-100 shadow-sm">
197
- {item.total.toFixed(2)} <span className="text-sm font-normal opacity-80">ุฌ.ู…</span>
198
- </span>
199
-
200
- <div className="flex items-center gap-2">
201
- {permissions.canEditInvoice ? (
202
- <button onClick={() => handleOpenEditModel(item)} className="p-2.5 text-blue-600 bg-blue-50 border border-blue-100 rounded-lg hover:bg-blue-600 hover:text-white transition-colors" title="ุชุนุฏูŠู„ ุงู„ุจู†ุฏ">
203
- <Pencil size={18} />
204
- </button>
205
- ) : null}
206
- {permissions.canEditInvoice ? (
207
- <DeleteInvoiceItemButton customerId={customerID} invoiceId={invoiceID} itemId={item._id} />
208
- ) : null}
209
- </div>
210
- </div>
211
- </div>
212
- ))}
213
- </div>
214
- )}
215
- </div>
216
-
217
- <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-4 border-t border-slate-100 mb-6">
218
- <Summary title="ุฅุฌู…ุงู„ูŠ ุงู„ูุงุชูˆุฑุฉ" value={invoice.totalAmount} type="blue" />
219
- <Summary title="ุงู„ู…ุฏููˆุน ุญุชู‰ ุงู„ุขู†" value={invoice.paidAmount} type="green" />
220
- <Summary title="ุงู„ุฑุตูŠุฏ ุงู„ู…ุชุจู‚ูŠ" value={invoice.remainingAmount} type="red" />
221
- </div>
222
-
223
- {invoice.payments?.length > 0 && (
224
- <div className="mt-8 bg-emerald-50/50 rounded-2xl p-5 md:p-6 border border-emerald-100 mb-6 group hover:shadow-sm transition-all">
225
- <h3 className="font-bold text-lg text-emerald-800 mb-4 flex items-center gap-2">
226
- <Clock size={20} className="text-emerald-500" /> ุณุฌู„ ุงู„ู…ุฏููˆุนุงุช
227
- </h3>
228
- <div className="space-y-3">
229
- {invoice.payments.map((payment) => (
230
- <div key={payment._id || payment.date} className="flex justify-between items-center bg-white border border-emerald-100 rounded-xl p-3 shadow-sm hover:border-emerald-200 transition-colors">
231
- <div className="flex items-center gap-3">
232
- <div className="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-600">
233
- <CheckCircle size={18} />
234
- </div>
235
- <div>
236
- <p className="font-bold text-slate-700 leading-tight">ุฏูุนุฉ {payment.method || 'ู†ู‚ุฏูŠุฉ'}</p>
237
- <p className="text-slate-500 text-sm mt-1">{new Date(payment.date).toLocaleString("ar-EG")}</p>
238
- </div>
239
- </div>
240
- <span className="font-black text-emerald-700 bg-emerald-50 px-4 py-2 rounded-xl border border-emerald-100 shadow-sm">
241
- +{payment.amount.toFixed(2)} <span className="text-xs font-normal opacity-70">ุฌ.ู…</span>
242
- </span>
243
- </div>
244
- ))}
245
- </div>
246
- </div>
247
  )}
 
 
248
 
249
- {permissions.canRecordPayments && invoice.remainingAmount > 0 && (
250
- <div className="flex justify-center md:justify-start pt-6 border-t border-slate-100">
251
- <button onClick={() => setOpenPayModal(true)} className="w-full md:w-auto flex items-center justify-center gap-3 bg-emerald-600 text-white px-8 py-3.5 rounded-xl hover:bg-emerald-700 font-bold shadow-sm shadow-emerald-500/20 transition-all hover:-translate-y-0.5 text-lg">
252
- <Wallet size={24} /> ุชุณุฌูŠู„ ุฏูุนุฉ
253
- </button>
254
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  )}
256
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  )}
258
- </div>
259
- {permissions.canEditInvoice && openEditModel && selectedItem ? <EditInvoiceItemModal customerId={customerID} onClose={closeEditModel} invoiceId={invoiceID} item={selectedItem} /> : null}
260
- {permissions.canRecordPayments && openPayModal ? <PayInvoiceModal customerId={customerID} remainingAmount={invoice.remainingAmount} onClose={() => setOpenPayModal(false)} /> : null}
261
- </div>
262
- );
263
- };
264
-
265
- const Summary = ({ title, value, type }) => {
266
- const variants = {
267
- blue: "bg-blue-50 border-blue-100 text-blue-700",
268
- green: "bg-emerald-50 border-emerald-100 text-emerald-700",
269
- red: "bg-rose-50 border-rose-100 text-rose-700",
270
- };
271
 
272
- const valueColor = {
273
- blue: "text-blue-700",
274
- green: "text-emerald-700",
275
- red: "text-rose-600",
276
- };
277
 
278
- return (
279
- <div className={`${variants[type]} border rounded-2xl p-5 flex flex-col items-center justify-center text-center shadow-sm hover:-translate-y-1 transition-transform`}>
280
- <p className="text-sm font-bold opacity-80 mb-2">{title}</p>
281
- <p className={`text-2xl font-black ${valueColor[type]} drop-shadow-sm`}>
282
- {value.toFixed(2)} <span className="text-sm font-normal opacity-80">ุฌ.ู…</span>
283
- </p>
 
 
 
 
 
 
 
 
 
 
 
284
  </div>
285
  );
286
  };
287
 
288
- export default CustomerDetails;
 
14
  MessageCircle,
15
  Printer,
16
  Wallet,
17
+ ChevronDown,
18
+ ChevronUp,
19
+ ChevronRight,
20
+ ChevronLeft,
21
+ TrendingUp,
22
+ CreditCard,
23
+ Hourglass,
24
  } from "lucide-react";
25
  import { useState } from "react";
26
  import EditInvoiceItemModal from "./EditInvoiceItemModal";
 
32
 
33
  const apiUrl = import.meta.env.VITE_API_URL;
34
 
35
+ // โ”€โ”€โ”€ Status badge โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
36
+ const getStatusBadge = (status) => {
37
+ const map = {
38
+ paid: { label: "ู…ุฏููˆุนุฉ", color: "bg-emerald-100 text-emerald-800 border-emerald-200", icon: <CheckCircle size={16} /> },
39
+ unpaid: { label: "ุบูŠุฑ ู…ุฏููˆุนุฉ", color: "bg-rose-100 text-rose-800 border-rose-200", icon: <AlertCircle size={16} /> },
40
+ partial: { label: "ู…ุฏููˆุนุฉ ุฌุฒุฆูŠุงู‹", color: "bg-amber-100 text-amber-800 border-amber-200", icon: <Clock size={16} /> },
41
+ open: { label: "ู…ูุชูˆุญุฉ", color: "bg-rose-100 text-rose-800 border-rose-200", icon: <AlertCircle size={16} /> },
42
+ };
43
+ const item = map[status] || map.unpaid;
44
+ return (
45
+ <span className={`${item.color} border px-4 py-1.5 rounded-full text-sm font-bold flex items-center gap-2 w-fit shadow-sm`}>
46
+ {item.icon}{item.label}
47
+ </span>
48
+ );
49
+ };
50
+
51
+ // โ”€โ”€โ”€ Summary card โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
52
+ const Summary = ({ title, value, type }) => {
53
+ const variants = {
54
+ blue: "bg-blue-50 border-blue-100 text-blue-700",
55
+ green: "bg-emerald-50 border-emerald-100 text-emerald-700",
56
+ red: "bg-rose-50 border-rose-100 text-rose-700",
57
+ };
58
+ const valueColor = { blue: "text-blue-700", green: "text-emerald-700", red: "text-rose-600" };
59
+ return (
60
+ <div className={`${variants[type]} border rounded-2xl p-5 flex flex-col items-center justify-center text-center shadow-sm hover:-translate-y-1 transition-transform`}>
61
+ <p className="text-sm font-bold opacity-80 mb-2">{title}</p>
62
+ <p className={`text-2xl font-black ${valueColor[type]} drop-shadow-sm`}>
63
+ {value.toFixed(2)} <span className="text-sm font-normal opacity-80">ุฌ.ู…</span>
64
+ </p>
65
+ </div>
66
+ );
67
+ };
68
+
69
+ // โ”€โ”€โ”€ Stat card (customer overview) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
70
+ const StatCard = ({ icon, label, value, color }) => (
71
+ <div className={`flex items-center gap-3 bg-white border ${color} rounded-xl px-5 py-4 shadow-sm flex-1 min-w-0`}>
72
+ <div className={`w-10 h-10 rounded-full flex items-center justify-center ${color.replace("border-", "bg-").replace("-200", "-100")}`}>
73
+ {icon}
74
+ </div>
75
+ <div className="min-w-0">
76
+ <p className="text-xs text-slate-500 font-medium truncate">{label}</p>
77
+ <p className="text-lg font-black text-slate-800 truncate">{value}</p>
78
+ </div>
79
+ </div>
80
+ );
81
+
82
+ // โ”€โ”€โ”€ Pagination โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
83
+ const Pagination = ({ pagination, page, setPage }) => {
84
+ if (!pagination || pagination.totalPages <= 1) return null;
85
+ const { total, totalPages } = pagination;
86
+
87
+ return (
88
+ <div className="flex flex-col sm:flex-row items-center justify-between gap-3 bg-white border border-slate-200 rounded-2xl px-6 py-4 shadow-sm">
89
+ <p className="text-sm text-slate-500 font-medium">
90
+ ุฅุฌู…ุงู„ูŠ ุงู„ููˆุงุชูŠุฑ: <span className="font-bold text-slate-700">{total}</span>
91
+ </p>
92
+ <div className="flex items-center gap-2">
93
+ <button
94
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
95
+ disabled={page === 1}
96
+ className="w-9 h-9 flex items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:bg-slate-100 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
97
+ >
98
+ <ChevronRight size={18} />
99
+ </button>
100
+
101
+ {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
102
+ <button
103
+ key={p}
104
+ onClick={() => setPage(p)}
105
+ className={`w-9 h-9 flex items-center justify-center rounded-lg border text-sm font-bold transition-colors ${p === page
106
+ ? "bg-amber-500 border-amber-500 text-white shadow-sm"
107
+ : "border-slate-200 text-slate-600 hover:bg-slate-100"
108
+ }`}
109
+ >
110
+ {p}
111
+ </button>
112
+ ))}
113
+
114
+ <button
115
+ onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
116
+ disabled={page === totalPages}
117
+ className="w-9 h-9 flex items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:bg-slate-100 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
118
+ >
119
+ <ChevronLeft size={18} />
120
+ </button>
121
+ </div>
122
+ </div>
123
+ );
124
+ };
125
+
126
+ // โ”€โ”€โ”€ Invoice card โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
127
+ const InvoiceCard = ({
128
+ invoice, customer, permissions, companyName,
129
+ onShare, onPrint, onEditItem, onPay,
130
+ }) => {
131
+ const [collapsed, setCollapsed] = useState(false);
132
+
133
+ return (
134
+ <div className="bg-white rounded-2xl shadow-sm shadow-slate-200/50 border border-slate-200 overflow-hidden">
135
+ {/* โ”€โ”€ Header โ”€โ”€ */}
136
+ <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 px-6 md:px-8 py-5 border-b border-slate-100">
137
+ <div className="flex flex-col md:flex-row items-start md:items-center gap-4 flex-1 min-w-0">
138
+ <div className="flex items-center gap-3 flex-wrap">
139
+ <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
140
+ <FileText size={22} className="text-amber-500 shrink-0" />
141
+ ูุงุชูˆุฑุฉ: {invoice.invoiceNumber}
142
+ </h2>
143
+ {getStatusBadge(invoice.status)}
144
+ </div>
145
+
146
+ <div className="flex items-center gap-2">
147
+ <button
148
+ onClick={() => onShare(invoice)}
149
+ className="flex items-center gap-2 px-4 py-2 bg-emerald-50 text-emerald-600 rounded-lg hover:bg-emerald-600 hover:text-white transition-colors font-bold text-sm border border-emerald-100 shadow-sm"
150
+ >
151
+ <MessageCircle size={18} />
152
+ <span className="hidden md:inline">ูˆุงุชุณุงุจ</span>
153
+ </button>
154
+ <button
155
+ onClick={() => onPrint(invoice)}
156
+ className="flex items-center gap-2 px-4 py-2 bg-slate-50 text-slate-600 rounded-lg hover:bg-slate-800 hover:text-white transition-colors font-bold text-sm border border-slate-200 shadow-sm"
157
+ >
158
+ <Printer size={18} />
159
+ <span className="hidden md:inline">ุทุจุงุนุฉ</span>
160
+ </button>
161
+ </div>
162
+ </div>
163
+
164
+ <div className="flex items-center gap-3 self-end md:self-auto">
165
+ <span className="text-sm text-slate-500 font-medium hidden sm:flex items-center gap-2 bg-slate-50 px-4 py-2 rounded-lg border border-slate-100">
166
+ <Clock size={15} className="text-slate-400" />
167
+ {new Date(invoice.updatedAt).toLocaleString("ar-EG")}
168
+ </span>
169
+ {/* Collapse toggle */}
170
+ <button
171
+ onClick={() => setCollapsed((c) => !c)}
172
+ className="w-9 h-9 flex items-center justify-center rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 transition-colors"
173
+ title={collapsed ? "ุชูˆุณูŠุน" : "ุทูŠ"}
174
+ >
175
+ {collapsed ? <ChevronDown size={18} /> : <ChevronUp size={18} />}
176
+ </button>
177
+ </div>
178
+ </div>
179
+
180
+ {/* โ”€โ”€ Collapsible body โ”€โ”€ */}
181
+ {!collapsed && (
182
+ <div className="px-6 md:px-8 py-6 space-y-6">
183
+ {/* Items */}
184
+ <div className="bg-slate-50 rounded-2xl p-5 md:p-6 border border-slate-100 shadow-inner">
185
+ <h3 className="font-bold text-lg text-slate-800 mb-5 flex items-center gap-2">
186
+ <ClipboardList size={20} className="text-amber-500" /> ุจู†ูˆุฏ ุงู„ูุงุชูˆุฑุฉ
187
+ </h3>
188
+ {invoice.items.length === 0 ? (
189
+ <p className="text-slate-500 text-center py-8 bg-white rounded-xl border border-slate-100">ู„ุง ุชูˆุฌุฏ ุจู†ูˆุฏ ููŠ ู‡ุฐู‡ ุงู„ูุงุชูˆุฑุฉ</p>
190
+ ) : (
191
+ <div className="space-y-3">
192
+ {invoice.items.map((item) => (
193
+ <div key={item._id} className="flex flex-col md:flex-row justify-between items-start md:items-center bg-white border border-slate-200 rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow">
194
+ <div className="mb-3 md:mb-0">
195
+ <span className="text-lg font-bold text-slate-800 block mb-2">{item.name}</span>
196
+ <span className="text-sm font-medium text-slate-600 bg-slate-100 px-3 py-1.5 rounded-lg border border-slate-200 flex items-center gap-2 w-fit">
197
+ <span>ุงู„ูƒู…ูŠุฉ: <b className="text-amber-600">{item.quantity}</b></span>
198
+ <span className="w-1 h-1 bg-slate-300 rounded-full" />
199
+ <span>ุงู„ุณุนุฑ: <b>{item.price}</b> ุฌ.ู…</span>
200
+ </span>
201
+ </div>
202
+ <div className="flex items-center gap-4 border-t md:border-t-0 border-slate-100 pt-3 md:pt-0 w-full md:w-auto justify-between md:justify-end">
203
+ <span className="font-black text-lg bg-emerald-50 text-emerald-700 px-4 py-2 rounded-lg border border-emerald-100 shadow-sm">
204
+ {item.total.toFixed(2)} <span className="text-sm font-normal opacity-80">ุฌ.ู…</span>
205
+ </span>
206
+ <div className="flex items-center gap-2">
207
+ {permissions.canEditInvoice && (
208
+ <button onClick={() => onEditItem(item, invoice)} className="p-2.5 text-blue-600 bg-blue-50 border border-blue-100 rounded-lg hover:bg-blue-600 hover:text-white transition-colors" title="ุชุนุฏูŠู„ ุงู„ุจู†ุฏ">
209
+ <Pencil size={18} />
210
+ </button>
211
+ )}
212
+ {permissions.canEditInvoice && (
213
+ <DeleteInvoiceItemButton customerId={customer._id} invoiceId={invoice._id} itemId={item._id} />
214
+ )}
215
+ </div>
216
+ </div>
217
+ </div>
218
+ ))}
219
+ </div>
220
+ )}
221
+ </div>
222
+
223
+ {/* Totals */}
224
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
225
+ <Summary title="ุฅุฌู…ุงู„ูŠ ุงู„ูุงุชูˆุฑุฉ" value={invoice.totalAmount} type="blue" />
226
+ <Summary title="ุงู„ู…ุฏููˆุน ุญุชู‰ ุงู„ุขู†" value={invoice.paidAmount} type="green" />
227
+ <Summary title="ุงู„ุฑุตูŠุฏ ุงู„ู…ุชุจู‚ูŠ" value={invoice.remainingAmount} type="red" />
228
+ </div>
229
+
230
+ {/* Payments log */}
231
+ {invoice.payments?.length > 0 && (
232
+ <div className="bg-emerald-50/50 rounded-2xl p-5 md:p-6 border border-emerald-100">
233
+ <h3 className="font-bold text-lg text-emerald-800 mb-4 flex items-center gap-2">
234
+ <Clock size={20} className="text-emerald-500" /> ุณุฌู„ ุงู„ู…ุฏููˆุนุงุช
235
+ </h3>
236
+ <div className="space-y-3">
237
+ {invoice.payments.map((payment) => (
238
+ <div key={payment._id || payment.date} className="flex justify-between items-center bg-white border border-emerald-100 rounded-xl p-3 shadow-sm hover:border-emerald-200 transition-colors">
239
+ <div className="flex items-center gap-3">
240
+ <div className="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-600">
241
+ <CheckCircle size={18} />
242
+ </div>
243
+ <div>
244
+ <p className="font-bold text-slate-700 leading-tight">ุฏูุนุฉ {payment.method === "cash" ? "ู†ู‚ุฏูŠุฉ" : payment.method}</p>
245
+ <p className="text-slate-500 text-sm mt-1">{new Date(payment.date).toLocaleString("ar-EG")}</p>
246
+ </div>
247
+ </div>
248
+ <span className="font-black text-emerald-700 bg-emerald-50 px-4 py-2 rounded-xl border border-emerald-100 shadow-sm">
249
+ +{payment.amount.toFixed(2)} <span className="text-xs font-normal opacity-70">ุฌ.ู…</span>
250
+ </span>
251
+ </div>
252
+ ))}
253
+ </div>
254
+ </div>
255
+ )}
256
+
257
+ {/* Pay button */}
258
+ {permissions.canRecordPayments && invoice.remainingAmount > 0 && (
259
+ <div className="flex justify-center md:justify-start pt-2">
260
+ <button
261
+ onClick={() => onPay(invoice)}
262
+ className="w-full md:w-auto flex items-center justify-center gap-3 bg-emerald-600 text-white px-8 py-3.5 rounded-xl hover:bg-emerald-700 font-bold shadow-sm shadow-emerald-500/20 transition-all hover:-translate-y-0.5 text-lg"
263
+ >
264
+ <Wallet size={24} /> ุชุณุฌูŠู„ ุฏูุนุฉ
265
+ </button>
266
+ </div>
267
+ )}
268
+ </div>
269
+ )}
270
+ </div>
271
+ );
272
+ };
273
+
274
+ // โ”€โ”€โ”€ Main component โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€๏ฟฝ๏ฟฝโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
275
  const CustomerDetails = () => {
276
  const { id } = useParams();
277
  const navigate = useNavigate();
278
  const { user } = useAuth();
279
  const permissions = getPermissions(user);
280
  const companyName = user?.tenant?.name || "ู†ุธุงู… ุฅุฏุงุฑุฉ ุงู„ู…ุจูŠุนุงุช";
281
+
282
  const [openEditModel, setOpenEditModel] = useState(false);
283
  const [selectedItem, setSelectedItem] = useState(null);
284
  const [openPayModal, setOpenPayModal] = useState(false);
285
+ const [activeInvoice, setActiveInvoice] = useState(null);
286
+ const [page, setPage] = useState(1);
287
+
288
+ // Status filter
289
+ const [statusFilter, setStatusFilter] = useState("all");
290
+ const STATUS_OPTS = [
291
+ { value: "all", label: "ุงู„ูƒู„" },
292
+ { value: "paid", label: "ู…ุฏููˆุนุฉ" },
293
+ { value: "partial", label: "ุฌุฒุฆูŠ" },
294
+ { value: "unpaid", label: "ุบูŠุฑ ู…ุฏููˆุนุฉ" },
295
+ ];
296
 
297
+ const limit = 5;
298
+
299
+ const getCustomerDetails = () =>
300
+ axios.get(`${apiUrl}/customers/${id}?includeInvoices=true&page=${page}&limit=${limit}`);
301
 
302
  const { data, isLoading } = useQuery({
303
+ queryKey: ["customer", id, page],
304
  queryFn: getCustomerDetails,
305
  refetchOnWindowFocus: false,
306
+ keepPreviousData: true, // smooth pagination โ€” no flicker
307
  });
308
 
309
  if (isLoading) return <LodderSpinner />;
310
 
311
  const customer = data?.data;
312
+ const allInvoices = customer?.invoices || [];
313
+ const pagination = customer?.pagination;
314
+
315
+ // Client-side status filter (applied on top of paginated results)
316
+ const invoices =
317
+ statusFilter === "all"
318
+ ? allInvoices
319
+ : allInvoices.filter((inv) => inv.status === statusFilter);
320
 
321
+ // Customer-level stats derived from current page data
322
+ const totalRevenue = allInvoices.reduce((s, inv) => s + inv.totalAmount, 0);
323
+ const totalPaid = allInvoices.reduce((s, inv) => s + inv.paidAmount, 0);
324
+ const totalRemaining = allInvoices.reduce((s, inv) => s + inv.remainingAmount, 0);
325
+
326
+ const handleShareWhatsApp = (invoice) => {
327
  if (!invoice) return;
328
  openWhatsAppMessage(
329
+ buildCustomerInvoiceMessage({ companyName, customerName: customer.name, invoice })
 
 
 
 
330
  );
331
  };
332
 
333
+ const handlePrint = (invoice) => {
334
+ window.open(`/print/invoice/${customer._id}/${invoice._id}`, "_blank");
335
  };
336
 
337
+ const handleOpenEditModel = (item, invoice) => {
338
+ setSelectedItem({ ...item, invoiceId: invoice._id });
339
+ setOpenEditModel(true);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
  };
341
 
342
+ const closeEditModel = () => {
 
 
 
 
 
 
343
  setSelectedItem(null);
344
+ setOpenEditModel(false);
345
+ };
346
 
347
  return (
348
  <div className="min-h-screen bg-slate-50 p-4 lg:p-8" dir="rtl">
349
  <div className="max-w-6xl mx-auto space-y-6">
 
 
350
 
351
+ {/* โ”€โ”€ Customer header โ”€โ”€ */}
352
+ <div className="bg-white rounded-2xl p-6 md:p-8 shadow-sm shadow-slate-200/50 border border-slate-200 relative overflow-hidden">
353
+ <div className="absolute top-0 right-0 w-2 h-full bg-gradient-to-b from-amber-400 to-amber-600" />
354
+ <button
355
+ onClick={() => navigate(-1)}
356
+ className="flex items-center gap-2 cursor-pointer text-slate-500 hover:text-slate-900 mb-6 w-fit hover:translate-x-1 transition-transform bg-slate-50 px-4 py-2 rounded-xl border border-slate-100 font-medium"
357
+ >
358
  <ArrowLeft size={18} /> ุงู„ุนูˆุฏุฉ ู„ู„ู‚ุงุฆู…ุฉ
359
  </button>
360
 
361
+ <div className="flex flex-col md:flex-row md:items-start justify-between gap-6">
362
  <div>
363
  <h1 className="text-3xl font-black text-slate-800 mb-2 flex items-center gap-3">
364
  <div className="w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 text-2xl shadow-inner font-bold border border-slate-200">
 
369
  <div className="flex items-center gap-2 text-slate-500 mt-3 font-medium bg-slate-50 w-fit px-4 py-2 rounded-lg border border-slate-100">
370
  <Calendar size={18} className="text-amber-500" />
371
  <span>
372
+ ุนู…ูŠู„ ู…ู†ุฐ{" "}
373
+ <span className="text-slate-700 font-bold">
374
+ {new Date(customer?.createdAt).toLocaleDateString("ar-EG")}
375
+ </span>
376
  </span>
377
  </div>
378
  </div>
 
 
379
 
380
+ {/* โ”€โ”€ Quick stats row โ”€โ”€ */}
381
+ <div className="flex flex-wrap gap-3 flex-1 md:justify-end">
382
+ <StatCard
383
+ icon={<TrendingUp size={18} className="text-blue-600" />}
384
+ label="ุฅุฌู…ุงู„ูŠ ุงู„ููˆุงุชูŠุฑ"
385
+ value={`${totalRevenue.toFixed(2)} ุฌ.ู…`}
386
+ color="border-blue-200"
387
+ />
388
+ <StatCard
389
+ icon={<CheckCircle size={18} className="text-emerald-600" />}
390
+ label="ุชู… ุชุญุตูŠู„ู‡"
391
+ value={`${totalPaid.toFixed(2)} ุฌ.ู…`}
392
+ color="border-emerald-200"
393
+ />
394
+ <StatCard
395
+ icon={<Hourglass size={18} className="text-rose-600" />}
396
+ label="ุงู„ู…ุชุจู‚ูŠ"
397
+ value={`${totalRemaining.toFixed(2)} ุฌ.ู…`}
398
+ color="border-rose-200"
399
+ />
400
  </div>
 
 
401
  </div>
402
+ </div>
 
 
 
 
 
 
 
 
 
403
 
404
+ {/* โ”€โ”€ Filter bar โ”€โ”€ */}
405
+ {allInvoices.length > 0 && (
406
+ <div className="bg-white border border-slate-200 rounded-2xl px-6 py-4 shadow-sm flex flex-wrap items-center gap-3">
407
+ <span className="text-sm font-bold text-slate-600 ml-2">ุชุตููŠุฉ ุญุณุจ ุงู„ุญุงู„ุฉ:</span>
408
+ {STATUS_OPTS.map((opt) => (
409
+ <button
410
+ key={opt.value}
411
+ onClick={() => { setStatusFilter(opt.value); setPage(1); }}
412
+ className={`px-4 py-1.5 rounded-full text-sm font-bold border transition-colors ${statusFilter === opt.value
413
+ ? "bg-amber-500 border-amber-500 text-white shadow-sm"
414
+ : "bg-slate-50 border-slate-200 text-slate-600 hover:bg-slate-100"
415
+ }`}
416
+ >
417
+ {opt.label}
418
+ </button>
419
+ ))}
420
+ {pagination && (
421
+ <span className="mr-auto text-sm text-slate-400 font-medium">
422
+ ุงู„ุตูุญุฉ {pagination.page} ู…ู† {pagination.totalPages} ยท {pagination.total} ูุงุชูˆุฑุฉ
423
  </span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
  )}
425
+ </div>
426
+ )}
427
 
428
+ {/* โ”€โ”€ Invoice list โ”€โ”€ */}
429
+ {invoices.length === 0 ? (
430
+ <div className="bg-white rounded-2xl p-16 text-center shadow-sm shadow-slate-200/50 border border-slate-200 flex flex-col items-center justify-center">
431
+ <div className="w-24 h-24 bg-slate-50 rounded-full flex items-center justify-center mb-6">
432
+ <FileText size={48} className="text-slate-300" />
433
+ </div>
434
+ <h3 className="text-2xl font-bold text-slate-700 mb-2">
435
+ {statusFilter === "all" ? "ู„ุง ุชูˆุฌุฏ ููˆุงุชูŠุฑ" : "ู„ุง ุชูˆุฌุฏ ููˆุงุชูŠุฑ ุจู‡ุฐู‡ ุงู„ุญุงู„ุฉ"}
436
+ </h3>
437
+ <p className="text-slate-500 max-w-md">
438
+ {statusFilter === "all"
439
+ ? "ู‡ุฐุง ุงู„ุนู…ูŠู„ ู„ูŠุณ ู„ุฏูŠู‡ ุฃูŠ ููˆุงุชูŠุฑ ู…ุณุฌู„ุฉ ุจุนุฏ."
440
+ : "ุฌุฑู‘ุจ ุชุตููŠุฉ ู…ุฎุชู„ูุฉ ู„ู„ุงุทู„ุงุน ุนู„ู‰ ุงู„ููˆุงุชูŠุฑ ุงู„ุฃุฎุฑู‰."}
441
+ </p>
442
+ {statusFilter !== "all" && (
443
+ <button
444
+ onClick={() => setStatusFilter("all")}
445
+ className="mt-4 px-5 py-2 bg-amber-50 border border-amber-200 text-amber-700 rounded-xl font-bold text-sm hover:bg-amber-100 transition-colors"
446
+ >
447
+ ุฅุธู‡ุงุฑ ุงู„ูƒู„
448
+ </button>
449
  )}
450
  </div>
451
+ ) : (
452
+ invoices.map((invoice) => (
453
+ <InvoiceCard
454
+ key={invoice._id}
455
+ invoice={invoice}
456
+ customer={customer}
457
+ permissions={permissions}
458
+ companyName={companyName}
459
+ onShare={handleShareWhatsApp}
460
+ onPrint={handlePrint}
461
+ onEditItem={handleOpenEditModel}
462
+ onPay={(inv) => { setActiveInvoice(inv); setOpenPayModal(true); }}
463
+ />
464
+ ))
465
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
466
 
467
+ {/* โ”€โ”€ Pagination โ”€โ”€ */}
468
+ <Pagination pagination={pagination} page={page} setPage={setPage} />
469
+ </div>
 
 
470
 
471
+ {/* โ”€โ”€ Modals โ”€โ”€ */}
472
+ {permissions.canEditInvoice && openEditModel && selectedItem && (
473
+ <EditInvoiceItemModal
474
+ customerId={customer._id}
475
+ onClose={closeEditModel}
476
+ invoiceId={selectedItem.invoiceId}
477
+ item={selectedItem}
478
+ />
479
+ )}
480
+ {permissions.canRecordPayments && openPayModal && activeInvoice && (
481
+ <PayInvoiceModal
482
+ customerId={customer._id}
483
+ invoiceId={activeInvoice._id}
484
+ remainingAmount={activeInvoice.remainingAmount}
485
+ onClose={() => setOpenPayModal(false)}
486
+ />
487
+ )}
488
  </div>
489
  );
490
  };
491
 
492
+ export default CustomerDetails;
frontend/src/components/CustomerDetails/PrintInvoice.jsx CHANGED
@@ -8,105 +8,138 @@ import { useAuth } from "../../Context/AuthContext";
8
  const apiUrl = import.meta.env.VITE_API_URL;
9
 
10
  const PrintInvoice = () => {
11
- const { id } = useParams();
 
12
  const { user } = useAuth();
13
  const companyName = user?.tenant?.name || "ู†ุธุงู… ุฅุฏุงุฑุฉ ุงู„ู…ุจูŠุนุงุช";
14
- const companyDescription = user?.tenant?.address || "ู†ุธุงู… ู…ุญุงุณุจุฉ ูˆููˆุชุฑุฉ ู…ุชุนุฏุฏ ุงู„ู…ุณุชุฃุฌุฑูŠู†";
15
 
16
  const { data, isLoading } = useQuery({
17
- queryKey: ["customer", id],
18
- queryFn: () => axios.get(`${apiUrl}/customers/${id}`),
 
19
  refetchOnWindowFocus: false,
20
  });
21
 
 
 
 
 
22
  useEffect(() => {
23
- if (data) {
24
- setTimeout(() => {
25
- window.print();
26
- }, 500);
27
- }
28
- }, [data]);
29
 
30
  if (isLoading) return <LodderSpinner />;
31
 
32
- const customer = data?.data;
33
- const invoice = customer?.invoice;
34
 
35
- if (!invoice) return <div className="p-10 text-center">ู„ุง ุชูˆุฌุฏ ูุงุชูˆุฑุฉ ู„ู‡ุฐุง ุงู„ุนู…ูŠู„</div>;
 
36
 
37
  return (
38
- <div className="bg-white p-8 max-w-4xl mx-auto text-black font-sans min-h-screen" dir="rtl">
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  <style>{`
40
  @media print {
41
- @page { margin: 0; size: auto; }
42
- body { background: white; margin: 1cm; print-color-adjust: exact; -webkit-print-color-adjust: exact; }
 
 
 
 
 
 
 
43
  }
44
  `}</style>
45
 
46
- <div className="text-center border-b-2 border-slate-800 pb-6 mb-6">
47
- <h1 className="text-4xl font-black mb-2">{companyName}</h1>
48
- <p className="text-xl font-bold">{companyDescription}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  </div>
50
 
51
- <div className="flex justify-between mb-10 pt-2">
52
- <div>
53
- <p className="font-bold text-gray-500 mb-1">ุงู„ุนู…ูŠู„</p>
54
- <h2 className="text-3xl font-bold">{customer.name}</h2>
 
 
 
 
 
 
55
  </div>
56
- <div className="text-left bg-gray-50 p-4 rounded-xl border border-gray-200">
57
- <p className="font-bold text-gray-500 mb-1">ุฑู‚ู… ุงู„ูุงุชูˆุฑุฉ</p>
58
- <p className="text-xl font-black"># {invoice.invoiceNumber || invoice._id.slice(-6).toUpperCase()}</p>
59
- <p className="font-bold text-gray-500 mt-2 mb-1">ุชุงุฑูŠุฎ ุงู„ุทุจุงุนุฉ</p>
60
- <p className="text-lg font-bold">{new Date().toLocaleString("ar-EG")}</p>
 
 
 
 
61
  </div>
62
  </div>
63
 
64
- <table className="w-full text-right border-collapse mb-10">
65
- <thead>
66
- <tr className="bg-gray-100 border-y-2 border-gray-300">
67
- <th className="p-4 font-bold text-lg">#</th>
68
- <th className="p-4 font-bold text-lg">ุงู„ุตู†ู</th>
69
- <th className="p-4 font-bold text-lg text-center">ุงู„ูƒู…ูŠุฉ</th>
70
- <th className="p-4 font-bold text-lg text-center">ุณุนุฑ ุงู„ูˆุญุฏุฉ</th>
71
- <th className="p-4 font-bold text-lg text-right">ุงู„ุฅุฌู…ุงู„ูŠ</th>
72
- </tr>
73
- </thead>
74
- <tbody>
75
- {invoice.items.map((item, index) => (
76
- <tr key={index} className="border-b border-gray-200">
77
- <td className="p-4">{index + 1}</td>
78
- <td className="p-4 font-black">{item.name}</td>
79
- <td className="p-4 font-bold text-center">{item.quantity}</td>
80
- <td className="p-4 text-center">{item.price} ุฌ.ู…</td>
81
- <td className="p-4 font-black text-right">{item.total.toFixed(2)} ุฌ.ู…</td>
82
- </tr>
83
  ))}
84
- </tbody>
85
- </table>
86
-
87
- <div className="flex justify-start mt-4">
88
- <div className="w-1/2 p-6 rounded-xl border-4 border-gray-800">
89
- <div className="flex justify-between mb-4 text-xl">
90
- <span className="font-bold text-gray-600">ุฅุฌู…ุงู„ูŠ ุงู„ูุงุชูˆุฑุฉ</span>
91
- <span className="font-black">{invoice.totalAmount.toFixed(2)} ุฌ.ู…</span>
92
- </div>
93
- <div className="flex justify-between mb-4 text-xl border-b-2 border-gray-300 pb-4">
94
- <span className="font-bold text-gray-600">ุงู„ู…ุฏููˆุนุงุช ุงู„ู…ุณุชู„ู…ุฉ</span>
95
- <span className="font-bold text-gray-800">{invoice.paidAmount.toFixed(2)} ุฌ.ู…</span>
96
- </div>
97
- <div className="flex justify-between mt-4 text-2xl">
98
- <span className="font-black text-black">ุงู„ุฑุตูŠุฏ ุงู„ู…ุชุจู‚ูŠ</span>
99
- <span className="font-black text-black">{invoice.remainingAmount.toFixed(2)} ุฌ.ู…</span>
100
- </div>
101
  </div>
102
- </div>
103
 
104
- <div className="text-center mt-16 pt-8 border-t-2 border-dashed border-gray-300">
105
- <p className="font-black text-2xl mb-2">ุดูƒุฑุงู‹ ู„ุงุฎุชูŠุงุฑูƒู… {companyName}</p>
106
- <p className="text-lg text-gray-600 font-bold">ู‡ุฐู‡ ุงู„ู†ุณุฎุฉ ุฌุงู‡ุฒุฉ ู„ู„ุทุจุงุนุฉ ูˆูŠู…ูƒู† ุญูุธู‡ุง ูƒู…ู„ู PDF</p>
 
107
  </div>
108
  </div>
109
  );
110
  };
111
 
112
- export default PrintInvoice;
 
 
 
 
 
 
 
 
8
  const apiUrl = import.meta.env.VITE_API_URL;
9
 
10
  const PrintInvoice = () => {
11
+ // Route should be: /print/invoice/:customerId/:invoiceId
12
+ const { customerId, invoiceId } = useParams();
13
  const { user } = useAuth();
14
  const companyName = user?.tenant?.name || "ู†ุธุงู… ุฅุฏุงุฑุฉ ุงู„ู…ุจูŠุนุงุช";
15
+ const companyAddress = user?.tenant?.address || "";
16
 
17
  const { data, isLoading } = useQuery({
18
+ queryKey: ["print-invoice", customerId, invoiceId],
19
+ queryFn: () =>
20
+ axios.get(`${apiUrl}/customers/${customerId}?includeInvoices=true`),
21
  refetchOnWindowFocus: false,
22
  });
23
 
24
+ const customer = data?.data;
25
+ // Find the specific invoice from the invoices array
26
+ const invoice = customer?.invoices?.find((inv) => inv._id === invoiceId);
27
+
28
  useEffect(() => {
29
+ if (invoice) setTimeout(() => window.print(), 500);
30
+ }, [invoice]);
 
 
 
 
31
 
32
  if (isLoading) return <LodderSpinner />;
33
 
34
+ if (!customer)
35
+ return <div style={{ padding: 20, textAlign: "center" }}>ู„ู… ูŠุชู… ุงู„ุนุซูˆุฑ ุนู„ู‰ ุงู„ุนู…ูŠู„</div>;
36
 
37
+ if (!invoice)
38
+ return <div style={{ padding: 20, textAlign: "center" }}>ู„ุง ุชูˆุฌุฏ ูุงุชูˆุฑุฉ ุจู‡ุฐุง ุงู„ุฑู‚ู…</div>;
39
 
40
  return (
41
+ <div
42
+ className="receipt-root"
43
+ dir="rtl"
44
+ style={{
45
+ width: "80mm",
46
+ margin: "0 auto",
47
+ fontFamily: "'Courier New', monospace",
48
+ fontSize: "12px",
49
+ color: "#000",
50
+ background: "#fff",
51
+ padding: "8px",
52
+ lineHeight: "1.5",
53
+ }}
54
+ >
55
  <style>{`
56
  @media print {
57
+ @page {
58
+ size: 80mm auto;
59
+ margin: 4mm;
60
+ }
61
+ body {
62
+ margin: 0;
63
+ background: white;
64
+ -webkit-print-color-adjust: exact;
65
+ }
66
  }
67
  `}</style>
68
 
69
+ {/* Header */}
70
+ <div style={{ textAlign: "center", borderBottom: "1px dashed #000", paddingBottom: 8, marginBottom: 8 }}>
71
+ <div style={{ fontSize: "15px", fontWeight: "bold", letterSpacing: "1px" }}>
72
+ {companyName}
73
+ </div>
74
+ {companyAddress && (
75
+ <div style={{ fontSize: "10px", marginTop: 2 }}>{companyAddress}</div>
76
+ )}
77
+ </div>
78
+
79
+ {/* Meta */}
80
+ <Row label="ูุงุชูˆุฑุฉ #" value={invoice.invoiceNumber || invoice._id.slice(-6).toUpperCase()} />
81
+ <Row label="ุงู„ุนู…ูŠู„" value={customer.name} />
82
+ <Row label="ุงู„ุชุงุฑูŠุฎ" value={new Date().toLocaleString("ar-EG")} />
83
+
84
+ {/* Items header */}
85
+ <div style={{ borderTop: "1px solid #000", borderBottom: "1px solid #000", marginTop: 8, padding: "4px 0", display: "flex", justifyContent: "space-between", fontSize: "10px" }}>
86
+ <span style={{ flex: 2 }}>ุงู„ุตู†ู</span>
87
+ <span style={{ flex: 1, textAlign: "center" }}>ูƒู…ูŠุฉ</span>
88
+ <span style={{ flex: 1, textAlign: "center" }}>ุณุนุฑ</span>
89
+ <span style={{ flex: 1, textAlign: "left" }}>ุฅุฌู…ุงู„ูŠ</span>
90
  </div>
91
 
92
+ {/* Items */}
93
+ {invoice.items.map((item, i) => (
94
+ <div
95
+ key={i}
96
+ style={{ display: "flex", justifyContent: "space-between", padding: "3px 0", borderBottom: "1px dashed #ccc", fontSize: "11px" }}
97
+ >
98
+ <span style={{ flex: 2, wordBreak: "break-word" }}>{item.name}</span>
99
+ <span style={{ flex: 1, textAlign: "center" }}>{item.quantity}</span>
100
+ <span style={{ flex: 1, textAlign: "center" }}>{item.price}</span>
101
+ <span style={{ flex: 1, textAlign: "left", fontWeight: "bold" }}>{item.total.toFixed(2)}</span>
102
  </div>
103
+ ))}
104
+
105
+ {/* Totals */}
106
+ <div style={{ marginTop: 8, borderTop: "1px solid #000", paddingTop: 6 }}>
107
+ <Row label="ุฅุฌู…ุงู„ูŠ ุงู„ูุงุชูˆุฑุฉ" value={`${invoice.totalAmount.toFixed(2)} ุฌ.ู…`} />
108
+ <Row label="ุงู„ู…ุฏููˆุนุงุช ุงู„ู…ุณุชู„ู…ุฉ" value={`${invoice.paidAmount.toFixed(2)} ุฌ.ู…`} />
109
+ <div style={{ display: "flex", justifyContent: "space-between", fontWeight: "bold", fontSize: "13px", borderTop: "2px solid #000", marginTop: 6, paddingTop: 6 }}>
110
+ <span>ุงู„ุฑุตูŠุฏ ุงู„ู…ุชุจู‚ูŠ</span>
111
+ <span>{invoice.remainingAmount.toFixed(2)} ุฌ.ู…</span>
112
  </div>
113
  </div>
114
 
115
+ {/* Payments log */}
116
+ {invoice.payments?.length > 0 && (
117
+ <div style={{ marginTop: 8, borderTop: "1px dashed #000", paddingTop: 6 }}>
118
+ <div style={{ fontSize: "10px", fontWeight: "bold", marginBottom: 4 }}>ุณุฌู„ ุงู„ู…ุฏููˆุนุงุช</div>
119
+ {invoice.payments.map((p, i) => (
120
+ <div key={i} style={{ display: "flex", justifyContent: "space-between", fontSize: "10px", marginBottom: 2 }}>
121
+ <span>{new Date(p.date).toLocaleDateString("ar-EG")}</span>
122
+ <span>{p.method === "cash" ? "ู†ู‚ุฏูŠ" : p.method}</span>
123
+ <span style={{ fontWeight: "bold" }}>{p.amount.toFixed(2)} ุฌ.ู…</span>
124
+ </div>
 
 
 
 
 
 
 
 
 
125
  ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  </div>
127
+ )}
128
 
129
+ {/* Footer */}
130
+ <div style={{ textAlign: "center", borderTop: "1px dashed #000", marginTop: 12, paddingTop: 8, fontSize: "10px" }}>
131
+ <div style={{ fontWeight: "bold" }}>ุดูƒุฑุงู‹ ู„ุงุฎุชูŠุงุฑูƒู… {companyName}</div>
132
+ <div style={{ marginTop: 4, color: "#555" }}>ู‡ุฐู‡ ุงู„ูุงุชูˆุฑุฉ ูˆุซูŠู‚ุฉ ุฑุณู…ูŠุฉ</div>
133
  </div>
134
  </div>
135
  );
136
  };
137
 
138
+ const Row = ({ label, value }) => (
139
+ <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3, fontSize: "11px" }}>
140
+ <span style={{ color: "#555" }}>{label}</span>
141
+ <span style={{ fontWeight: "bold", maxWidth: "60%", textAlign: "left", wordBreak: "break-word" }}>{value}</span>
142
+ </div>
143
+ );
144
+
145
+ export default PrintInvoice;
frontend/src/components/Reports/DailyReport.jsx CHANGED
@@ -17,10 +17,11 @@ const DailyReport = () => {
17
  queryFn: () => axios.get(`${apiUrl}/reports/daily`),
18
  refetchInterval: 30000,
19
  });
20
-
21
  if (isLoading) return <LodderSpinner />;
22
 
23
  const report = data?.data;
 
 
24
 
25
  return (
26
  <div className="space-y-6">
@@ -106,7 +107,7 @@ const DailyReport = () => {
106
  ุงู„ุฏูุนุงุช ุงู„ู…ุญุตู„ุฉ ู„ู„ุฅูŠุฑุงุฏุงุช
107
  </h3>
108
 
109
- {report?.recentPayments?.length === 0 ? (
110
  <div className="text-center py-12 bg-slate-50/50 rounded-2xl border-2 border-dashed border-slate-200">
111
  <p className="text-slate-500 font-bold">ู„ุง ุชูˆุฌุฏ ุฅูŠุฑุงุฏุงุช ูƒุงุด ู…ุณุฌู„ุฉ ุงู„ูŠูˆู…</p>
112
  </div>
@@ -121,7 +122,7 @@ const DailyReport = () => {
121
  </tr>
122
  </thead>
123
  <tbody className="divide-y divide-slate-100 bg-white">
124
- {report?.recentPayments?.map((payment, idx) => (
125
  <tr key={idx} className="hover:bg-slate-50">
126
  <td className="py-3 px-4 font-bold text-slate-700">{payment.customerName}</td>
127
  <td className="py-3 px-4 font-black text-emerald-600">+{payment.amount.toFixed(2)}</td>
@@ -145,7 +146,7 @@ const DailyReport = () => {
145
  ุณุฌู„ ุงู„ู…ุตุฑูˆูุงุช ูˆุงู„ู…ุณุญูˆุจุงุช ุงู„ู†ู‚ุฏูŠุฉ
146
  </h3>
147
 
148
- {report?.expensesList?.length === 0 ? (
149
  <div className="text-center py-12 bg-slate-50/50 rounded-2xl border-2 border-dashed border-slate-200">
150
  <p className="text-slate-500 font-bold">ู„ู… ูŠุชู… ุชุณุฌูŠู„ ุฃูŠ ู…ุตุงุฑูŠู ุญุชู‰ ุงู„ุขู†</p>
151
  </div>
@@ -160,7 +161,7 @@ const DailyReport = () => {
160
  </tr>
161
  </thead>
162
  <tbody className="divide-y divide-slate-100 bg-white">
163
- {report?.expensesList?.map((expense) => (
164
  <tr key={expense._id} className="hover:bg-slate-50 relative">
165
  <td className="py-3 px-4 font-bold text-slate-700">
166
  {expense.title}
 
17
  queryFn: () => axios.get(`${apiUrl}/reports/daily`),
18
  refetchInterval: 30000,
19
  });
 
20
  if (isLoading) return <LodderSpinner />;
21
 
22
  const report = data?.data;
23
+ const recentPayments = Array.isArray(report?.recentPayments) ? report.recentPayments : [];
24
+ const expensesList = Array.isArray(report?.expensesList) ? report.expensesList : [];
25
 
26
  return (
27
  <div className="space-y-6">
 
107
  ุงู„ุฏูุนุงุช ุงู„ู…ุญุตู„ุฉ ู„ู„ุฅูŠุฑุงุฏุงุช
108
  </h3>
109
 
110
+ {recentPayments?.length === 0 ? (
111
  <div className="text-center py-12 bg-slate-50/50 rounded-2xl border-2 border-dashed border-slate-200">
112
  <p className="text-slate-500 font-bold">ู„ุง ุชูˆุฌุฏ ุฅูŠุฑุงุฏุงุช ูƒุงุด ู…ุณุฌู„ุฉ ุงู„ูŠูˆู…</p>
113
  </div>
 
122
  </tr>
123
  </thead>
124
  <tbody className="divide-y divide-slate-100 bg-white">
125
+ {recentPayments?.map((payment, idx) => (
126
  <tr key={idx} className="hover:bg-slate-50">
127
  <td className="py-3 px-4 font-bold text-slate-700">{payment.customerName}</td>
128
  <td className="py-3 px-4 font-black text-emerald-600">+{payment.amount.toFixed(2)}</td>
 
146
  ุณุฌู„ ุงู„ู…ุตุฑูˆูุงุช ูˆุงู„ู…ุณุญูˆุจุงุช ุงู„ู†ู‚ุฏูŠุฉ
147
  </h3>
148
 
149
+ {expensesList?.length === 0 ? (
150
  <div className="text-center py-12 bg-slate-50/50 rounded-2xl border-2 border-dashed border-slate-200">
151
  <p className="text-slate-500 font-bold">ู„ู… ูŠุชู… ุชุณุฌูŠู„ ุฃูŠ ู…ุตุงุฑูŠู ุญุชู‰ ุงู„ุขู†</p>
152
  </div>
 
161
  </tr>
162
  </thead>
163
  <tbody className="divide-y divide-slate-100 bg-white">
164
+ {expensesList?.map((expense) => (
165
  <tr key={expense._id} className="hover:bg-slate-50 relative">
166
  <td className="py-3 px-4 font-bold text-slate-700">
167
  {expense.title}
frontend/src/components/Reports/ReportsWorkspace.jsx CHANGED
@@ -1,6 +1,7 @@
1
  import axios from "axios";
 
2
  import { useQuery } from "@tanstack/react-query";
3
- import { Download, Printer, Share2 } from "lucide-react";
4
  import LodderSpinner from "../../common/LoaderSpinner";
5
  import { useAuth } from "../../Context/AuthContext";
6
  import { downloadCsv, printHtmlDocument } from "../../utils/exports";
@@ -8,45 +9,181 @@ import { formatCurrency, formatDate, formatDateTime } from "../../utils/formatte
8
  import { openWhatsAppMessage } from "../../utils/whatsapp";
9
 
10
  const apiUrl = import.meta.env.VITE_API_URL;
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  const ReportsWorkspace = () => {
13
  const { user } = useAuth();
14
  const currency = user?.tenant?.settings?.currency || "EGP";
15
  const companyName = user?.tenant?.name || "ุงู„ุดุฑูƒุฉ";
16
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  const { data: overviewData, isLoading: overviewLoading } = useQuery({
18
- queryKey: ["reports", "overview"],
19
- queryFn: () => axios.get(`${apiUrl}/reports/overview`),
 
 
 
 
 
 
 
 
 
20
  refetchOnWindowFocus: false,
21
  });
 
22
  const { data: customersData, isLoading: customersLoading } = useQuery({
23
- queryKey: ["customers", "all"],
24
- queryFn: () => axios.get(`${apiUrl}/customers`, { params: { limit: 1000 } }),
 
25
  refetchOnWindowFocus: false,
 
 
26
  });
27
  const { data: productsData, isLoading: productsLoading } = useQuery({
28
- queryKey: ["products", "all"],
29
- queryFn: () => axios.get(`${apiUrl}/products`, { params: { limit: 1000 } }),
 
30
  refetchOnWindowFocus: false,
31
  });
 
32
  const { data: suppliersData, isLoading: suppliersLoading } = useQuery({
33
- queryKey: ["suppliers", "all"],
34
- queryFn: () => axios.get(`${apiUrl}/suppliers`, { params: { limit: 1000 } }),
 
35
  refetchOnWindowFocus: false,
36
  });
37
 
 
38
  const overview = overviewData?.data;
39
- const customers = customersData?.data?.data || [];
40
- const products = productsData?.data?.data || [];
41
- const suppliers = suppliersData?.data?.data || [];
 
 
 
 
42
  const metrics = overview?.metrics || {};
 
 
 
 
 
 
 
 
 
 
43
  const financialRows = [
44
- { metric: "ุงู„ู…ุจูŠุนุงุช ููŠ ุงู„ูุชุฑุฉ", value: formatCurrency(metrics.salesInRange, currency) },
45
- { metric: "ุงู„ุชุญุตูŠู„ุงุช ููŠ ุงู„ูุชุฑุฉ", value: formatCurrency(metrics.collectionsInRange, currency) },
46
- { metric: "ุงู„ู…ุตุฑูˆูุงุช ููŠ ุงู„ูุชุฑุฉ", value: formatCurrency(metrics.expensesInRange, currency) },
47
- { metric: "ุตุงููŠ ุงู„ุชุฏูู‚ ุงู„ู†ู‚ุฏูŠ", value: formatCurrency(metrics.netCashFlow, currency) },
48
- { metric: "ุงู„ู…ุณุชุญู‚ุงุช ุงู„ู…ุนู„ู‚ุฉ", value: formatCurrency(metrics.outstandingReceivables, currency) },
49
- { metric: "ู…ุณุชุญู‚ุงุช ุงู„ู…ูˆุฑุฏูŠู†", value: formatCurrency(metrics.supplierOutstanding, currency) },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  ];
51
 
52
  if (overviewLoading || customersLoading || productsLoading || suppliersLoading) {
@@ -58,32 +195,46 @@ const ReportsWorkspace = () => {
58
  `ุชู‚ุงุฑูŠุฑ ${companyName}`,
59
  `
60
  <h1>ุงู„ุชู‚ุฑูŠุฑ ุงู„ุชุดุบูŠู„ูŠ - ${companyName}</h1>
61
- <p>ุชู… ุงู„ุฅู†ุด๏ฟฝ๏ฟฝุก ${formatDateTime(new Date())}</p>
 
62
  <div class="section">
63
  <h2>ุงู„ู…ู„ุฎุต ุงู„ู…ุงู„ูŠ</h2>
64
  <div class="kpi-grid">
65
- ${financialRows.map((row) => `<div class="kpi-card"><strong>${row.metric}</strong><div>${row.value}</div></div>`).join("")}
 
 
 
 
 
66
  </div>
67
  </div>
68
  <div class="section">
69
  <h2>ู…ุณุชุญู‚ุงุช ุงู„ุนู…ู„ุงุก</h2>
70
- ${tableHtml(
71
- ["ุงู„ุนู…ูŠู„", "ุงู„ููˆุงุชูŠุฑ", "ุงู„ู…ุณุชุญู‚ุงุช"],
72
- customers.map((customer) => [customer.name, customer.invoices?.length || 0, formatCurrency(customer.totalDebt || 0, currency)])
73
- )}
 
 
 
 
 
 
 
 
74
  </div>
75
  <div class="section">
76
  <h2>ุงู„ู…ุฎุฒูˆู†</h2>
77
  ${tableHtml(
78
  ["ุงู„ู…ู†ุชุฌ", "ุงู„ู…ุฎุฒูˆู†", "ุงู„ุญุฏ ุงู„ุฃุฏู†ู‰", "ุณุนุฑ ุงู„ูˆุญุฏุฉ"],
79
- products.map((product) => [product.name, product.stock, product.lowStockThreshold, formatCurrency(product.price, currency)])
80
  )}
81
  </div>
82
  <div class="section">
83
  <h2>ุงู„ู…ูˆุฑุฏูˆู†</h2>
84
  ${tableHtml(
85
  ["ุงู„ู…ูˆุฑุฏ", "ุงู„ู…ุณุชุญู‚ุงุช"],
86
- suppliers.map((supplier) => [supplier.name, formatCurrency(supplier.totalDebt || 0, currency)])
87
  )}
88
  </div>
89
  `
@@ -91,126 +242,209 @@ const ReportsWorkspace = () => {
91
  };
92
 
93
  return (
94
- <div className="space-y-6">
 
 
95
  <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
96
- <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
97
  <div>
98
  <h3 className="text-xl font-black text-slate-900">ุงู„ุชู‚ุงุฑูŠุฑ ุงู„ุชูุตูŠู„ูŠุฉ</h3>
99
- <p className="text-sm text-slate-500">ุชุตุฏูŠุฑ ูˆุทุจุงุนุฉ ูˆู…ุดุงุฑูƒุฉ ุงู„ุญุงู„ุฉ ุงู„ู…ุงู„ูŠุฉ ูˆุงู„ุชุดุบูŠู„ูŠุฉ ู„ู„ุดุฑูƒุฉ.</p>
100
  </div>
101
- <div className="flex flex-wrap gap-3">
102
- <ActionButton onClick={() => downloadCsv("financial-summary.csv", [{ key: "metric", label: "ุงู„ู…ุคุดุฑ" }, { key: "value", label: "ุงู„ู‚ูŠู…ุฉ" }], financialRows)} icon={Download} label="ุชุตุฏูŠุฑ ุงู„ู…ู„ุฎุต" />
103
- <ActionButton onClick={printReport} icon={Printer} label="ุทุจุงุนุฉ ุงู„ุชู‚ุฑูŠุฑ" />
104
- <button
105
- type="button"
106
- onClick={() =>
107
- openWhatsAppMessage(
108
- [
109
- `ู„ู‚ุทุฉ ุชู‚ุฑูŠุฑ ${companyName}`,
110
- `ุงู„ู…ุจูŠุนุงุช: ${formatCurrency(metrics.salesInRange, currency)}`,
111
- `ุงู„ุชุญุตูŠู„ุงุช: ${formatCurrency(metrics.collectionsInRange, currency)}`,
112
- `ุงู„ู…ุตุฑูˆูุงุช: ${formatCurrency(metrics.expensesInRange, currency)}`,
113
- `ุงู„ู…ุณุชุญู‚ุงุช ุงู„ู…ุนู„ู‚ุฉ: ${formatCurrency(metrics.outstandingReceivables, currency)}`,
114
- `ุฃุตู†ุงู ู…ุฎุฒูˆู† ู…ู†ุฎูุถ: ${metrics.lowStockCount || 0}`,
115
- ].join("\n")
116
- )
117
- }
118
- className="flex h-11 items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-4 font-bold text-white transition hover:bg-emerald-700"
119
- >
120
- <Share2 size={16} />
121
- ู…ุดุงุฑูƒุฉ ุงู„ู…ู„ุฎุต
122
- </button>
123
  </div>
124
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  </section>
126
 
127
- <Section title="ุงู„ู…ู„ุฎุต ุงู„ู…ุงู„ูŠ">
 
128
  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
129
  {financialRows.map((row) => (
130
  <div key={row.metric} className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
131
- <p className="text-sm font-bold text-slate-500">{row.metric}</p>
132
- <p className="mt-2 text-2xl font-black text-slate-900">{row.value}</p>
 
133
  </div>
134
  ))}
135
  </div>
136
  </Section>
137
 
138
- <Section title="ู…ุณุชุญู‚ุงุช ุงู„ุนู…ู„ุงุก">
 
139
  <SimpleTable
140
- headers={["ุงู„ุนู…ูŠู„", "ุงู„ููˆุงุชูŠุฑ", "ุงู„ู…ุณุชุญู‚ุงุช"]}
141
- rows={customers.map((customer) => [
142
- customer.name,
143
- customer.invoices?.length || 0,
144
- formatCurrency(customer.totalDebt || 0, currency),
 
145
  ])}
146
  />
 
147
  </Section>
148
 
 
149
  <div className="grid gap-6 xl:grid-cols-2">
150
- <Section title="ุชู‚ุงุฑูŠุฑ ุงู„ู…ุฎุฒูˆู†">
151
  <SimpleTable
152
  headers={["ุงู„ู…ู†ุชุฌ", "ุงู„ู…ุฎุฒูˆู†", "ุงู„ุญุฏ ุงู„ุฃุฏู†ู‰", "ุณุนุฑ ุงู„ูˆุญุฏุฉ", "ุงู„ุญุงู„ุฉ"]}
153
- rows={products.map((product) => [
154
- product.name,
155
- product.stock,
156
- product.lowStockThreshold,
157
- formatCurrency(product.price, currency),
158
- product.isLowStock ? "ู…ุฎุฒูˆู† ู…ู†ุฎูุถ" : "ุณู„ูŠู…",
 
 
 
 
 
 
 
 
159
  ])}
160
  />
 
161
  </Section>
162
 
163
- <Section title="ู…ุณุชุญู‚ุงุช ุงู„ู…ูˆุฑุฏูŠู†">
164
  <SimpleTable
165
  headers={["ุงู„ู…ูˆุฑุฏ", "ุงู„ู…ุณุชุญู‚ุงุช"]}
166
- rows={suppliers.map((supplier) => [supplier.name, formatCurrency(supplier.totalDebt || 0, currency)])}
 
 
 
167
  />
 
168
  </Section>
169
  </div>
170
 
171
- <Section title="ู†ุดุงุท ุงู„ู…ุฏููˆุนุงุช ูˆุงู„ููˆุงุชูŠุฑ ุงู„ุฃุฎูŠุฑ">
 
172
  <div className="grid gap-6 xl:grid-cols-2">
173
- <SimpleTable
174
- headers={["ุงู„ุนู…ูŠู„", "ุงู„ู…ุจู„ุบ", "ุงู„ุชุงุฑูŠุฎ"]}
175
- rows={(overview?.recentPayments || []).map((payment) => [
176
- payment.customerName,
177
- formatCurrency(payment.amount, currency),
178
- formatDateTime(payment.date),
179
- ])}
180
- />
181
- <SimpleTable
182
- headers={["ุงู„ูุงุชูˆุฑุฉ", "ุงู„ุนู…ูŠู„", "ุงู„ุญุงู„ุฉ", "ุชุงุฑูŠุฎ ุงู„ุฅู†ุดุงุก"]}
183
- rows={(overview?.recentInvoices || []).map((invoice) => [
184
- invoice.invoiceNumber,
185
- invoice.customerName,
186
- invoice.status,
187
- formatDate(invoice.createdAt),
188
- ])}
189
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  </div>
191
  </Section>
192
  </div>
193
  );
194
  };
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  const ActionButton = ({ onClick, icon, label }) => {
197
- const IconComponent = icon;
198
  return (
199
- <button
200
- type="button"
201
- onClick={onClick}
202
- className="flex h-11 items-center justify-center gap-2 rounded-2xl border border-slate-200 bg-slate-50 px-4 font-bold text-slate-700 transition hover:bg-slate-100"
203
- >
204
- <IconComponent size={16} />
205
- {label}
206
- </button>
207
  );
208
  };
209
 
210
- const Section = ({ title, children }) => (
211
  <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
212
  <div className="mb-5">
213
  <h3 className="text-lg font-black text-slate-900">{title}</h3>
 
214
  </div>
215
  {children}
216
  </section>
@@ -221,23 +455,23 @@ const SimpleTable = ({ headers, rows }) => (
221
  <table className="min-w-full border-collapse">
222
  <thead>
223
  <tr className="border-b border-slate-200 text-right text-sm font-bold text-slate-500">
224
- {headers.map((header) => (
225
- <th key={header} className="px-3 py-3">{header}</th>
226
  ))}
227
  </tr>
228
  </thead>
229
  <tbody>
230
  {rows.length ? (
231
- rows.map((row, index) => (
232
- <tr key={`${headers[0]}-${index}`} className="border-b border-slate-100 text-sm text-slate-700">
233
- {row.map((cell, cellIndex) => (
234
- <td key={`${index}-${cellIndex}`} className="px-3 py-4">{cell}</td>
235
  ))}
236
  </tr>
237
  ))
238
  ) : (
239
  <tr>
240
- <td colSpan={headers.length} className="px-3 py-10 text-center text-sm font-medium text-slate-500">
241
  ู„ุง ุชูˆุฌุฏ ุจูŠุงู†ุงุช ู…ุชุงุญุฉ.
242
  </td>
243
  </tr>
@@ -246,16 +480,26 @@ const SimpleTable = ({ headers, rows }) => (
246
  </table>
247
  </div>
248
  );
249
-
250
- const tableHtml = (headers, rows) => `
251
- <table>
252
- <thead>
253
- <tr>${headers.map((header) => `<th>${header}</th>`).join("")}</tr>
254
- </thead>
255
- <tbody>
256
- ${rows.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("")}
257
- </tbody>
258
- </table>
 
 
 
 
 
 
 
 
 
 
 
259
  `;
260
-
261
- export default ReportsWorkspace;
 
1
  import axios from "axios";
2
+ import { useState } from "react";
3
  import { useQuery } from "@tanstack/react-query";
4
+ import { Download, Printer, Share2, ChevronRight, ChevronLeft, Calendar } from "lucide-react";
5
  import LodderSpinner from "../../common/LoaderSpinner";
6
  import { useAuth } from "../../Context/AuthContext";
7
  import { downloadCsv, printHtmlDocument } from "../../utils/exports";
 
9
  import { openWhatsAppMessage } from "../../utils/whatsapp";
10
 
11
  const apiUrl = import.meta.env.VITE_API_URL;
12
+ const LIMIT = 5;
13
 
14
+ // โ”€โ”€ helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
15
+ const toArr = (val) => (Array.isArray(val) ? val : []);
16
+
17
+ const getDefaultStart = () => {
18
+ const d = new Date();
19
+ d.setDate(d.getDate() - 29);
20
+ return d.toISOString().split("T")[0];
21
+ };
22
+ const getDefaultEnd = () => new Date().toISOString().split("T")[0];
23
+
24
+ const formatRangeLabel = (start, end) => {
25
+ const opts = { day: "numeric", month: "long", year: "numeric" };
26
+ const s = new Date(start).toLocaleDateString("ar-EG", opts);
27
+ const e = new Date(end).toLocaleDateString("ar-EG", opts);
28
+ return `${s} โ€” ${e}`;
29
+ };
30
+
31
+ // โ”€โ”€ Pagination component โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
32
+ const Pagination = ({ pagination, page, setPage }) => {
33
+ if (!pagination || pagination.totalPages <= 1) return null;
34
+ const { total, totalPages } = pagination;
35
+ const pages = Array.from({ length: totalPages }, (_, i) => i + 1);
36
+
37
+ return (
38
+ <div className="flex items-center justify-between mt-4 pt-4 border-t border-slate-100">
39
+ <span className="text-xs font-bold text-slate-400">
40
+ {total} ู†ุชูŠุฌุฉ โ€ข ุตูุญุฉ {page} ู…ู† {totalPages}
41
+ </span>
42
+ <div className="flex gap-2">
43
+ <button
44
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
45
+ disabled={page === 1}
46
+ className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 disabled:opacity-30 disabled:cursor-not-allowed"
47
+ >
48
+ <ChevronRight size={16} />
49
+ </button>
50
+ {/* Number buttons */}
51
+ {pages.map((p) => (
52
+ <button
53
+ key={p}
54
+ onClick={() => setPage(p)}
55
+ className={`w-8 h-8 rounded-lg text-sm font-bold transition-all ${p === page
56
+ ? "bg-slate-800 text-white border border-slate-800"
57
+ : "border border-slate-200 text-slate-500 hover:bg-slate-50"
58
+ }`}
59
+ >
60
+ {p}
61
+ </button>
62
+ ))}
63
+ <button
64
+ onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
65
+ disabled={page === totalPages}
66
+ className="p-1.5 rounded-lg border border-slate-200 text-slate-500 hover:bg-slate-50 disabled:opacity-30 disabled:cursor-not-allowed"
67
+ >
68
+ <ChevronLeft size={16} />
69
+ </button>
70
+ </div>
71
+ </div>
72
+ );
73
+ };
74
+
75
+ // โ”€โ”€ Main component โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
76
  const ReportsWorkspace = () => {
77
  const { user } = useAuth();
78
  const currency = user?.tenant?.settings?.currency || "EGP";
79
  const companyName = user?.tenant?.name || "ุงู„ุดุฑูƒุฉ";
80
 
81
+ // date range state
82
+ const [startDate, setStartDate] = useState(getDefaultStart());
83
+ const [endDate, setEndDate] = useState(getDefaultEnd());
84
+
85
+ // pagination state per table
86
+ const [customersPage, setCustomersPage] = useState(1);
87
+ const [productsPage, setProductsPage] = useState(1);
88
+ const [suppliersPage, setSuppliersPage] = useState(1);
89
+ const [paymentsPage, setPaymentsPage] = useState(1);
90
+ const [invoicesPage, setInvoicesPage] = useState(1);
91
+
92
+ // โ”€โ”€ queries โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
93
  const { data: overviewData, isLoading: overviewLoading } = useQuery({
94
+ queryKey: ["reports", "overview", startDate, endDate, paymentsPage, invoicesPage],
95
+ queryFn: () =>
96
+ axios.get(`${apiUrl}/reports/overview`, {
97
+ params: {
98
+ start: startDate,
99
+ end: endDate,
100
+ limit: LIMIT,
101
+ paymentsPage,
102
+ invoicesPage,
103
+ },
104
+ }),
105
  refetchOnWindowFocus: false,
106
  });
107
+
108
  const { data: customersData, isLoading: customersLoading } = useQuery({
109
+ queryKey: ["customers", "paginated", customersPage],
110
+ queryFn: () =>
111
+ axios.get(`${apiUrl}/customers`, { params: { limit: LIMIT, page: customersPage } }),
112
  refetchOnWindowFocus: false,
113
+ keepPreviousData: true,
114
+ staleTime: 2 * 60 * 1000, // 5 minutes cache
115
  });
116
  const { data: productsData, isLoading: productsLoading } = useQuery({
117
+ queryKey: ["products", "paginated", productsPage],
118
+ queryFn: () =>
119
+ axios.get(`${apiUrl}/products`, { params: { limit: LIMIT, page: productsPage } }),
120
  refetchOnWindowFocus: false,
121
  });
122
+
123
  const { data: suppliersData, isLoading: suppliersLoading } = useQuery({
124
+ queryKey: ["suppliers", "paginated", suppliersPage],
125
+ queryFn: () =>
126
+ axios.get(`${apiUrl}/suppliers`, { params: { limit: LIMIT, page: suppliersPage } }),
127
  refetchOnWindowFocus: false,
128
  });
129
 
130
+ // โ”€โ”€ derived data โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
131
  const overview = overviewData?.data;
132
+ const customers = toArr(customersData?.data?.data);
133
+ const customersPagination = customersData?.data?.pagination;
134
+ const products = toArr(productsData?.data?.data);
135
+ const productsPagination = productsData?.data?.pagination;
136
+ const suppliers = toArr(suppliersData?.data?.data);
137
+ const suppliersPagination = suppliersData?.data?.pagination;
138
+
139
  const metrics = overview?.metrics || {};
140
+ const recentPayments = toArr(overview?.recentPayments?.data);
141
+ const paymentsPagination = overview?.recentPayments?.pagination;
142
+ const recentInvoices = toArr(overview?.recentInvoices?.data);
143
+ const invoicesPagination = overview?.recentInvoices?.pagination;
144
+
145
+ // actual range returned by backend (more reliable than local state)
146
+ const rangeLabel = overview?.dateRange
147
+ ? formatRangeLabel(overview.dateRange.start, overview.dateRange.end)
148
+ : formatRangeLabel(startDate, endDate);
149
+
150
  const financialRows = [
151
+ {
152
+ metric: "ุงู„ู…ุจูŠุนุงุช",
153
+ sub: rangeLabel,
154
+ value: formatCurrency(metrics.salesInRange, currency),
155
+ color: "text-indigo-600",
156
+ },
157
+ {
158
+ metric: "ุงู„ุชุญุตูŠู„ุงุช ุงู„ู†ู‚ุฏูŠุฉ",
159
+ sub: rangeLabel,
160
+ value: formatCurrency(metrics.collectionsInRange, currency),
161
+ color: "text-emerald-600",
162
+ },
163
+ {
164
+ metric: "ุงู„ู…ุตุฑูˆูุงุช",
165
+ sub: rangeLabel,
166
+ value: formatCurrency(metrics.expensesInRange, currency),
167
+ color: "text-rose-600",
168
+ },
169
+ {
170
+ metric: "ุตุงููŠ ุงู„ุชุฏูู‚ ุงู„ู†ู‚ุฏูŠ",
171
+ sub: "ุงู„ุชุญุตูŠู„ุงุช ู†ุงู‚ุต ุงู„ู…ุตุฑูˆูุงุช",
172
+ value: formatCurrency(metrics.netCashFlow, currency),
173
+ color: metrics.netCashFlow >= 0 ? "text-emerald-600" : "text-rose-600",
174
+ },
175
+ {
176
+ metric: "ุงู„ู…ุณุชุญู‚ุงุช ุนู„ู‰ ุงู„ุนู…ู„ุงุก",
177
+ sub: "ุฅุฌู…ุงู„ูŠ ุงู„ุฑุตูŠุฏ ุงู„ู…ุชุจู‚ูŠ ุบูŠุฑ ุงู„ู…ุณุฏุฏ",
178
+ value: formatCurrency(metrics.outstandingReceivables, currency),
179
+ color: "text-amber-600",
180
+ },
181
+ {
182
+ metric: "ุงู„ู…ุณุชุญู‚ุงุช ู„ู„ู…ูˆุฑุฏูŠู†",
183
+ sub: "ุฅุฌู…ุงู„ูŠ ู…ุง ู†ุณุชุญู‚ู‡ ู„ู…ูˆุฑุฏูŠู†ู†ุง",
184
+ value: formatCurrency(metrics.supplierOutstanding, currency),
185
+ color: "text-slate-700",
186
+ },
187
  ];
188
 
189
  if (overviewLoading || customersLoading || productsLoading || suppliersLoading) {
 
195
  `ุชู‚ุงุฑูŠุฑ ${companyName}`,
196
  `
197
  <h1>ุงู„ุชู‚ุฑูŠุฑ ุงู„ุชุดุบูŠู„ูŠ - ${companyName}</h1>
198
+ <p>ุงู„ูุชุฑุฉ: ${rangeLabel}</p>
199
+ <p>ุชู… ุงู„ุฅู†ุดุงุก: ${formatDateTime(new Date())}</p>
200
  <div class="section">
201
  <h2>ุงู„ู…ู„ุฎุต ุงู„ู…ุงู„ูŠ</h2>
202
  <div class="kpi-grid">
203
+ ${financialRows
204
+ .map(
205
+ (row) =>
206
+ `<div class="kpi-card"><strong>${row.metric}</strong><small style="display:block;color:#888">${row.sub}</small><div>${row.value}</div></div>`
207
+ )
208
+ .join("")}
209
  </div>
210
  </div>
211
  <div class="section">
212
  <h2>ู…ุณุชุญู‚ุงุช ุงู„ุนู…ู„ุงุก</h2>
213
+ ${tableHtml(
214
+ ["#", "ุงู„ุนู…ูŠู„", "ุงู„ููˆุงุชูŠุฑ", "ุงู„ู…ุณุชุญู‚ุงุช"],
215
+ customers
216
+ .filter(c => Number(c.totalDebt) > 0) // keep only customers with debt
217
+ .map((c, index) => [
218
+ index + 1, // serial number
219
+ c.name,
220
+ c.invoices?.length || 0,
221
+ formatCurrency(Number(c.totalDebt), currency)
222
+ ]),
223
+ true // add serial column
224
+ )}
225
  </div>
226
  <div class="section">
227
  <h2>ุงู„ู…ุฎุฒูˆู†</h2>
228
  ${tableHtml(
229
  ["ุงู„ู…ู†ุชุฌ", "ุงู„ู…ุฎุฒูˆู†", "ุงู„ุญุฏ ุงู„ุฃุฏู†ู‰", "ุณุนุฑ ุงู„ูˆุญุฏุฉ"],
230
+ products.map((p) => [p.name, p.stock, p.lowStockThreshold, formatCurrency(p.price, currency)])
231
  )}
232
  </div>
233
  <div class="section">
234
  <h2>ุงู„ู…ูˆุฑุฏูˆู†</h2>
235
  ${tableHtml(
236
  ["ุงู„ู…ูˆุฑุฏ", "ุงู„ู…ุณุชุญู‚ุงุช"],
237
+ suppliers.map((s) => [s.name, formatCurrency(s.totalDebt || 0, currency)])
238
  )}
239
  </div>
240
  `
 
242
  };
243
 
244
  return (
245
+ <div className="space-y-6" dir="rtl">
246
+
247
+ {/* โ”€โ”€ Header & actions โ”€โ”€ */}
248
  <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
249
+ <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
250
  <div>
251
  <h3 className="text-xl font-black text-slate-900">ุงู„ุชู‚ุงุฑูŠุฑ ุงู„ุชูุตูŠู„ูŠุฉ</h3>
252
+ <p className="text-sm text-slate-500 mt-1">ุชุตุฏูŠุฑ ูˆุทุจุงุนุฉ ูˆู…ุดุงุฑูƒุฉ ุงู„ุญุงู„ุฉ ุงู„ู…ุงู„ูŠุฉ ูˆุงู„ุชุดุบูŠู„ูŠุฉ ู„ู„ุดุฑูƒุฉ.</p>
253
  </div>
254
+
255
+ {/* Date range picker */}
256
+ <div className="flex flex-wrap items-center gap-3">
257
+ <div className="flex items-center gap-2 bg-slate-50 border border-slate-200 rounded-2xl px-4 py-2">
258
+ <Calendar size={16} className="text-slate-400 shrink-0" />
259
+ <input
260
+ type="date"
261
+ value={startDate}
262
+ onChange={(e) => { setStartDate(e.target.value); setPaymentsPage(1); setInvoicesPage(1); }}
263
+ className="bg-transparent text-sm font-bold text-slate-700 outline-none"
264
+ />
265
+ <span className="text-slate-400 text-sm">โ€”</span>
266
+ <input
267
+ type="date"
268
+ value={endDate}
269
+ onChange={(e) => { setEndDate(e.target.value); setPaymentsPage(1); setInvoicesPage(1); }}
270
+ className="bg-transparent text-sm font-bold text-slate-700 outline-none"
271
+ />
272
+ </div>
 
 
 
273
  </div>
274
  </div>
275
+
276
+ {/* Action buttons */}
277
+ <div className="flex flex-wrap gap-3 mt-4 pt-4 border-t border-slate-100">
278
+ <ActionButton
279
+ onClick={() =>
280
+ downloadCsv(
281
+ "financial-summary.csv",
282
+ [{ key: "metric", label: "ุงู„ู…ุคุดุฑ" }, { key: "sub", label: "ุงู„ูุชุฑุฉ" }, { key: "value", label: "ุงู„ู‚ูŠู…ุฉ" }],
283
+ financialRows
284
+ )
285
+ }
286
+ icon={Download}
287
+ label="ุชุตุฏูŠุฑ ุงู„ู…ู„ุฎุต"
288
+ />
289
+ <ActionButton onClick={printReport} icon={Printer} label="ุทุจุงุนุฉ ุงู„ุชู‚ุฑูŠุฑ" />
290
+ <button
291
+ type="button"
292
+ onClick={() =>
293
+ openWhatsAppMessage(
294
+ [
295
+ `๐Ÿ“Š ู„ู‚ุทุฉ ุชู‚ุฑูŠุฑ ${companyName}`,
296
+ `๐Ÿ“… ุงู„ูุชุฑุฉ: ${rangeLabel}`,
297
+ `๐Ÿ’ฐ ุงู„ู…ุจูŠุนุงุช: ${formatCurrency(metrics.salesInRange, currency)}`,
298
+ `โœ… ุงู„ุชุญุตูŠู„ุงุช: ${formatCurrency(metrics.collectionsInRange, currency)}`,
299
+ `๐Ÿ”ด ุงู„ู…ุตุฑูˆูุงุช: ${formatCurrency(metrics.expensesInRange, currency)}`,
300
+ `๐Ÿ“Œ ุงู„ู…ุณุชุญู‚ุงุช ุนู„ู‰ ุงู„ุนู…ู„ุงุก: ${formatCurrency(metrics.outstandingReceivables, currency)}`,
301
+ `๐Ÿ“ฆ ุฃุตู†ุงู ู…ุฎุฒูˆู† ู…ู†ุฎูุถ: ${metrics.lowStockCount || 0}`,
302
+ ].join("\n")
303
+ )
304
+ }
305
+ className="flex h-11 items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-4 font-bold text-white transition hover:bg-emerald-700"
306
+ >
307
+ <Share2 size={16} />
308
+ ู…ุดุงุฑูƒุฉ ุงู„ู…ู„ุฎุต
309
+ </button>
310
+ </div>
311
  </section>
312
 
313
+ {/* โ”€โ”€ Financial summary โ”€โ”€ */}
314
+ <Section title="ุงู„ู…ู„ุฎุต ุงู„ู…ุงู„ูŠ" subtitle={`ุจูŠุงู†ุงุช ุงู„ูุชุฑุฉ: ${rangeLabel}`}>
315
  <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
316
  {financialRows.map((row) => (
317
  <div key={row.metric} className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
318
+ <p className="text-sm font-black text-slate-700">{row.metric}</p>
319
+ <p className="text-xs text-slate-400 font-medium mt-0.5 mb-2">{row.sub}</p>
320
+ <p className={`text-2xl font-black ${row.color}`}>{row.value}</p>
321
  </div>
322
  ))}
323
  </div>
324
  </Section>
325
 
326
+ {/* โ”€โ”€ Customer receivables โ”€โ”€ */}
327
+ <Section title="ู…ุณุชุญู‚ุงุช ุงู„ุนู…ู„ุงุก" subtitle="ุงู„ุฑุตูŠุฏ ุงู„ู…ุชุจู‚ูŠ ุบูŠุฑ ุงู„ู…ุณุฏุฏ ู„ูƒู„ ุนู…ูŠู„">
328
  <SimpleTable
329
+ headers={["#", "ุงู„ุนู…ูŠู„", "ุนุฏุฏ ุงู„ููˆุงุชูŠุฑ", "ุงู„ู…ุณุชุญู‚ุงุช"]}
330
+ rows={customers.map((c, index) => [
331
+ index + 1 + (customersPage - 1) * LIMIT, // <-- correct global index
332
+ c.name,
333
+ c.invoices?.length || 0,
334
+ formatCurrency(c.totalDebt || 0, currency),
335
  ])}
336
  />
337
+ <Pagination pagination={customersPagination} page={customersPage} setPage={setCustomersPage} />
338
  </Section>
339
 
340
+ {/* โ”€โ”€ Inventory & Suppliers โ”€โ”€ */}
341
  <div className="grid gap-6 xl:grid-cols-2">
342
+ <Section title="ุชู‚ุงุฑูŠุฑ ุงู„ู…ุฎุฒูˆู†" subtitle="ุงู„ูƒู…ูŠุงุช ุงู„ู…ุชุงุญุฉ ูˆุชู†ุจูŠู‡ุงุช ุงู„ู†ูุงุฏ">
343
  <SimpleTable
344
  headers={["ุงู„ู…ู†ุชุฌ", "ุงู„ู…ุฎุฒูˆู†", "ุงู„ุญุฏ ุงู„ุฃุฏู†ู‰", "ุณุนุฑ ุงู„ูˆุญุฏุฉ", "ุงู„ุญุงู„ุฉ"]}
345
+ rows={products.map((p) => [
346
+ p.name,
347
+ p.stock,
348
+ p.lowStockThreshold,
349
+ formatCurrency(p.price, currency),
350
+ p.isLowStock ? (
351
+ <span className="text-xs font-bold text-rose-600 bg-rose-50 px-2 py-1 rounded-lg border border-rose-100">
352
+ ู…ุฎุฒูˆู† ู…ู†ุฎูุถ
353
+ </span>
354
+ ) : (
355
+ <span className="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-1 rounded-lg border border-emerald-100">
356
+ ุณู„ูŠู…
357
+ </span>
358
+ ),
359
  ])}
360
  />
361
+ <Pagination pagination={productsPagination} page={productsPage} setPage={setProductsPage} />
362
  </Section>
363
 
364
+ <Section title="ู…ุณุชุญู‚ุงุช ุงู„ู…ูˆุฑุฏูŠู†" subtitle="ู…ุง ูŠุณุชุญู‚ู‡ ุงู„ู…ูˆุฑุฏ ู…ู† ู…ุฏููˆุนุงุช">
365
  <SimpleTable
366
  headers={["ุงู„ู…ูˆุฑุฏ", "ุงู„ู…ุณุชุญู‚ุงุช"]}
367
+ rows={suppliers.map((s) => [
368
+ s.name,
369
+ formatCurrency(s.totalDebt || 0, currency),
370
+ ])}
371
  />
372
+ <Pagination pagination={suppliersPagination} page={suppliersPage} setPage={setSuppliersPage} />
373
  </Section>
374
  </div>
375
 
376
+ {/* โ”€โ”€ Recent activity โ”€โ”€ */}
377
+ <Section title="ู†ุดุงุท ุงู„ู…ุฏููˆุนุงุช ูˆุงู„ููˆุงุชูŠุฑ" subtitle={`ุงู„ู…ุนุงู…ู„ุงุช ุฎู„ุงู„: ${rangeLabel}`}>
378
  <div className="grid gap-6 xl:grid-cols-2">
379
+
380
+ {/* Payments */}
381
+ <div>
382
+ <p className="text-sm font-black text-slate-600 mb-3">ุขุฎุฑ ุงู„ู…ุฏููˆุนุงุช ุงู„ู…ุณุชู„ู…ุฉ</p>
383
+ <SimpleTable
384
+ headers={["ุงู„ุนู…ูŠู„", "ุงู„ู…ุจู„ุบ", "ุงู„ุชุงุฑูŠุฎ"]}
385
+ rows={recentPayments.map((p) => [
386
+ p.customerName,
387
+ formatCurrency(p.amount, currency),
388
+ formatDateTime(p.date),
389
+ ])}
390
+ />
391
+ <Pagination pagination={paymentsPagination} page={paymentsPage} setPage={(fn) => { setPaymentsPage(fn); }} />
392
+ </div>
393
+
394
+ {/* Invoices */}
395
+ <div>
396
+ <p className="text-sm font-black text-slate-600 mb-3">ุขุฎุฑ ุงู„ููˆุงุชูŠุฑ ุงู„ู…ู†ุดุฃุฉ</p>
397
+ <SimpleTable
398
+ headers={["ุฑู‚ู… ุงู„ูุงุชูˆุฑุฉ", "ุงู„ุนู…ูŠู„", "ุงู„ุญุงู„ุฉ", "ุชุงุฑูŠุฎ ุงู„ุฅู†ุดุงุก"]}
399
+ rows={recentInvoices.map((inv) => [
400
+ inv.invoiceNumber,
401
+ inv.customerName,
402
+ <StatusBadge status={inv.status} />,
403
+ formatDate(inv.createdAt),
404
+ ])}
405
+ />
406
+ <Pagination pagination={invoicesPagination} page={invoicesPage} setPage={setInvoicesPage} />
407
+ </div>
408
+
409
  </div>
410
  </Section>
411
  </div>
412
  );
413
  };
414
 
415
+ // โ”€๏ฟฝ๏ฟฝ Sub-components โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
416
+
417
+ const StatusBadge = ({ status }) => {
418
+ const map = {
419
+ paid: { label: "ู…ุณุฏุฏุฉ", cls: "text-emerald-600 bg-emerald-50 border-emerald-100" },
420
+ partial: { label: "ุฌุฒุฆูŠุฉ", cls: "text-amber-600 bg-amber-50 border-amber-100" },
421
+ unpaid: { label: "ุบูŠุฑ ู…ุณุฏุฏุฉ", cls: "text-rose-600 bg-rose-50 border-rose-100" },
422
+ };
423
+ const { label, cls } = map[status] || { label: status, cls: "text-slate-500 bg-slate-50 border-slate-100" };
424
+ return (
425
+ <span className={`text-xs font-bold px-2 py-1 rounded-lg border ${cls}`}>{label}</span>
426
+ );
427
+ };
428
+
429
  const ActionButton = ({ onClick, icon, label }) => {
430
+ const Icon = icon;
431
  return (
432
+ <button
433
+ type="button"
434
+ onClick={onClick}
435
+ className="flex h-11 items-center justify-center gap-2 rounded-2xl border border-slate-200 bg-slate-50 px-4 font-bold text-slate-700 transition hover:bg-slate-100"
436
+ >
437
+ <Icon size={16} />
438
+ {label}
439
+ </button>
440
  );
441
  };
442
 
443
+ const Section = ({ title, subtitle, children }) => (
444
  <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
445
  <div className="mb-5">
446
  <h3 className="text-lg font-black text-slate-900">{title}</h3>
447
+ {subtitle && <p className="text-xs text-slate-400 font-medium mt-0.5">{subtitle}</p>}
448
  </div>
449
  {children}
450
  </section>
 
455
  <table className="min-w-full border-collapse">
456
  <thead>
457
  <tr className="border-b border-slate-200 text-right text-sm font-bold text-slate-500">
458
+ {headers.map((h) => (
459
+ <th key={h} className="px-3 py-3">{h}</th>
460
  ))}
461
  </tr>
462
  </thead>
463
  <tbody>
464
  {rows.length ? (
465
+ rows.map((row, i) => (
466
+ <tr key={i} className="border-b border-slate-100 text-sm text-slate-700">
467
+ {row.map((cell, j) => (
468
+ <td key={j} className="px-3 py-3">{cell}</td>
469
  ))}
470
  </tr>
471
  ))
472
  ) : (
473
  <tr>
474
+ <td colSpan={headers.length} className="px-3 py-10 text-center text-sm font-medium text-slate-400">
475
  ู„ุง ุชูˆุฌุฏ ุจูŠุงู†ุงุช ู…ุชุงุญุฉ.
476
  </td>
477
  </tr>
 
480
  </table>
481
  </div>
482
  );
483
+ const tableHtml = (headers, rows, addSerial = false) => `
484
+ <table border="1" cellspacing="0" cellpadding="5">
485
+ <thead>
486
+ <tr>
487
+ ${addSerial ? "<th>#</th>" : ""}
488
+ ${headers.map((h) => `<th>${h}</th>`).join("")}
489
+ </tr>
490
+ </thead>
491
+ <tbody>
492
+ ${rows
493
+ .map(
494
+ (row, index) => `
495
+ <tr>
496
+ ${addSerial ? `<td>${index + 1}</td>` : ""}
497
+ ${row.map((cell) => `<td>${cell}</td>`).join("")}
498
+ </tr>
499
+ `
500
+ )
501
+ .join("")}
502
+ </tbody>
503
+ </table>
504
  `;
505
+ export default ReportsWorkspace;
 
frontend/src/routes/routes.jsx CHANGED
@@ -64,7 +64,7 @@ export const routes = createBrowserRouter([
64
  ),
65
  },
66
  {
67
- path: '/print/invoice/:id',
68
  element: (
69
  <ProtectedRoute>
70
  <PrintInvoice />
 
64
  ),
65
  },
66
  {
67
+ path: '/print/invoice/:customerId/:invoiceId',
68
  element: (
69
  <ProtectedRoute>
70
  <PrintInvoice />