Spaces:
Sleeping
Sleeping
mahmoud commited on
Commit ·
b5eea9b
1
Parent(s): 0bdd2ee
system update
Browse files- backend/controller/authController.js +86 -0
- backend/controller/customerController.js +70 -9
- backend/controller/expenseController.js +32 -0
- backend/controller/incomeController.js +83 -0
- backend/controller/reportController.js +37 -4
- backend/index.js +8 -2
- backend/models/CustomerModel.js +8 -0
- backend/models/IncomeModel.js +46 -0
- backend/models/InvoiceModel.js +4 -0
- backend/models/TenantModel.js +40 -0
- backend/routes/authRoutes.js +4 -0
- backend/routes/customerRoutes.js +2 -0
- backend/routes/expenseRoutes.js +4 -3
- backend/routes/incomeRoutes.js +13 -0
- backend/routes/supplierRoutes.js +2 -2
- frontend/src/Context/AuthContext.jsx +36 -8
- frontend/src/components/Customers/CustomersWorkspace.jsx +55 -15
- frontend/src/components/Dashboard/DashboardTab.jsx +57 -1
- frontend/src/components/Suppliers/SuppliersWorkspace.jsx +215 -2
- frontend/src/components/Tenants/TenantsAdminTab.jsx +102 -0
- frontend/src/pages/Hero.jsx +1 -1
- frontend/src/pages/Login.jsx +0 -137
- frontend/src/pages/Login_fixed.jsx +4 -4
- frontend/src/pages/Login_new.jsx +0 -2
- frontend/src/utils/formatters.js +8 -0
- frontend/src/utils/permissions.js +2 -2
backend/controller/authController.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import User from "../models/UserModel.js";
|
| 2 |
import Tenant from "../models/TenantModel.js";
|
| 3 |
import {
|
|
@@ -8,6 +9,13 @@ import {
|
|
| 8 |
toSlug,
|
| 9 |
} from "../utils/authCookies.js";
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
const sanitizeTenant = (tenant) => {
|
| 12 |
if (!tenant) {
|
| 13 |
return null;
|
|
@@ -25,6 +33,12 @@ const sanitizeTenant = (tenant) => {
|
|
| 25 |
status: tenant.status,
|
| 26 |
settings: tenant.settings,
|
| 27 |
createdAt: tenant.createdAt,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
};
|
| 29 |
};
|
| 30 |
|
|
@@ -54,6 +68,12 @@ const createUniqueSlug = async (name) => {
|
|
| 54 |
return slug;
|
| 55 |
};
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
export const checkAdmin = async (req, res) => {
|
| 58 |
try {
|
| 59 |
const count = await User.countDocuments({ role: "super_admin" });
|
|
@@ -440,6 +460,69 @@ export const updateTenantStatus = async (req, res) => {
|
|
| 440 |
}
|
| 441 |
};
|
| 442 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
export const createTenantOwner = async (req, res) => {
|
| 444 |
if (req.user.role !== "super_admin") {
|
| 445 |
return res.status(403).json({ message: "Only the platform admin can create tenants" });
|
|
@@ -481,6 +564,9 @@ export const createTenantOwner = async (req, res) => {
|
|
| 481 |
ownerPhone: phone,
|
| 482 |
whatsappNumber,
|
| 483 |
address,
|
|
|
|
|
|
|
|
|
|
| 484 |
});
|
| 485 |
|
| 486 |
const owner = await User.create({
|
|
|
|
| 1 |
+
import mongoose from "mongoose";
|
| 2 |
import User from "../models/UserModel.js";
|
| 3 |
import Tenant from "../models/TenantModel.js";
|
| 4 |
import {
|
|
|
|
| 9 |
toSlug,
|
| 10 |
} from "../utils/authCookies.js";
|
| 11 |
|
| 12 |
+
const getPaymentStatus = (tenant) => {
|
| 13 |
+
if (!tenant) return "due";
|
| 14 |
+
const nextDue = tenant.nextPaymentDueAt ? new Date(tenant.nextPaymentDueAt) : null;
|
| 15 |
+
if (!nextDue) return "due";
|
| 16 |
+
return nextDue < new Date() ? "overdue" : "due";
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
const sanitizeTenant = (tenant) => {
|
| 20 |
if (!tenant) {
|
| 21 |
return null;
|
|
|
|
| 33 |
status: tenant.status,
|
| 34 |
settings: tenant.settings,
|
| 35 |
createdAt: tenant.createdAt,
|
| 36 |
+
monthlyFeeAmount: tenant.monthlyFeeAmount || 800,
|
| 37 |
+
monthlyFeeCurrency: tenant.monthlyFeeCurrency || "EGP",
|
| 38 |
+
nextPaymentDueAt: tenant.nextPaymentDueAt || null,
|
| 39 |
+
lastPaymentAt: tenant.lastPaymentAt || null,
|
| 40 |
+
paymentsCount: Array.isArray(tenant.payments) ? tenant.payments.length : 0,
|
| 41 |
+
paymentStatus: getPaymentStatus(tenant),
|
| 42 |
};
|
| 43 |
};
|
| 44 |
|
|
|
|
| 68 |
return slug;
|
| 69 |
};
|
| 70 |
|
| 71 |
+
const addOneMonth = (date) => {
|
| 72 |
+
const next = new Date(date);
|
| 73 |
+
next.setMonth(next.getMonth() + 1);
|
| 74 |
+
return next;
|
| 75 |
+
};
|
| 76 |
+
|
| 77 |
export const checkAdmin = async (req, res) => {
|
| 78 |
try {
|
| 79 |
const count = await User.countDocuments({ role: "super_admin" });
|
|
|
|
| 460 |
}
|
| 461 |
};
|
| 462 |
|
| 463 |
+
export const getDbUsage = async (req, res) => {
|
| 464 |
+
if (req.user.role !== 'super_admin') {
|
| 465 |
+
return res.status(403).json({ message: 'Only system admin can access database usage metrics' });
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
try {
|
| 469 |
+
const stats = await mongoose.connection.db.stats();
|
| 470 |
+
res.status(200).json({
|
| 471 |
+
storageSize: stats.storageSize,
|
| 472 |
+
dataSize: stats.dataSize,
|
| 473 |
+
indexSize: stats.indexSize,
|
| 474 |
+
fileSize: stats.fileSize || null,
|
| 475 |
+
fsTotalSize: stats.fsTotalSize || null,
|
| 476 |
+
fsUsedSize: stats.fsUsedSize || null,
|
| 477 |
+
collections: stats.collections,
|
| 478 |
+
objects: stats.objects,
|
| 479 |
+
indexes: stats.indexes,
|
| 480 |
+
});
|
| 481 |
+
} catch (error) {
|
| 482 |
+
res.status(500).json({ message: error.message });
|
| 483 |
+
}
|
| 484 |
+
};
|
| 485 |
+
|
| 486 |
+
export const recordTenantPayment = async (req, res) => {
|
| 487 |
+
const tenantId = req.params.id;
|
| 488 |
+
const amount = Number(req.body.amount || 800);
|
| 489 |
+
const method = req.body.method?.trim() || 'manual';
|
| 490 |
+
const note = req.body.note?.trim() || 'Monthly fee payment';
|
| 491 |
+
|
| 492 |
+
try {
|
| 493 |
+
const tenant = await Tenant.findById(tenantId);
|
| 494 |
+
if (!tenant) {
|
| 495 |
+
return res.status(404).json({ message: 'Tenant not found' });
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
if (req.user.role !== 'super_admin') {
|
| 499 |
+
if (!req.user.tenant || req.user.tenant._id.toString() !== tenant._id.toString()) {
|
| 500 |
+
return res.status(403).json({ message: 'You do not have permission to record payments for this tenant' });
|
| 501 |
+
}
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
const paymentDate = new Date();
|
| 505 |
+
tenant.payments = tenant.payments || [];
|
| 506 |
+
tenant.payments.push({
|
| 507 |
+
amount,
|
| 508 |
+
date: paymentDate,
|
| 509 |
+
method,
|
| 510 |
+
note,
|
| 511 |
+
recordedBy: req.user._id,
|
| 512 |
+
});
|
| 513 |
+
tenant.lastPaymentAt = paymentDate;
|
| 514 |
+
tenant.nextPaymentDueAt = addOneMonth(tenant.nextPaymentDueAt || paymentDate);
|
| 515 |
+
await tenant.save();
|
| 516 |
+
|
| 517 |
+
res.status(200).json({
|
| 518 |
+
message: 'Payment recorded successfully',
|
| 519 |
+
tenant: sanitizeTenant(tenant),
|
| 520 |
+
});
|
| 521 |
+
} catch (error) {
|
| 522 |
+
res.status(500).json({ message: error.message });
|
| 523 |
+
}
|
| 524 |
+
};
|
| 525 |
+
|
| 526 |
export const createTenantOwner = async (req, res) => {
|
| 527 |
if (req.user.role !== "super_admin") {
|
| 528 |
return res.status(403).json({ message: "Only the platform admin can create tenants" });
|
|
|
|
| 564 |
ownerPhone: phone,
|
| 565 |
whatsappNumber,
|
| 566 |
address,
|
| 567 |
+
monthlyFeeAmount: 800,
|
| 568 |
+
monthlyFeeCurrency: "EGP",
|
| 569 |
+
nextPaymentDueAt: addOneMonth(new Date()),
|
| 570 |
});
|
| 571 |
|
| 572 |
const owner = await User.create({
|
backend/controller/customerController.js
CHANGED
|
@@ -17,6 +17,7 @@ export const createCustomer = async (req, res) => {
|
|
| 17 |
const exists = await Customer.findOne({
|
| 18 |
tenant: tenantId,
|
| 19 |
name: new RegExp(`^${name}$`, "i"),
|
|
|
|
| 20 |
});
|
| 21 |
|
| 22 |
if (exists) {
|
|
@@ -47,8 +48,15 @@ export const getCustomers = async (req, res) => {
|
|
| 47 |
const skip = (page - 1) * limit;
|
| 48 |
const search = req.query.search || "";
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
const matchQuery = {
|
| 51 |
tenant: tenantId,
|
|
|
|
| 52 |
};
|
| 53 |
|
| 54 |
if (search) {
|
|
@@ -142,6 +150,7 @@ export const getCustomerById = async (req, res) => {
|
|
| 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 })
|
|
@@ -166,16 +175,68 @@ export const getCustomerById = async (req, res) => {
|
|
| 166 |
export const deleteCustomer = async (req, res) => {
|
| 167 |
try {
|
| 168 |
const customerId = req.params.id;
|
| 169 |
-
await Customer.
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
res.status(200).json({ message: "Customer
|
| 179 |
} catch (error) {
|
| 180 |
res.status(500).json({ message: error.message });
|
| 181 |
}
|
|
|
|
| 17 |
const exists = await Customer.findOne({
|
| 18 |
tenant: tenantId,
|
| 19 |
name: new RegExp(`^${name}$`, "i"),
|
| 20 |
+
isDeleted: false,
|
| 21 |
});
|
| 22 |
|
| 23 |
if (exists) {
|
|
|
|
| 48 |
const skip = (page - 1) * limit;
|
| 49 |
const search = req.query.search || "";
|
| 50 |
|
| 51 |
+
const showDeleted = req.query.deleted === "true";
|
| 52 |
+
|
| 53 |
+
if (showDeleted && !["owner", "admin"].includes(req.user.role)) {
|
| 54 |
+
return res.status(403).json({ message: "You do not have permission to view deleted customers" });
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
const matchQuery = {
|
| 58 |
tenant: tenantId,
|
| 59 |
+
isDeleted: showDeleted,
|
| 60 |
};
|
| 61 |
|
| 62 |
if (search) {
|
|
|
|
| 150 |
const invoices = await Invoice.find({
|
| 151 |
customer: customer._id,
|
| 152 |
tenant: req.user.tenant._id,
|
| 153 |
+
isDeleted: false,
|
| 154 |
})
|
| 155 |
.populate("items.productId", "name price")
|
| 156 |
.sort({ [sortField]: sortOrder })
|
|
|
|
| 175 |
export const deleteCustomer = async (req, res) => {
|
| 176 |
try {
|
| 177 |
const customerId = req.params.id;
|
| 178 |
+
const deletedCustomer = await Customer.findOneAndUpdate(
|
| 179 |
+
{
|
| 180 |
+
_id: customerId,
|
| 181 |
+
tenant: req.user.tenant._id,
|
| 182 |
+
isDeleted: false,
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
isDeleted: true,
|
| 186 |
+
deletedAt: new Date(),
|
| 187 |
+
},
|
| 188 |
+
{ new: true }
|
| 189 |
+
);
|
| 190 |
+
|
| 191 |
+
if (!deletedCustomer) {
|
| 192 |
+
return res.status(404).json({ message: "Customer not found or already deleted" });
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
await Invoice.updateMany(
|
| 196 |
+
{
|
| 197 |
+
customer: customerId,
|
| 198 |
+
tenant: req.user.tenant._id,
|
| 199 |
+
isDeleted: false,
|
| 200 |
+
},
|
| 201 |
+
{ isDeleted: true }
|
| 202 |
+
);
|
| 203 |
+
|
| 204 |
+
res.status(200).json({ message: "Customer soft deleted and linked invoices archived successfully" });
|
| 205 |
+
} catch (error) {
|
| 206 |
+
res.status(500).json({ message: error.message });
|
| 207 |
+
}
|
| 208 |
+
};
|
| 209 |
+
|
| 210 |
+
export const restoreCustomer = async (req, res) => {
|
| 211 |
+
try {
|
| 212 |
+
const customerId = req.params.id;
|
| 213 |
+
const restoredCustomer = await Customer.findOneAndUpdate(
|
| 214 |
+
{
|
| 215 |
+
_id: customerId,
|
| 216 |
+
tenant: req.user.tenant._id,
|
| 217 |
+
isDeleted: true,
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
isDeleted: false,
|
| 221 |
+
deletedAt: null,
|
| 222 |
+
},
|
| 223 |
+
{ new: true }
|
| 224 |
+
);
|
| 225 |
+
|
| 226 |
+
if (!restoredCustomer) {
|
| 227 |
+
return res.status(404).json({ message: "Deleted customer not found" });
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
await Invoice.updateMany(
|
| 231 |
+
{
|
| 232 |
+
customer: customerId,
|
| 233 |
+
tenant: req.user.tenant._id,
|
| 234 |
+
isDeleted: true,
|
| 235 |
+
},
|
| 236 |
+
{ isDeleted: false }
|
| 237 |
+
);
|
| 238 |
|
| 239 |
+
res.status(200).json({ message: "Customer restored with all linked invoices" });
|
| 240 |
} catch (error) {
|
| 241 |
res.status(500).json({ message: error.message });
|
| 242 |
}
|
backend/controller/expenseController.js
CHANGED
|
@@ -19,6 +19,38 @@ export const addExpense = async (req, res) => {
|
|
| 19 |
}
|
| 20 |
};
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
export const deleteExpense = async (req, res) => {
|
| 23 |
try {
|
| 24 |
await Expense.findOneAndDelete({
|
|
|
|
| 19 |
}
|
| 20 |
};
|
| 21 |
|
| 22 |
+
export const getExpenses = async (req, res) => {
|
| 23 |
+
try {
|
| 24 |
+
const tenantId = req.user.tenant._id;
|
| 25 |
+
const page = parseInt(req.query.page) || 1;
|
| 26 |
+
const limit = parseInt(req.query.limit) || 5;
|
| 27 |
+
const skip = (page - 1) * limit;
|
| 28 |
+
const search = req.query.search || "";
|
| 29 |
+
|
| 30 |
+
const query = { tenant: tenantId };
|
| 31 |
+
if (search) {
|
| 32 |
+
query.title = { $regex: search, $options: "i" };
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
const [items, total] = await Promise.all([
|
| 36 |
+
Expense.find(query).sort({ date: -1 }).skip(skip).limit(limit),
|
| 37 |
+
Expense.countDocuments(query),
|
| 38 |
+
]);
|
| 39 |
+
|
| 40 |
+
res.status(200).json({
|
| 41 |
+
data: items,
|
| 42 |
+
pagination: {
|
| 43 |
+
total,
|
| 44 |
+
page,
|
| 45 |
+
limit,
|
| 46 |
+
totalPages: Math.ceil(total / limit),
|
| 47 |
+
},
|
| 48 |
+
});
|
| 49 |
+
} catch (error) {
|
| 50 |
+
res.status(500).json({ message: error.message });
|
| 51 |
+
}
|
| 52 |
+
};
|
| 53 |
+
|
| 54 |
export const deleteExpense = async (req, res) => {
|
| 55 |
try {
|
| 56 |
await Expense.findOneAndDelete({
|
backend/controller/incomeController.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import Income from "../models/IncomeModel.js";
|
| 2 |
+
|
| 3 |
+
export const addIncome = async (req, res) => {
|
| 4 |
+
try {
|
| 5 |
+
const tenantId = req.user.tenant._id;
|
| 6 |
+
const title = req.body.title?.trim();
|
| 7 |
+
const amount = Number(req.body.amount);
|
| 8 |
+
const category = req.body.category?.trim() || "general";
|
| 9 |
+
const paymentMethod = req.body.paymentMethod?.trim() || "cash";
|
| 10 |
+
const notes = req.body.notes?.trim() || "";
|
| 11 |
+
const date = req.body.date ? new Date(req.body.date) : new Date();
|
| 12 |
+
|
| 13 |
+
if (!title) {
|
| 14 |
+
return res.status(400).json({ message: "Income title is required" });
|
| 15 |
+
}
|
| 16 |
+
if (!amount || amount <= 0) {
|
| 17 |
+
return res.status(400).json({ message: "Income amount must be greater than zero" });
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
const income = await Income.create({
|
| 21 |
+
tenant: tenantId,
|
| 22 |
+
title,
|
| 23 |
+
category,
|
| 24 |
+
amount,
|
| 25 |
+
paymentMethod,
|
| 26 |
+
notes,
|
| 27 |
+
date,
|
| 28 |
+
createdBy: req.user._id,
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
res.status(201).json(income);
|
| 32 |
+
} catch (error) {
|
| 33 |
+
res.status(500).json({ message: error.message });
|
| 34 |
+
}
|
| 35 |
+
};
|
| 36 |
+
|
| 37 |
+
export const getIncomes = async (req, res) => {
|
| 38 |
+
try {
|
| 39 |
+
const tenantId = req.user.tenant._id;
|
| 40 |
+
const page = parseInt(req.query.page) || 1;
|
| 41 |
+
const limit = parseInt(req.query.limit) || 5;
|
| 42 |
+
const skip = (page - 1) * limit;
|
| 43 |
+
const search = req.query.search || "";
|
| 44 |
+
|
| 45 |
+
const query = { tenant: tenantId };
|
| 46 |
+
if (search) {
|
| 47 |
+
query.title = { $regex: search, $options: "i" };
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
const [items, total] = await Promise.all([
|
| 51 |
+
Income.find(query).sort({ date: -1 }).skip(skip).limit(limit),
|
| 52 |
+
Income.countDocuments(query),
|
| 53 |
+
]);
|
| 54 |
+
|
| 55 |
+
res.status(200).json({
|
| 56 |
+
data: items,
|
| 57 |
+
pagination: {
|
| 58 |
+
total,
|
| 59 |
+
page,
|
| 60 |
+
limit,
|
| 61 |
+
totalPages: Math.ceil(total / limit),
|
| 62 |
+
},
|
| 63 |
+
});
|
| 64 |
+
} catch (error) {
|
| 65 |
+
res.status(500).json({ message: error.message });
|
| 66 |
+
}
|
| 67 |
+
};
|
| 68 |
+
|
| 69 |
+
export const deleteIncome = async (req, res) => {
|
| 70 |
+
try {
|
| 71 |
+
const incomeId = req.params.id;
|
| 72 |
+
const income = await Income.findOneAndDelete({
|
| 73 |
+
_id: incomeId,
|
| 74 |
+
tenant: req.user.tenant._id,
|
| 75 |
+
});
|
| 76 |
+
if (!income) {
|
| 77 |
+
return res.status(404).json({ message: "Income entry not found" });
|
| 78 |
+
}
|
| 79 |
+
res.status(200).json({ message: "Income entry deleted successfully" });
|
| 80 |
+
} catch (error) {
|
| 81 |
+
res.status(500).json({ message: error.message });
|
| 82 |
+
}
|
| 83 |
+
};
|
backend/controller/reportController.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import Invoice from "../models/InvoiceModel.js";
|
| 2 |
import Expense from "../models/ExpenseModel.js";
|
|
|
|
| 3 |
import Product from "../models/ProductModel.js";
|
| 4 |
import Customer from "../models/CustomerModel.js";
|
| 5 |
import Supplier from "../models/SupplierModel.js";
|
|
@@ -99,10 +100,11 @@ export const getDashboardOverview = async (req, res) => {
|
|
| 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 }),
|
|
@@ -123,6 +125,7 @@ export const getDashboardOverview = async (req, res) => {
|
|
| 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 |
|
|
@@ -172,6 +175,17 @@ export const getDashboardOverview = async (req, res) => {
|
|
| 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))
|
|
@@ -205,8 +219,9 @@ export const getDashboardOverview = async (req, res) => {
|
|
| 205 |
metrics: {
|
| 206 |
salesInRange,
|
| 207 |
collectionsInRange,
|
|
|
|
| 208 |
expensesInRange,
|
| 209 |
-
netCashFlow: collectionsInRange - expensesInRange,
|
| 210 |
outstandingReceivables,
|
| 211 |
supplierOutstanding,
|
| 212 |
customersCount: customers.length,
|
|
@@ -237,6 +252,7 @@ export const getDashboardOverview = async (req, res) => {
|
|
| 237 |
amount: toNumber(e.amount),
|
| 238 |
date: e.date,
|
| 239 |
})),
|
|
|
|
| 240 |
});
|
| 241 |
} catch (error) {
|
| 242 |
res.status(500).json({ message: error.message });
|
|
@@ -260,12 +276,16 @@ export const getDailyReport = async (req, res) => {
|
|
| 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 ─────────────────────────────────────────────────────────
|
|
@@ -307,6 +327,7 @@ export const getDailyReport = async (req, res) => {
|
|
| 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);
|
|
@@ -320,16 +341,28 @@ export const getDailyReport = async (req, res) => {
|
|
| 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 });
|
|
|
|
| 1 |
import Invoice from "../models/InvoiceModel.js";
|
| 2 |
import Expense from "../models/ExpenseModel.js";
|
| 3 |
+
import Income from "../models/IncomeModel.js";
|
| 4 |
import Product from "../models/ProductModel.js";
|
| 5 |
import Customer from "../models/CustomerModel.js";
|
| 6 |
import Supplier from "../models/SupplierModel.js";
|
|
|
|
| 100 |
const limit = parseInt(req.query.limit) || 5;
|
| 101 |
|
| 102 |
// ── fetch all data in parallel ────────────────────────────────────────
|
| 103 |
+
const [invoices, expenses, incomes, products, customers, suppliers, supplierInvoices, users] =
|
| 104 |
await Promise.all([
|
| 105 |
Invoice.find({ tenant: tenantId }).populate("customer", "name"),
|
| 106 |
Expense.find({ tenant: tenantId }).sort({ date: -1 }),
|
| 107 |
+
Income.find({ tenant: tenantId }).sort({ date: -1 }),
|
| 108 |
Product.find({ tenant: tenantId }).sort({ stock: 1, createdAt: -1 }),
|
| 109 |
Customer.find({ tenant: tenantId }).sort({ createdAt: -1 }),
|
| 110 |
Supplier.find({ tenant: tenantId }).sort({ createdAt: -1 }),
|
|
|
|
| 125 |
}, 0);
|
| 126 |
|
| 127 |
const expensesInRange = rangeExpenses.reduce((s, e) => s + toNumber(e.amount), 0);
|
| 128 |
+
const incomeInRange = incomes.filter((inc) => isWithinRange(inc.date, start, end)).reduce((s, inc) => s + toNumber(inc.amount), 0);
|
| 129 |
const outstandingReceivables = invoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
|
| 130 |
const supplierOutstanding = supplierInvoices.reduce((s, inv) => s + toNumber(inv.remainingAmount), 0);
|
| 131 |
|
|
|
|
| 175 |
.filter((p) => isWithinRange(p.date, start, end))
|
| 176 |
.sort((a, b) => new Date(b.date) - new Date(a.date));
|
| 177 |
|
| 178 |
+
const recentIncome = incomes
|
| 179 |
+
.filter((inc) => isWithinRange(inc.date, start, end))
|
| 180 |
+
.sort((a, b) => new Date(b.date) - new Date(a.date))
|
| 181 |
+
.slice(0, 8)
|
| 182 |
+
.map((inc) => ({
|
| 183 |
+
_id: inc._id,
|
| 184 |
+
title: inc.title,
|
| 185 |
+
amount: toNumber(inc.amount),
|
| 186 |
+
date: inc.date,
|
| 187 |
+
}));
|
| 188 |
+
|
| 189 |
// ── recent invoices (within range, sorted newest first) ───────────────
|
| 190 |
const allRecentInvoices = [...rangeInvoices]
|
| 191 |
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
|
|
|
|
| 219 |
metrics: {
|
| 220 |
salesInRange,
|
| 221 |
collectionsInRange,
|
| 222 |
+
incomeInRange,
|
| 223 |
expensesInRange,
|
| 224 |
+
netCashFlow: collectionsInRange + incomeInRange - expensesInRange,
|
| 225 |
outstandingReceivables,
|
| 226 |
supplierOutstanding,
|
| 227 |
customersCount: customers.length,
|
|
|
|
| 252 |
amount: toNumber(e.amount),
|
| 253 |
date: e.date,
|
| 254 |
})),
|
| 255 |
+
recentIncome,
|
| 256 |
});
|
| 257 |
} catch (error) {
|
| 258 |
res.status(500).json({ message: error.message });
|
|
|
|
| 276 |
endOfDay.setHours(23, 59, 59, 999);
|
| 277 |
|
| 278 |
// ── fetch ─────────────────────────────────────────────────────────────
|
| 279 |
+
const [invoices, expenses, incomes] = await Promise.all([
|
| 280 |
Invoice.find({ tenant: tenantId }).populate("customer", "name"),
|
| 281 |
Expense.find({
|
| 282 |
tenant: tenantId,
|
| 283 |
date: { $gte: startOfDay, $lte: endOfDay },
|
| 284 |
}).sort({ date: -1 }),
|
| 285 |
+
Income.find({
|
| 286 |
+
tenant: tenantId,
|
| 287 |
+
date: { $gte: startOfDay, $lte: endOfDay },
|
| 288 |
+
}).sort({ date: -1 }),
|
| 289 |
]);
|
| 290 |
|
| 291 |
// ── aggregate ─────────────────────────────────────────────────────────
|
|
|
|
| 327 |
dailyPaymentsList.sort((a, b) => new Date(b.date) - new Date(a.date));
|
| 328 |
|
| 329 |
const totalExpenses = expenses.reduce((s, e) => s + toNumber(e.amount), 0);
|
| 330 |
+
const totalIncome = incomes.reduce((s, inc) => s + toNumber(inc.amount), 0);
|
| 331 |
|
| 332 |
// ── paginate both lists ───────────────────────────────────────────────
|
| 333 |
const paginatedPayments = paginate(dailyPaymentsList, req.query.paymentsPage, limit);
|
|
|
|
| 341 |
req.query.expensesPage,
|
| 342 |
limit
|
| 343 |
);
|
| 344 |
+
const paginatedIncome = paginate(
|
| 345 |
+
incomes.map((inc) => ({
|
| 346 |
+
_id: inc._id,
|
| 347 |
+
title: inc.title,
|
| 348 |
+
amount: toNumber(inc.amount),
|
| 349 |
+
date: inc.date,
|
| 350 |
+
})),
|
| 351 |
+
req.query.incomePage,
|
| 352 |
+
limit
|
| 353 |
+
);
|
| 354 |
|
| 355 |
// ── respond ───────────────────────────────────────────────────────────
|
| 356 |
res.status(200).json({
|
| 357 |
totalCashCollected,
|
| 358 |
totalSalesToday,
|
| 359 |
+
totalIncome,
|
| 360 |
newInvoicesCount,
|
| 361 |
totalExpenses,
|
| 362 |
+
netCashInDrawer: totalCashCollected + totalIncome - totalExpenses,
|
| 363 |
recentPayments: paginatedPayments, // { data: [...], pagination: {...} }
|
| 364 |
expensesList: paginatedExpenses, // { data: [...], pagination: {...} }
|
| 365 |
+
incomeList: paginatedIncome,
|
| 366 |
});
|
| 367 |
} catch (error) {
|
| 368 |
res.status(500).json({ message: error.message });
|
backend/index.js
CHANGED
|
@@ -8,6 +8,7 @@ import invoicesRoutes from "./routes/invoiceRoutes.js";
|
|
| 8 |
import reportsRoutes from "./routes/reportRoutes.js";
|
| 9 |
import productRoutes from "./routes/productRoutes.js";
|
| 10 |
import expenseRoutes from "./routes/expenseRoutes.js";
|
|
|
|
| 11 |
import supplierRoutes from "./routes/supplierRoutes.js";
|
| 12 |
import authRoutes from "./routes/authRoutes.js";
|
| 13 |
import { dbConnection } from './config/database.js';
|
|
@@ -19,8 +20,12 @@ 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) => {
|
|
@@ -43,6 +48,7 @@ app.use('/invoices', invoicesRoutes);
|
|
| 43 |
app.use('/reports', reportsRoutes);
|
| 44 |
app.use('/products', productRoutes);
|
| 45 |
app.use('/expenses', expenseRoutes);
|
|
|
|
| 46 |
app.use('/suppliers', supplierRoutes);
|
| 47 |
app.use('/auth', authRoutes);
|
| 48 |
app.get('/', (req, res) => {
|
|
|
|
| 8 |
import reportsRoutes from "./routes/reportRoutes.js";
|
| 9 |
import productRoutes from "./routes/productRoutes.js";
|
| 10 |
import expenseRoutes from "./routes/expenseRoutes.js";
|
| 11 |
+
import incomeRoutes from "./routes/incomeRoutes.js";
|
| 12 |
import supplierRoutes from "./routes/supplierRoutes.js";
|
| 13 |
import authRoutes from "./routes/authRoutes.js";
|
| 14 |
import { dbConnection } from './config/database.js';
|
|
|
|
| 20 |
|
| 21 |
const allowedOrigins = [
|
| 22 |
'https://salessystem-tau.vercel.app',
|
| 23 |
+
'http://localhost:5173',
|
| 24 |
+
'http://127.0.0.1:5173',
|
| 25 |
+
'http://localhost:4173',
|
| 26 |
+
'http://127.0.0.1:4173',
|
| 27 |
+
process.env.FRONTEND_URL?.trim(),
|
| 28 |
+
].filter(Boolean);
|
| 29 |
|
| 30 |
app.use(cors({
|
| 31 |
origin: (origin, callback) => {
|
|
|
|
| 48 |
app.use('/reports', reportsRoutes);
|
| 49 |
app.use('/products', productRoutes);
|
| 50 |
app.use('/expenses', expenseRoutes);
|
| 51 |
+
app.use('/incomes', incomeRoutes);
|
| 52 |
app.use('/suppliers', supplierRoutes);
|
| 53 |
app.use('/auth', authRoutes);
|
| 54 |
app.get('/', (req, res) => {
|
backend/models/CustomerModel.js
CHANGED
|
@@ -44,6 +44,14 @@ const customerSchema = new mongoose.Schema(
|
|
| 44 |
ref: "Invoice",
|
| 45 |
},
|
| 46 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
},
|
| 48 |
{
|
| 49 |
timestamps: true,
|
|
|
|
| 44 |
ref: "Invoice",
|
| 45 |
},
|
| 46 |
],
|
| 47 |
+
isDeleted: {
|
| 48 |
+
type: Boolean,
|
| 49 |
+
default: false,
|
| 50 |
+
},
|
| 51 |
+
deletedAt: {
|
| 52 |
+
type: Date,
|
| 53 |
+
default: null,
|
| 54 |
+
},
|
| 55 |
},
|
| 56 |
{
|
| 57 |
timestamps: true,
|
backend/models/IncomeModel.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mongoose from "mongoose";
|
| 2 |
+
|
| 3 |
+
const incomeSchema = new mongoose.Schema(
|
| 4 |
+
{
|
| 5 |
+
tenant: {
|
| 6 |
+
type: mongoose.Schema.Types.ObjectId,
|
| 7 |
+
ref: "Tenant",
|
| 8 |
+
required: true,
|
| 9 |
+
index: true,
|
| 10 |
+
},
|
| 11 |
+
title: {
|
| 12 |
+
type: String,
|
| 13 |
+
required: true,
|
| 14 |
+
},
|
| 15 |
+
category: {
|
| 16 |
+
type: String,
|
| 17 |
+
default: "general",
|
| 18 |
+
},
|
| 19 |
+
amount: {
|
| 20 |
+
type: Number,
|
| 21 |
+
required: true,
|
| 22 |
+
},
|
| 23 |
+
paymentMethod: {
|
| 24 |
+
type: String,
|
| 25 |
+
default: "cash",
|
| 26 |
+
},
|
| 27 |
+
notes: {
|
| 28 |
+
type: String,
|
| 29 |
+
default: "",
|
| 30 |
+
},
|
| 31 |
+
date: {
|
| 32 |
+
type: Date,
|
| 33 |
+
default: Date.now,
|
| 34 |
+
},
|
| 35 |
+
createdBy: {
|
| 36 |
+
type: mongoose.Schema.Types.ObjectId,
|
| 37 |
+
ref: "User",
|
| 38 |
+
default: null,
|
| 39 |
+
},
|
| 40 |
+
},
|
| 41 |
+
{ timestamps: true }
|
| 42 |
+
);
|
| 43 |
+
|
| 44 |
+
incomeSchema.index({ tenant: 1, date: -1 });
|
| 45 |
+
|
| 46 |
+
export default mongoose.model("Income", incomeSchema);
|
backend/models/InvoiceModel.js
CHANGED
|
@@ -81,6 +81,10 @@ const invoiceSchema = new mongoose.Schema(
|
|
| 81 |
type: String,
|
| 82 |
default: "",
|
| 83 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
},
|
| 85 |
{ timestamps: true }
|
| 86 |
);
|
|
|
|
| 81 |
type: String,
|
| 82 |
default: "",
|
| 83 |
},
|
| 84 |
+
isDeleted: {
|
| 85 |
+
type: Boolean,
|
| 86 |
+
default: false,
|
| 87 |
+
},
|
| 88 |
},
|
| 89 |
{ timestamps: true }
|
| 90 |
);
|
backend/models/TenantModel.js
CHANGED
|
@@ -55,6 +55,46 @@ const tenantSchema = new mongoose.Schema(
|
|
| 55 |
default: 5,
|
| 56 |
},
|
| 57 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
},
|
| 59 |
{ timestamps: true }
|
| 60 |
);
|
|
|
|
| 55 |
default: 5,
|
| 56 |
},
|
| 57 |
},
|
| 58 |
+
monthlyFeeAmount: {
|
| 59 |
+
type: Number,
|
| 60 |
+
default: 800,
|
| 61 |
+
},
|
| 62 |
+
monthlyFeeCurrency: {
|
| 63 |
+
type: String,
|
| 64 |
+
default: "EGP",
|
| 65 |
+
},
|
| 66 |
+
nextPaymentDueAt: {
|
| 67 |
+
type: Date,
|
| 68 |
+
},
|
| 69 |
+
lastPaymentAt: {
|
| 70 |
+
type: Date,
|
| 71 |
+
},
|
| 72 |
+
payments: [
|
| 73 |
+
{
|
| 74 |
+
amount: {
|
| 75 |
+
type: Number,
|
| 76 |
+
required: true,
|
| 77 |
+
},
|
| 78 |
+
date: {
|
| 79 |
+
type: Date,
|
| 80 |
+
required: true,
|
| 81 |
+
default: Date.now,
|
| 82 |
+
},
|
| 83 |
+
method: {
|
| 84 |
+
type: String,
|
| 85 |
+
default: "manual",
|
| 86 |
+
},
|
| 87 |
+
note: {
|
| 88 |
+
type: String,
|
| 89 |
+
default: "Monthly fee payment",
|
| 90 |
+
},
|
| 91 |
+
recordedBy: {
|
| 92 |
+
type: mongoose.Schema.Types.ObjectId,
|
| 93 |
+
ref: "User",
|
| 94 |
+
default: null,
|
| 95 |
+
},
|
| 96 |
+
},
|
| 97 |
+
],
|
| 98 |
},
|
| 99 |
{ timestamps: true }
|
| 100 |
);
|
backend/routes/authRoutes.js
CHANGED
|
@@ -14,6 +14,8 @@ import {
|
|
| 14 |
createTenantOwner,
|
| 15 |
updateTenantProfile,
|
| 16 |
updateTenantStatus,
|
|
|
|
|
|
|
| 17 |
} from "../controller/authController.js";
|
| 18 |
import { protect } from "../middleware/authMiddleware.js";
|
| 19 |
|
|
@@ -31,6 +33,8 @@ router.delete("/users/:id", protect, deleteUser);
|
|
| 31 |
router.get("/tenants", protect, getTenants);
|
| 32 |
router.post("/tenants", protect, createTenantOwner);
|
| 33 |
router.patch("/tenants/:id/status", protect, updateTenantStatus);
|
|
|
|
|
|
|
| 34 |
router.get("/tenant-profile", protect, getTenantProfile);
|
| 35 |
router.put("/tenant-profile", protect, updateTenantProfile);
|
| 36 |
|
|
|
|
| 14 |
createTenantOwner,
|
| 15 |
updateTenantProfile,
|
| 16 |
updateTenantStatus,
|
| 17 |
+
getDbUsage,
|
| 18 |
+
recordTenantPayment,
|
| 19 |
} from "../controller/authController.js";
|
| 20 |
import { protect } from "../middleware/authMiddleware.js";
|
| 21 |
|
|
|
|
| 33 |
router.get("/tenants", protect, getTenants);
|
| 34 |
router.post("/tenants", protect, createTenantOwner);
|
| 35 |
router.patch("/tenants/:id/status", protect, updateTenantStatus);
|
| 36 |
+
router.post("/tenants/:id/payments", protect, recordTenantPayment);
|
| 37 |
+
router.get("/db-usage", protect, getDbUsage);
|
| 38 |
router.get("/tenant-profile", protect, getTenantProfile);
|
| 39 |
router.put("/tenant-profile", protect, updateTenantProfile);
|
| 40 |
|
backend/routes/customerRoutes.js
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
| 4 |
getCustomerById,
|
| 5 |
getCustomers,
|
| 6 |
deleteCustomer,
|
|
|
|
| 7 |
} from "../controller/customerController.js";
|
| 8 |
import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
|
| 9 |
|
|
@@ -15,5 +16,6 @@ router.post("/create", createCustomer);
|
|
| 15 |
router.get("/", getCustomers);
|
| 16 |
router.get("/:id", getCustomerById);
|
| 17 |
router.delete("/:id", authorize("owner", "admin"), deleteCustomer);
|
|
|
|
| 18 |
|
| 19 |
export default router;
|
|
|
|
| 4 |
getCustomerById,
|
| 5 |
getCustomers,
|
| 6 |
deleteCustomer,
|
| 7 |
+
restoreCustomer,
|
| 8 |
} from "../controller/customerController.js";
|
| 9 |
import { authorize, protect, requireTenantUser } from "../middleware/authMiddleware.js";
|
| 10 |
|
|
|
|
| 16 |
router.get("/", getCustomers);
|
| 17 |
router.get("/:id", getCustomerById);
|
| 18 |
router.delete("/:id", authorize("owner", "admin"), deleteCustomer);
|
| 19 |
+
router.patch("/:id/restore", authorize("owner", "admin"), restoreCustomer);
|
| 20 |
|
| 21 |
export default router;
|
backend/routes/expenseRoutes.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
import { Router } from "express";
|
| 2 |
-
import { addExpense, deleteExpense } from "../controller/expenseController.js";
|
| 3 |
-
import {
|
| 4 |
|
| 5 |
const router = Router();
|
| 6 |
|
| 7 |
-
router.use(protect, requireTenantUser
|
| 8 |
|
|
|
|
| 9 |
router.post("/", addExpense);
|
| 10 |
router.delete("/:id", deleteExpense);
|
| 11 |
|
|
|
|
| 1 |
import { Router } from "express";
|
| 2 |
+
import { addExpense, deleteExpense, getExpenses } from "../controller/expenseController.js";
|
| 3 |
+
import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
|
| 4 |
|
| 5 |
const router = Router();
|
| 6 |
|
| 7 |
+
router.use(protect, requireTenantUser);
|
| 8 |
|
| 9 |
+
router.get("/", getExpenses);
|
| 10 |
router.post("/", addExpense);
|
| 11 |
router.delete("/:id", deleteExpense);
|
| 12 |
|
backend/routes/incomeRoutes.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Router } from "express";
|
| 2 |
+
import { addIncome, getIncomes, deleteIncome } from "../controller/incomeController.js";
|
| 3 |
+
import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
|
| 4 |
+
|
| 5 |
+
const router = Router();
|
| 6 |
+
|
| 7 |
+
router.use(protect, requireTenantUser);
|
| 8 |
+
|
| 9 |
+
router.post("/", addIncome);
|
| 10 |
+
router.get("/", getIncomes);
|
| 11 |
+
router.delete("/:id", deleteIncome);
|
| 12 |
+
|
| 13 |
+
export default router;
|
backend/routes/supplierRoutes.js
CHANGED
|
@@ -7,11 +7,11 @@ import {
|
|
| 7 |
addPurchasesToSupplier,
|
| 8 |
paySupplier,
|
| 9 |
} from "../controller/supplierController.js";
|
| 10 |
-
import {
|
| 11 |
|
| 12 |
const router = Router();
|
| 13 |
|
| 14 |
-
router.use(protect, requireTenantUser
|
| 15 |
|
| 16 |
router.post("/create", createSupplier);
|
| 17 |
router.get("/", getSuppliers);
|
|
|
|
| 7 |
addPurchasesToSupplier,
|
| 8 |
paySupplier,
|
| 9 |
} from "../controller/supplierController.js";
|
| 10 |
+
import { protect, requireTenantUser } from "../middleware/authMiddleware.js";
|
| 11 |
|
| 12 |
const router = Router();
|
| 13 |
|
| 14 |
+
router.use(protect, requireTenantUser);
|
| 15 |
|
| 16 |
router.post("/create", createSupplier);
|
| 17 |
router.get("/", getSuppliers);
|
frontend/src/Context/AuthContext.jsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
/* eslint-disable react-refresh/only-export-components */
|
| 2 |
-
import { createContext, useContext, useEffect, useState } from "react";
|
| 3 |
import axios from "axios";
|
| 4 |
|
| 5 |
const apiUrl = import.meta.env.VITE_API_URL;
|
|
@@ -18,7 +18,7 @@ export const AuthProvider = ({ children }) => {
|
|
| 18 |
}
|
| 19 |
};
|
| 20 |
|
| 21 |
-
const saveToken = (token) => {
|
| 22 |
if (token) {
|
| 23 |
localStorage.setItem(storageKey, token);
|
| 24 |
setAuthHeader(token);
|
|
@@ -26,13 +26,16 @@ export const AuthProvider = ({ children }) => {
|
|
| 26 |
localStorage.removeItem(storageKey);
|
| 27 |
setAuthHeader(null);
|
| 28 |
}
|
| 29 |
-
};
|
| 30 |
|
| 31 |
-
const refreshSession = async () => {
|
| 32 |
try {
|
| 33 |
const storedToken = localStorage.getItem(storageKey);
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
| 36 |
}
|
| 37 |
|
| 38 |
const res = await axios.get(`${apiUrl}/auth/me`);
|
|
@@ -45,11 +48,36 @@ export const AuthProvider = ({ children }) => {
|
|
| 45 |
} finally {
|
| 46 |
setIsBootstrapping(false);
|
| 47 |
}
|
| 48 |
-
};
|
| 49 |
|
| 50 |
useEffect(() => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
refreshSession();
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
const login = async (credentials) => {
|
| 55 |
const res = await axios.post(`${apiUrl}/auth/login`, credentials);
|
|
|
|
| 1 |
/* eslint-disable react-refresh/only-export-components */
|
| 2 |
+
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
| 3 |
import axios from "axios";
|
| 4 |
|
| 5 |
const apiUrl = import.meta.env.VITE_API_URL;
|
|
|
|
| 18 |
}
|
| 19 |
};
|
| 20 |
|
| 21 |
+
const saveToken = useCallback((token) => {
|
| 22 |
if (token) {
|
| 23 |
localStorage.setItem(storageKey, token);
|
| 24 |
setAuthHeader(token);
|
|
|
|
| 26 |
localStorage.removeItem(storageKey);
|
| 27 |
setAuthHeader(null);
|
| 28 |
}
|
| 29 |
+
}, []);
|
| 30 |
|
| 31 |
+
const refreshSession = useCallback(async () => {
|
| 32 |
try {
|
| 33 |
const storedToken = localStorage.getItem(storageKey);
|
| 34 |
+
saveToken(storedToken);
|
| 35 |
+
|
| 36 |
+
if (!storedToken) {
|
| 37 |
+
setUser(null);
|
| 38 |
+
return null;
|
| 39 |
}
|
| 40 |
|
| 41 |
const res = await axios.get(`${apiUrl}/auth/me`);
|
|
|
|
| 48 |
} finally {
|
| 49 |
setIsBootstrapping(false);
|
| 50 |
}
|
| 51 |
+
}, [saveToken]);
|
| 52 |
|
| 53 |
useEffect(() => {
|
| 54 |
+
const requestInterceptor = axios.interceptors.request.use((config) => {
|
| 55 |
+
const token = localStorage.getItem(storageKey);
|
| 56 |
+
if (token) {
|
| 57 |
+
config.headers = config.headers || {};
|
| 58 |
+
config.headers.Authorization = `Bearer ${token}`;
|
| 59 |
+
}
|
| 60 |
+
return config;
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
const responseInterceptor = axios.interceptors.response.use(
|
| 64 |
+
(response) => response,
|
| 65 |
+
(error) => {
|
| 66 |
+
if (error?.response?.status === 401) {
|
| 67 |
+
saveToken(null);
|
| 68 |
+
setUser(null);
|
| 69 |
+
}
|
| 70 |
+
return Promise.reject(error);
|
| 71 |
+
}
|
| 72 |
+
);
|
| 73 |
+
|
| 74 |
refreshSession();
|
| 75 |
+
|
| 76 |
+
return () => {
|
| 77 |
+
axios.interceptors.request.eject(requestInterceptor);
|
| 78 |
+
axios.interceptors.response.eject(responseInterceptor);
|
| 79 |
+
};
|
| 80 |
+
}, [refreshSession, saveToken]);
|
| 81 |
|
| 82 |
const login = async (credentials) => {
|
| 83 |
const res = await axios.post(`${apiUrl}/auth/login`, credentials);
|
frontend/src/components/Customers/CustomersWorkspace.jsx
CHANGED
|
@@ -25,16 +25,18 @@ const CustomersWorkspace = () => {
|
|
| 25 |
const [searchTerm, setSearchTerm] = useState("");
|
| 26 |
const debouncedSearch = useDebounce(searchTerm, 2000);
|
| 27 |
const [page, setPage] = useState(1);
|
|
|
|
| 28 |
const [activeCustomerId, setActiveCustomerId] = useState(null);
|
| 29 |
const [pendingDeleteId, setPendingDeleteId] = useState(null);
|
| 30 |
|
| 31 |
const { data: response, isLoading } = useQuery({
|
| 32 |
-
queryKey: ["customers", page, debouncedSearch],
|
| 33 |
queryFn: () => axios.get(`${apiUrl}/customers`, {
|
| 34 |
params: {
|
| 35 |
page,
|
| 36 |
limit: 5,
|
| 37 |
-
search: debouncedSearch
|
|
|
|
| 38 |
}
|
| 39 |
}),
|
| 40 |
refetchOnWindowFocus: false,
|
|
@@ -67,6 +69,18 @@ const CustomersWorkspace = () => {
|
|
| 67 |
},
|
| 68 |
});
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
const formik = useFormik({
|
| 71 |
initialValues: {
|
| 72 |
name: "",
|
|
@@ -135,6 +149,18 @@ const CustomersWorkspace = () => {
|
|
| 135 |
className="h-11 w-full rounded-2xl border border-slate-200 bg-slate-50 pr-11 pl-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-amber-500"
|
| 136 |
/>
|
| 137 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
</div>
|
| 139 |
|
| 140 |
<div className="overflow-x-auto">
|
|
@@ -170,24 +196,38 @@ const CustomersWorkspace = () => {
|
|
| 170 |
</td>
|
| 171 |
<td className="px-4 py-4">
|
| 172 |
<div className="flex flex-wrap items-center gap-2">
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
<button
|
| 182 |
type="button"
|
| 183 |
-
onClick={() =>
|
| 184 |
-
|
|
|
|
| 185 |
>
|
| 186 |
<PlusCircle size={16} />
|
| 187 |
-
|
| 188 |
</button>
|
| 189 |
-
) :
|
| 190 |
-
{permissions.canDeleteCustomers ? (
|
| 191 |
pendingDeleteId === customer._id ? (
|
| 192 |
<div className="flex items-center gap-2 rounded-2xl border border-rose-200 bg-rose-50 px-3 py-2">
|
| 193 |
<span className="text-xs font-bold text-rose-700">حذف الحساب؟</span>
|
|
|
|
| 25 |
const [searchTerm, setSearchTerm] = useState("");
|
| 26 |
const debouncedSearch = useDebounce(searchTerm, 2000);
|
| 27 |
const [page, setPage] = useState(1);
|
| 28 |
+
const [showDeleted, setShowDeleted] = useState(false);
|
| 29 |
const [activeCustomerId, setActiveCustomerId] = useState(null);
|
| 30 |
const [pendingDeleteId, setPendingDeleteId] = useState(null);
|
| 31 |
|
| 32 |
const { data: response, isLoading } = useQuery({
|
| 33 |
+
queryKey: ["customers", page, debouncedSearch, showDeleted],
|
| 34 |
queryFn: () => axios.get(`${apiUrl}/customers`, {
|
| 35 |
params: {
|
| 36 |
page,
|
| 37 |
limit: 5,
|
| 38 |
+
search: debouncedSearch,
|
| 39 |
+
deleted: showDeleted,
|
| 40 |
}
|
| 41 |
}),
|
| 42 |
refetchOnWindowFocus: false,
|
|
|
|
| 69 |
},
|
| 70 |
});
|
| 71 |
|
| 72 |
+
const restoreCustomerMutation = useMutation({
|
| 73 |
+
mutationFn: (customerId) => axios.patch(`${apiUrl}/customers/${customerId}/restore`),
|
| 74 |
+
onSuccess: () => {
|
| 75 |
+
queryClient.invalidateQueries({ queryKey: ["customers"] });
|
| 76 |
+
queryClient.invalidateQueries({ queryKey: ["reports", "overview"] });
|
| 77 |
+
toast.success("تم استعادة العميل بنجاح");
|
| 78 |
+
},
|
| 79 |
+
onError: (error) => {
|
| 80 |
+
toast.error(error.response?.data?.message || "تعذر استعادة العميل");
|
| 81 |
+
},
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
const formik = useFormik({
|
| 85 |
initialValues: {
|
| 86 |
name: "",
|
|
|
|
| 149 |
className="h-11 w-full rounded-2xl border border-slate-200 bg-slate-50 pr-11 pl-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-amber-500"
|
| 150 |
/>
|
| 151 |
</div>
|
| 152 |
+
{permissions.canDeleteCustomers ? (
|
| 153 |
+
<button
|
| 154 |
+
type="button"
|
| 155 |
+
onClick={() => {
|
| 156 |
+
setShowDeleted((prev) => !prev);
|
| 157 |
+
setPage(1);
|
| 158 |
+
}}
|
| 159 |
+
className="h-11 rounded-2xl border border-slate-200 bg-white px-4 text-sm font-bold text-slate-700 transition hover:bg-slate-100"
|
| 160 |
+
>
|
| 161 |
+
{showDeleted ? "إخفاء المحذوفين" : "عرض العملاء المحذوفين"}
|
| 162 |
+
</button>
|
| 163 |
+
) : null}
|
| 164 |
</div>
|
| 165 |
|
| 166 |
<div className="overflow-x-auto">
|
|
|
|
| 196 |
</td>
|
| 197 |
<td className="px-4 py-4">
|
| 198 |
<div className="flex flex-wrap items-center gap-2">
|
| 199 |
+
{!showDeleted ? (
|
| 200 |
+
<>
|
| 201 |
+
<Link
|
| 202 |
+
to={`/customers/${customer._id}`}
|
| 203 |
+
className="flex h-10 items-center justify-center gap-2 rounded-2xl bg-slate-900 px-4 font-bold text-white transition hover:bg-slate-800"
|
| 204 |
+
>
|
| 205 |
+
<Eye size={16} />
|
| 206 |
+
التفاصيل
|
| 207 |
+
</Link>
|
| 208 |
+
{permissions.canCreateInvoices ? (
|
| 209 |
+
<button
|
| 210 |
+
type="button"
|
| 211 |
+
onClick={() => setActiveCustomerId(customer._id)}
|
| 212 |
+
className="flex h-10 items-center justify-center gap-2 rounded-2xl bg-amber-500 px-4 font-bold text-slate-900 transition hover:bg-amber-400"
|
| 213 |
+
>
|
| 214 |
+
<PlusCircle size={16} />
|
| 215 |
+
فاتورة جديدة
|
| 216 |
+
</button>
|
| 217 |
+
) : null}
|
| 218 |
+
</>
|
| 219 |
+
) : null}
|
| 220 |
+
{showDeleted ? (
|
| 221 |
<button
|
| 222 |
type="button"
|
| 223 |
+
onClick={() => restoreCustomerMutation.mutate(customer._id)}
|
| 224 |
+
disabled={restoreCustomerMutation.isPending}
|
| 225 |
+
className="flex h-10 items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-4 font-bold text-white transition hover:bg-emerald-700 disabled:opacity-60"
|
| 226 |
>
|
| 227 |
<PlusCircle size={16} />
|
| 228 |
+
استعادة العميل
|
| 229 |
</button>
|
| 230 |
+
) : permissions.canDeleteCustomers ? (
|
|
|
|
| 231 |
pendingDeleteId === customer._id ? (
|
| 232 |
<div className="flex items-center gap-2 rounded-2xl border border-rose-200 bg-rose-50 px-3 py-2">
|
| 233 |
<span className="text-xs font-bold text-rose-700">حذف الحساب؟</span>
|
frontend/src/components/Dashboard/DashboardTab.jsx
CHANGED
|
@@ -14,7 +14,8 @@ import {
|
|
| 14 |
import LodderSpinner from "../../common/LoaderSpinner";
|
| 15 |
import Pagination from "../../common/Pagination";
|
| 16 |
import { useAuth } from "../../Context/AuthContext";
|
| 17 |
-
import {
|
|
|
|
| 18 |
|
| 19 |
const apiUrl = import.meta.env.VITE_API_URL;
|
| 20 |
const EMPTY_LIST = [];
|
|
@@ -36,6 +37,7 @@ const toneClasses = {
|
|
| 36 |
|
| 37 |
const DashboardTab = () => {
|
| 38 |
const { user } = useAuth();
|
|
|
|
| 39 |
const currency = user?.tenant?.settings?.currency || "EGP";
|
| 40 |
|
| 41 |
const [invoicesPage, setInvoicesPage] = useState(1);
|
|
@@ -44,6 +46,13 @@ const DashboardTab = () => {
|
|
| 44 |
const [lowStockPage, setLowStockPage] = useState(1);
|
| 45 |
const limit = 5;
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
const { data, isLoading } = useQuery({
|
| 48 |
queryKey: ["reports", "overview", invoicesPage, paymentsPage, customersPage, lowStockPage],
|
| 49 |
queryFn: () => axios.get(`${apiUrl}/reports/overview`, {
|
|
@@ -93,6 +102,53 @@ const DashboardTab = () => {
|
|
| 93 |
)})}
|
| 94 |
</div>
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
<div className="grid gap-6 xl:grid-cols-[1.8fr_1fr]">
|
| 97 |
<section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
|
| 98 |
<div className="mb-6 flex items-center justify-between gap-4">
|
|
|
|
| 14 |
import LodderSpinner from "../../common/LoaderSpinner";
|
| 15 |
import Pagination from "../../common/Pagination";
|
| 16 |
import { useAuth } from "../../Context/AuthContext";
|
| 17 |
+
import { getPermissions } from "../../utils/permissions";
|
| 18 |
+
import { formatCurrency, formatDate, formatDateTime, formatNumber, formatBytes } from "../../utils/formatters";
|
| 19 |
|
| 20 |
const apiUrl = import.meta.env.VITE_API_URL;
|
| 21 |
const EMPTY_LIST = [];
|
|
|
|
| 37 |
|
| 38 |
const DashboardTab = () => {
|
| 39 |
const { user } = useAuth();
|
| 40 |
+
const permissions = getPermissions(user);
|
| 41 |
const currency = user?.tenant?.settings?.currency || "EGP";
|
| 42 |
|
| 43 |
const [invoicesPage, setInvoicesPage] = useState(1);
|
|
|
|
| 46 |
const [lowStockPage, setLowStockPage] = useState(1);
|
| 47 |
const limit = 5;
|
| 48 |
|
| 49 |
+
const { data: dbUsageData } = useQuery({
|
| 50 |
+
queryKey: ["db-usage"],
|
| 51 |
+
queryFn: () => axios.get(`${apiUrl}/auth/db-usage`),
|
| 52 |
+
enabled: permissions.isSuperAdmin,
|
| 53 |
+
refetchOnWindowFocus: false,
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
const { data, isLoading } = useQuery({
|
| 57 |
queryKey: ["reports", "overview", invoicesPage, paymentsPage, customersPage, lowStockPage],
|
| 58 |
queryFn: () => axios.get(`${apiUrl}/reports/overview`, {
|
|
|
|
| 102 |
)})}
|
| 103 |
</div>
|
| 104 |
|
| 105 |
+
{dbUsageData?.data ? (
|
| 106 |
+
<section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
|
| 107 |
+
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
| 108 |
+
<div>
|
| 109 |
+
<h3 className="text-xl font-black text-slate-900">استخدام قاعدة البيانات</h3>
|
| 110 |
+
<p className="text-sm text-slate-500">رصد استهلاك MongoDB Atlas وتخزين المجموعة الحالية.</p>
|
| 111 |
+
</div>
|
| 112 |
+
<div className="rounded-2xl bg-slate-50 px-4 py-2 text-sm font-bold text-slate-600">
|
| 113 |
+
{dbUsageData.data.collections} مجموعات · {dbUsageData.data.objects} مستندات · {dbUsageData.data.indexes} فهارس
|
| 114 |
+
</div>
|
| 115 |
+
</div>
|
| 116 |
+
|
| 117 |
+
<div className="grid gap-4 md:grid-cols-3">
|
| 118 |
+
{[
|
| 119 |
+
{ label: "بيانات", value: dbUsageData.data.dataSize, color: "emerald" },
|
| 120 |
+
{ label: "فهارس", value: dbUsageData.data.indexSize, color: "blue" },
|
| 121 |
+
{ label: "التخزين الإجمالي", value: dbUsageData.data.storageSize, color: "rose" },
|
| 122 |
+
].map((item) => {
|
| 123 |
+
const percentage = dbUsageData.data.fileSize
|
| 124 |
+
? Math.min(100, Math.round((item.value / dbUsageData.data.fileSize) * 100))
|
| 125 |
+
: 0;
|
| 126 |
+
return (
|
| 127 |
+
<div key={item.label} className="rounded-3xl border border-slate-200 bg-slate-50 p-4">
|
| 128 |
+
<div className="flex items-center justify-between gap-4">
|
| 129 |
+
<p className="text-sm font-bold text-slate-600">{item.label}</p>
|
| 130 |
+
<span className={`rounded-full px-3 py-1 text-xs font-bold ${item.color === "emerald" ? "bg-emerald-100 text-emerald-700" : item.color === "blue" ? "bg-blue-100 text-blue-700" : "bg-rose-100 text-rose-700"}`}>
|
| 131 |
+
{percentage}%
|
| 132 |
+
</span>
|
| 133 |
+
</div>
|
| 134 |
+
<p className="mt-3 text-2xl font-black text-slate-900">{formatBytes(item.value)}</p>
|
| 135 |
+
<div className="mt-4 h-3 overflow-hidden rounded-full bg-slate-200">
|
| 136 |
+
<div className={`h-full ${item.color === "emerald" ? "bg-emerald-600" : item.color === "blue" ? "bg-blue-600" : "bg-rose-600"}`} style={{ width: `${percentage}%` }} />
|
| 137 |
+
</div>
|
| 138 |
+
</div>
|
| 139 |
+
);
|
| 140 |
+
})}
|
| 141 |
+
</div>
|
| 142 |
+
|
| 143 |
+
{dbUsageData.data.fsTotalSize ? (
|
| 144 |
+
<div className="mt-6 rounded-3xl border border-slate-200 bg-white p-4">
|
| 145 |
+
<p className="text-sm font-bold text-slate-600">سعة التخزين المتاحة في نظام الملفات</p>
|
| 146 |
+
<p className="mt-2 text-sm text-slate-700">{formatBytes(dbUsageData.data.fsUsedSize)} مستخدمة من أصل {formatBytes(dbUsageData.data.fsTotalSize)}</p>
|
| 147 |
+
</div>
|
| 148 |
+
) : null}
|
| 149 |
+
</section>
|
| 150 |
+
) : null}
|
| 151 |
+
|
| 152 |
<div className="grid gap-6 xl:grid-cols-[1.8fr_1fr]">
|
| 153 |
<section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
|
| 154 |
<div className="mb-6 flex items-center justify-between gap-4">
|
frontend/src/components/Suppliers/SuppliersWorkspace.jsx
CHANGED
|
@@ -2,7 +2,7 @@ import { useState } from "react";
|
|
| 2 |
import useDebounce from "../../hooks/useDebounce";
|
| 3 |
import axios from "axios";
|
| 4 |
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
| 5 |
-
import { ArrowUpRight, Boxes, Factory, Loader2, MessageCircle, PlusCircle, Search, Trash2 } from "lucide-react";
|
| 6 |
import { useFormik } from "formik";
|
| 7 |
import * as Yup from "yup";
|
| 8 |
import { toast } from "react-toastify";
|
|
@@ -25,6 +25,10 @@ const SuppliersWorkspace = () => {
|
|
| 25 |
const [purchaseSupplier, setPurchaseSupplier] = useState(null);
|
| 26 |
const [paymentSupplier, setPaymentSupplier] = useState(null);
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
const { data: response, isLoading } = useQuery({
|
| 29 |
queryKey: ["suppliers", page, debouncedSearch],
|
| 30 |
queryFn: () => axios.get(`${apiUrl}/suppliers`, {
|
|
@@ -36,6 +40,19 @@ const SuppliersWorkspace = () => {
|
|
| 36 |
}),
|
| 37 |
refetchOnWindowFocus: false,
|
| 38 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
const { data: productsData } = useQuery({
|
| 40 |
queryKey: ["products", "all"],
|
| 41 |
queryFn: () => axios.get(`${apiUrl}/products`, { params: { limit: 1000 } }),
|
|
@@ -67,6 +84,39 @@ const SuppliersWorkspace = () => {
|
|
| 67 |
},
|
| 68 |
});
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
const formik = useFormik({
|
| 71 |
initialValues: {
|
| 72 |
name: "",
|
|
@@ -81,13 +131,36 @@ const SuppliersWorkspace = () => {
|
|
| 81 |
|
| 82 |
const suppliers = response?.data?.data ?? [];
|
| 83 |
const pagination = response?.data?.pagination || { total: 0, totalPages: 0 };
|
|
|
|
|
|
|
| 84 |
|
| 85 |
const handleSearchChange = (e) => {
|
| 86 |
setSearchTerm(e.target.value);
|
| 87 |
setPage(1);
|
| 88 |
};
|
| 89 |
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return <LodderSpinner />;
|
| 92 |
}
|
| 93 |
|
|
@@ -232,6 +305,146 @@ const SuppliersWorkspace = () => {
|
|
| 232 |
/>
|
| 233 |
</section>
|
| 234 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
{purchaseSupplier ? (
|
| 236 |
<ReceiveGoodsModal
|
| 237 |
supplier={purchaseSupplier}
|
|
|
|
| 2 |
import useDebounce from "../../hooks/useDebounce";
|
| 3 |
import axios from "axios";
|
| 4 |
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
| 5 |
+
import { ArrowUpRight, Boxes, DollarSign, Factory, Loader2, MessageCircle, PlusCircle, Search, Trash2 } from "lucide-react";
|
| 6 |
import { useFormik } from "formik";
|
| 7 |
import * as Yup from "yup";
|
| 8 |
import { toast } from "react-toastify";
|
|
|
|
| 25 |
const [purchaseSupplier, setPurchaseSupplier] = useState(null);
|
| 26 |
const [paymentSupplier, setPaymentSupplier] = useState(null);
|
| 27 |
|
| 28 |
+
const [expenseSearch, setExpenseSearch] = useState("");
|
| 29 |
+
const debouncedExpenseSearch = useDebounce(expenseSearch, 2000);
|
| 30 |
+
const [expensePage, setExpensePage] = useState(1);
|
| 31 |
+
|
| 32 |
const { data: response, isLoading } = useQuery({
|
| 33 |
queryKey: ["suppliers", page, debouncedSearch],
|
| 34 |
queryFn: () => axios.get(`${apiUrl}/suppliers`, {
|
|
|
|
| 40 |
}),
|
| 41 |
refetchOnWindowFocus: false,
|
| 42 |
});
|
| 43 |
+
|
| 44 |
+
const { data: expenseResponse, isLoading: isExpenseLoading } = useQuery({
|
| 45 |
+
queryKey: ["expenses", expensePage, debouncedExpenseSearch],
|
| 46 |
+
queryFn: () => axios.get(`${apiUrl}/expenses`, {
|
| 47 |
+
params: {
|
| 48 |
+
page: expensePage,
|
| 49 |
+
limit: 5,
|
| 50 |
+
search: debouncedExpenseSearch,
|
| 51 |
+
},
|
| 52 |
+
}),
|
| 53 |
+
refetchOnWindowFocus: false,
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
const { data: productsData } = useQuery({
|
| 57 |
queryKey: ["products", "all"],
|
| 58 |
queryFn: () => axios.get(`${apiUrl}/products`, { params: { limit: 1000 } }),
|
|
|
|
| 84 |
},
|
| 85 |
});
|
| 86 |
|
| 87 |
+
const addExpenseMutation = useMutation({
|
| 88 |
+
mutationFn: (values) => axios.post(`${apiUrl}/expenses`, values),
|
| 89 |
+
onSuccess: () => {
|
| 90 |
+
queryClient.invalidateQueries({ queryKey: ["expenses"] });
|
| 91 |
+
queryClient.invalidateQueries({ queryKey: ["reports", "overview"] });
|
| 92 |
+
setExpenseFormik({ title: "", category: "general", amount: "", paymentMethod: "cash", notes: "" });
|
| 93 |
+
toast.success("تم تسجيل المصروف بنجاح");
|
| 94 |
+
},
|
| 95 |
+
onError: (error) => {
|
| 96 |
+
toast.error(error.response?.data?.message || "تعذر تسجيل المصروف");
|
| 97 |
+
},
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
const deleteExpenseMutation = useMutation({
|
| 101 |
+
mutationFn: (expenseId) => axios.delete(`${apiUrl}/expenses/${expenseId}`),
|
| 102 |
+
onSuccess: () => {
|
| 103 |
+
queryClient.invalidateQueries({ queryKey: ["expenses"] });
|
| 104 |
+
queryClient.invalidateQueries({ queryKey: ["reports", "overview"] });
|
| 105 |
+
toast.success("تم حذف المصروف");
|
| 106 |
+
},
|
| 107 |
+
onError: (error) => {
|
| 108 |
+
toast.error(error.response?.data?.message || "تعذر حذف المصروف");
|
| 109 |
+
},
|
| 110 |
+
});
|
| 111 |
+
|
| 112 |
+
const [expenseFormik, setExpenseFormik] = useState({
|
| 113 |
+
title: "",
|
| 114 |
+
category: "general",
|
| 115 |
+
amount: "",
|
| 116 |
+
paymentMethod: "cash",
|
| 117 |
+
notes: "",
|
| 118 |
+
});
|
| 119 |
+
|
| 120 |
const formik = useFormik({
|
| 121 |
initialValues: {
|
| 122 |
name: "",
|
|
|
|
| 131 |
|
| 132 |
const suppliers = response?.data?.data ?? [];
|
| 133 |
const pagination = response?.data?.pagination || { total: 0, totalPages: 0 };
|
| 134 |
+
const expenses = expenseResponse?.data?.data ?? [];
|
| 135 |
+
const expensePagination = expenseResponse?.data?.pagination || { total: 0, totalPages: 0 };
|
| 136 |
|
| 137 |
const handleSearchChange = (e) => {
|
| 138 |
setSearchTerm(e.target.value);
|
| 139 |
setPage(1);
|
| 140 |
};
|
| 141 |
|
| 142 |
+
const handleExpenseSearchChange = (e) => {
|
| 143 |
+
setExpenseSearch(e.target.value);
|
| 144 |
+
setExpensePage(1);
|
| 145 |
+
};
|
| 146 |
+
|
| 147 |
+
const handleExpenseChange = (e) => {
|
| 148 |
+
const { name, value } = e.target;
|
| 149 |
+
setExpenseFormik((prev) => ({ ...prev, [name]: value }));
|
| 150 |
+
};
|
| 151 |
+
|
| 152 |
+
const handleExpenseSubmit = (e) => {
|
| 153 |
+
e.preventDefault();
|
| 154 |
+
addExpenseMutation.mutate({
|
| 155 |
+
title: expenseFormik.title,
|
| 156 |
+
category: expenseFormik.category,
|
| 157 |
+
amount: Number(expenseFormik.amount),
|
| 158 |
+
paymentMethod: expenseFormik.paymentMethod,
|
| 159 |
+
notes: expenseFormik.notes,
|
| 160 |
+
});
|
| 161 |
+
};
|
| 162 |
+
|
| 163 |
+
if (isLoading || isExpenseLoading) {
|
| 164 |
return <LodderSpinner />;
|
| 165 |
}
|
| 166 |
|
|
|
|
| 305 |
/>
|
| 306 |
</section>
|
| 307 |
|
| 308 |
+
<section className="rounded-3xl border border-slate-200 bg-white shadow-sm">
|
| 309 |
+
<div className="flex flex-col gap-4 border-b border-slate-100 p-5 md:flex-row md:items-center md:justify-between">
|
| 310 |
+
<div>
|
| 311 |
+
<h3 className="text-lg font-black text-slate-900">سجل المصروفات</h3>
|
| 312 |
+
<p className="text-sm text-slate-500">سجل المصروفات بسهولة وراجع الفواتير الأخيرة دفعة واحدة.</p>
|
| 313 |
+
</div>
|
| 314 |
+
<div className="relative w-full md:max-w-sm">
|
| 315 |
+
<Search size={18} className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400" />
|
| 316 |
+
<input
|
| 317 |
+
type="text"
|
| 318 |
+
value={expenseSearch}
|
| 319 |
+
onChange={handleExpenseSearchChange}
|
| 320 |
+
placeholder="البحث في السجلات..."
|
| 321 |
+
className="h-11 w-full rounded-2xl border border-slate-200 bg-slate-50 pr-11 pl-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-indigo-500"
|
| 322 |
+
/>
|
| 323 |
+
</div>
|
| 324 |
+
</div>
|
| 325 |
+
|
| 326 |
+
<div className="p-5">
|
| 327 |
+
<form onSubmit={handleExpenseSubmit} className="grid gap-4 lg:grid-cols-[1fr_1fr] xl:grid-cols-[1fr_1fr_300px]">
|
| 328 |
+
<div>
|
| 329 |
+
<label className="mb-1 block text-xs font-bold uppercase tracking-wide text-slate-500">عنوان المصروف</label>
|
| 330 |
+
<input
|
| 331 |
+
name="title"
|
| 332 |
+
value={expenseFormik.title}
|
| 333 |
+
onChange={handleExpenseChange}
|
| 334 |
+
className="h-12 w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-indigo-500"
|
| 335 |
+
/>
|
| 336 |
+
</div>
|
| 337 |
+
<div>
|
| 338 |
+
<label className="mb-1 block text-xs font-bold uppercase tracking-wide text-slate-500">المبلغ</label>
|
| 339 |
+
<input
|
| 340 |
+
name="amount"
|
| 341 |
+
type="number"
|
| 342 |
+
value={expenseFormik.amount}
|
| 343 |
+
onChange={handleExpenseChange}
|
| 344 |
+
className="h-12 w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-indigo-500"
|
| 345 |
+
/>
|
| 346 |
+
</div>
|
| 347 |
+
<div>
|
| 348 |
+
<label className="mb-1 block text-xs font-bold uppercase tracking-wide text-slate-500">التصنيف</label>
|
| 349 |
+
<select
|
| 350 |
+
name="category"
|
| 351 |
+
value={expenseFormik.category}
|
| 352 |
+
onChange={handleExpenseChange}
|
| 353 |
+
className="h-12 w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-indigo-500"
|
| 354 |
+
>
|
| 355 |
+
<option value="general">عام</option>
|
| 356 |
+
<option value="sales">مبيعات</option>
|
| 357 |
+
<option value="services">خدمات</option>
|
| 358 |
+
<option value="other">أخرى</option>
|
| 359 |
+
</select>
|
| 360 |
+
</div>
|
| 361 |
+
<div>
|
| 362 |
+
<label className="mb-1 block text-xs font-bold uppercase tracking-wide text-slate-500">طريقة الدفع</label>
|
| 363 |
+
<select
|
| 364 |
+
name="paymentMethod"
|
| 365 |
+
value={expenseFormik.paymentMethod}
|
| 366 |
+
onChange={handleExpenseChange}
|
| 367 |
+
className="h-12 w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-indigo-500"
|
| 368 |
+
>
|
| 369 |
+
<option value="cash">نقدي</option>
|
| 370 |
+
<option value="bank">بنك</option>
|
| 371 |
+
<option value="card">بطاقة</option>
|
| 372 |
+
<option value="other">أخرى</option>
|
| 373 |
+
</select>
|
| 374 |
+
</div>
|
| 375 |
+
<div className="lg:col-span-2 xl:col-span-1">
|
| 376 |
+
<label className="mb-1 block text-xs font-bold uppercase tracking-wide text-slate-500">ملاحظات</label>
|
| 377 |
+
<input
|
| 378 |
+
name="notes"
|
| 379 |
+
value={expenseFormik.notes}
|
| 380 |
+
onChange={handleExpenseChange}
|
| 381 |
+
className="h-12 w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 font-medium text-slate-800 outline-none transition focus:bg-white focus:ring-2 focus:ring-indigo-500"
|
| 382 |
+
/>
|
| 383 |
+
</div>
|
| 384 |
+
<button
|
| 385 |
+
type="submit"
|
| 386 |
+
disabled={addExpenseMutation.isPending}
|
| 387 |
+
className="flex h-12 items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-4 font-bold text-white transition hover:bg-emerald-700 disabled:opacity-60"
|
| 388 |
+
>
|
| 389 |
+
{addExpenseMutation.isPending ? <Loader2 size={18} className="animate-spin" /> : <DollarSign size={18} />}
|
| 390 |
+
تسجيل مصروف
|
| 391 |
+
</button>
|
| 392 |
+
</form>
|
| 393 |
+
</div>
|
| 394 |
+
|
| 395 |
+
<div className="overflow-x-auto">
|
| 396 |
+
<table className="min-w-full border-collapse">
|
| 397 |
+
<thead>
|
| 398 |
+
<tr className="border-b border-slate-200 text-right text-sm font-bold text-slate-500">
|
| 399 |
+
<th className="px-4 py-3">العنوان</th>
|
| 400 |
+
<th className="px-4 py-3">المبلغ</th>
|
| 401 |
+
<th className="px-4 py-3">التصنيف</th>
|
| 402 |
+
<th className="px-4 py-3">طريقة الدفع</th>
|
| 403 |
+
<th className="px-4 py-3">التاريخ</th>
|
| 404 |
+
<th className="px-4 py-3">إجراء</th>
|
| 405 |
+
</tr>
|
| 406 |
+
</thead>
|
| 407 |
+
<tbody>
|
| 408 |
+
{expenses.length ? (
|
| 409 |
+
expenses.map((expense) => (
|
| 410 |
+
<tr key={expense._id} className="border-b border-slate-100 text-sm text-slate-700">
|
| 411 |
+
<td className="px-4 py-4 font-bold text-slate-900">{expense.title}</td>
|
| 412 |
+
<td className="px-4 py-4 text-rose-600 font-bold">-{formatCurrency(expense.amount, currency)}</td>
|
| 413 |
+
<td className="px-4 py-4 uppercase text-slate-500">{expense.category}</td>
|
| 414 |
+
<td className="px-4 py-4 text-slate-600">{expense.paymentMethod}</td>
|
| 415 |
+
<td className="px-4 py-4 text-slate-500">{new Date(expense.date).toLocaleDateString("ar-EG")}</td>
|
| 416 |
+
<td className="px-4 py-4">
|
| 417 |
+
<button
|
| 418 |
+
type="button"
|
| 419 |
+
onClick={() => deleteExpenseMutation.mutate(expense._id)}
|
| 420 |
+
disabled={deleteExpenseMutation.isPending}
|
| 421 |
+
className="flex h-10 items-center justify-center gap-2 rounded-2xl border border-rose-100 bg-rose-50 px-4 font-bold text-rose-700 transition hover:bg-rose-100 disabled:opacity-60"
|
| 422 |
+
>
|
| 423 |
+
<Trash2 size={16} /> حذف
|
| 424 |
+
</button>
|
| 425 |
+
</td>
|
| 426 |
+
</tr>
|
| 427 |
+
))
|
| 428 |
+
) : (
|
| 429 |
+
<tr>
|
| 430 |
+
<td colSpan="6" className="px-4 py-12 text-center text-sm font-medium text-slate-500">
|
| 431 |
+
لا يوجد سجلات مصروفات.
|
| 432 |
+
</td>
|
| 433 |
+
</tr>
|
| 434 |
+
)}
|
| 435 |
+
</tbody>
|
| 436 |
+
</table>
|
| 437 |
+
</div>
|
| 438 |
+
|
| 439 |
+
<Pagination
|
| 440 |
+
currentPage={expensePage}
|
| 441 |
+
totalPages={expensePagination.totalPages}
|
| 442 |
+
onPageChange={setExpensePage}
|
| 443 |
+
totalItems={expensePagination.total}
|
| 444 |
+
limit={5}
|
| 445 |
+
/>
|
| 446 |
+
</section>
|
| 447 |
+
|
| 448 |
{purchaseSupplier ? (
|
| 449 |
<ReceiveGoodsModal
|
| 450 |
supplier={purchaseSupplier}
|
frontend/src/components/Tenants/TenantsAdminTab.jsx
CHANGED
|
@@ -5,6 +5,7 @@ import { useFormik } from "formik";
|
|
| 5 |
import * as Yup from "yup";
|
| 6 |
import { toast } from "react-toastify";
|
| 7 |
import LodderSpinner from "../../common/LoaderSpinner";
|
|
|
|
| 8 |
|
| 9 |
const apiUrl = import.meta.env.VITE_API_URL;
|
| 10 |
|
|
@@ -17,6 +18,29 @@ const TenantsAdminTab = () => {
|
|
| 17 |
refetchOnWindowFocus: false,
|
| 18 |
});
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
const createTenantMutation = useMutation({
|
| 21 |
mutationFn: (values) => axios.post(`${apiUrl}/auth/tenants`, values),
|
| 22 |
onSuccess: (response) => {
|
|
@@ -103,6 +127,52 @@ const TenantsAdminTab = () => {
|
|
| 103 |
</section>
|
| 104 |
|
| 105 |
<div className="grid gap-4 xl:grid-cols-2">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
{tenants.map((tenant) => (
|
| 107 |
<section key={tenant._id} className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
|
| 108 |
<div className="flex items-start justify-between gap-4">
|
|
@@ -127,7 +197,39 @@ const TenantsAdminTab = () => {
|
|
| 127 |
<Info label="حد المخزون المنخفض" value={`${tenant.settings?.lowStockThreshold || 5}`} icon={<Power size={16} />} />
|
| 128 |
</div>
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
<div className="mt-5 flex flex-wrap gap-3">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
<button
|
| 132 |
type="button"
|
| 133 |
onClick={() => statusMutation.mutate({ tenantId: tenant._id, status: tenant.status === "active" ? "suspended" : "active" })}
|
|
|
|
| 5 |
import * as Yup from "yup";
|
| 6 |
import { toast } from "react-toastify";
|
| 7 |
import LodderSpinner from "../../common/LoaderSpinner";
|
| 8 |
+
import { formatBytes } from "../../utils/formatters";
|
| 9 |
|
| 10 |
const apiUrl = import.meta.env.VITE_API_URL;
|
| 11 |
|
|
|
|
| 18 |
refetchOnWindowFocus: false,
|
| 19 |
});
|
| 20 |
|
| 21 |
+
const { data: dbUsage, isLoading: isDbLoading } = useQuery({
|
| 22 |
+
queryKey: ["db-usage"],
|
| 23 |
+
queryFn: () => axios.get(`${apiUrl}/auth/db-usage`),
|
| 24 |
+
refetchOnWindowFocus: false,
|
| 25 |
+
staleTime: 1000 * 60 * 5,
|
| 26 |
+
});
|
| 27 |
+
|
| 28 |
+
const recordPaymentMutation = useMutation({
|
| 29 |
+
mutationFn: (tenantId) =>
|
| 30 |
+
axios.post(`${apiUrl}/auth/tenants/${tenantId}/payments`, {
|
| 31 |
+
amount: 800,
|
| 32 |
+
method: "manual",
|
| 33 |
+
note: "Direct monthly fee payment",
|
| 34 |
+
}),
|
| 35 |
+
onSuccess: () => {
|
| 36 |
+
queryClient.invalidateQueries({ queryKey: ["tenants"] });
|
| 37 |
+
toast.success("تم تسجيل الدفعة الشهرية بنجاح");
|
| 38 |
+
},
|
| 39 |
+
onError: (error) => {
|
| 40 |
+
toast.error(error.response?.data?.message || "تعذر تسجيل الدفعة");
|
| 41 |
+
},
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
const createTenantMutation = useMutation({
|
| 45 |
mutationFn: (values) => axios.post(`${apiUrl}/auth/tenants`, values),
|
| 46 |
onSuccess: (response) => {
|
|
|
|
| 127 |
</section>
|
| 128 |
|
| 129 |
<div className="grid gap-4 xl:grid-cols-2">
|
| 130 |
+
{dbUsage?.data ? (
|
| 131 |
+
<section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
|
| 132 |
+
<div className="mb-5 flex items-center gap-3">
|
| 133 |
+
<div className="flex h-12 w-12 items-center justify-center rounded-2xl border border-sky-100 bg-sky-50 text-sky-700">
|
| 134 |
+
<Building2 size={22} />
|
| 135 |
+
</div>
|
| 136 |
+
<div>
|
| 137 |
+
<h3 className="text-xl font-black text-slate-900">استخدام قاعدة البيانات</h3>
|
| 138 |
+
<p className="text-sm text-slate-500">عرض استهلاك MongoDB Atlas الحالي في رسم بياني مبسط.</p>
|
| 139 |
+
</div>
|
| 140 |
+
</div>
|
| 141 |
+
|
| 142 |
+
<div className="grid gap-4 md:grid-cols-3">
|
| 143 |
+
{[
|
| 144 |
+
{ label: "بيانات", value: dbUsage.data.dataSize, color: "emerald" },
|
| 145 |
+
{ label: "فهارس", value: dbUsage.data.indexSize, color: "blue" },
|
| 146 |
+
{ label: "التخزين", value: dbUsage.data.storageSize, color: "rose" },
|
| 147 |
+
].map((item) => {
|
| 148 |
+
const percentage = dbUsage.data.fileSize ? Math.min(100, Math.round((item.value / dbUsage.data.fileSize) * 100)) : 0;
|
| 149 |
+
return (
|
| 150 |
+
<div key={item.label} className="rounded-3xl border border-slate-200 bg-slate-50 p-4">
|
| 151 |
+
<div className="flex items-center justify-between gap-3">
|
| 152 |
+
<p className="text-sm font-bold text-slate-600">{item.label}</p>
|
| 153 |
+
<span className={`rounded-full px-3 py-1 text-xs font-bold ${item.color === "emerald" ? "bg-emerald-100 text-emerald-700" : item.color === "blue" ? "bg-blue-100 text-blue-700" : "bg-rose-100 text-rose-700"}`}>
|
| 154 |
+
{percentage}%
|
| 155 |
+
</span>
|
| 156 |
+
</div>
|
| 157 |
+
<p className="mt-3 text-2xl font-black text-slate-900">{formatBytes(item.value)}</p>
|
| 158 |
+
<div className="mt-4 h-3 overflow-hidden rounded-full bg-slate-200">
|
| 159 |
+
<div className={`h-full ${item.color === "emerald" ? "bg-emerald-600" : item.color === "blue" ? "bg-blue-600" : "bg-rose-600"}`} style={{ width: `${percentage}%` }} />
|
| 160 |
+
</div>
|
| 161 |
+
</div>
|
| 162 |
+
);
|
| 163 |
+
})}
|
| 164 |
+
</div>
|
| 165 |
+
|
| 166 |
+
{dbUsage.data.fsTotalSize ? (
|
| 167 |
+
<div className="mt-6 rounded-3xl border border-slate-200 bg-white p-4">
|
| 168 |
+
<p className="text-sm font-bold text-slate-600">سعة التخزين المتاحة</p>
|
| 169 |
+
<p className="mt-2 text-sm text-slate-700">
|
| 170 |
+
{formatBytes(dbUsage.data.fsUsedSize)} مستخدمة من أصل {formatBytes(dbUsage.data.fsTotalSize)}
|
| 171 |
+
</p>
|
| 172 |
+
</div>
|
| 173 |
+
) : null}
|
| 174 |
+
</section>
|
| 175 |
+
) : null}
|
| 176 |
{tenants.map((tenant) => (
|
| 177 |
<section key={tenant._id} className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
|
| 178 |
<div className="flex items-start justify-between gap-4">
|
|
|
|
| 197 |
<Info label="حد المخزون المنخفض" value={`${tenant.settings?.lowStockThreshold || 5}`} icon={<Power size={16} />} />
|
| 198 |
</div>
|
| 199 |
|
| 200 |
+
<div className="mt-5 rounded-3xl border border-slate-200 bg-slate-50 p-4">
|
| 201 |
+
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
| 202 |
+
<div>
|
| 203 |
+
<p className="text-xs font-bold uppercase tracking-wide text-slate-500">حالة دفعة الشهرية</p>
|
| 204 |
+
<p className="mt-1 text-sm font-black text-slate-900 capitalize">{tenant.paymentStatus === "overdue" ? "متأخر" : "مستحق"}</p>
|
| 205 |
+
</div>
|
| 206 |
+
<div className="flex flex-wrap items-center gap-2">
|
| 207 |
+
<span className="rounded-full bg-emerald-100 px-3 py-1 text-xs font-bold text-emerald-700">{tenant.monthlyFeeAmount} {tenant.monthlyFeeCurrency}</span>
|
| 208 |
+
<span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-bold text-slate-700">{tenant.paymentsCount} دفعات</span>
|
| 209 |
+
</div>
|
| 210 |
+
</div>
|
| 211 |
+
<div className="mt-4 grid gap-2 sm:grid-cols-2">
|
| 212 |
+
<div className="rounded-2xl bg-white p-3 text-sm text-slate-700 shadow-sm">
|
| 213 |
+
<p className="text-[11px] uppercase tracking-[0.2em] text-slate-500">تاريخ الاستحقاق التالي</p>
|
| 214 |
+
<p className="mt-2 font-bold text-slate-900">{tenant.nextPaymentDueAt ? new Date(tenant.nextPaymentDueAt).toLocaleDateString("en-EG") : "لم يتم التعيين"}</p>
|
| 215 |
+
</div>
|
| 216 |
+
<div className="rounded-2xl bg-white p-3 text-sm text-slate-700 shadow-sm">
|
| 217 |
+
<p className="text-[11px] uppercase tracking-[0.2em] text-slate-500">آخر دفعة</p>
|
| 218 |
+
<p className="mt-2 font-bold text-slate-900">{tenant.lastPaymentAt ? new Date(tenant.lastPaymentAt).toLocaleDateString("en-EG") : "لم يتم الدفع"}</p>
|
| 219 |
+
</div>
|
| 220 |
+
</div>
|
| 221 |
+
</div>
|
| 222 |
+
|
| 223 |
<div className="mt-5 flex flex-wrap gap-3">
|
| 224 |
+
<button
|
| 225 |
+
type="button"
|
| 226 |
+
onClick={() => recordPaymentMutation.mutate(tenant._id)}
|
| 227 |
+
disabled={recordPaymentMutation.isPending}
|
| 228 |
+
className="flex h-10 items-center justify-center gap-2 rounded-2xl bg-cyan-600 px-4 font-bold text-white transition hover:bg-cyan-700 disabled:opacity-60"
|
| 229 |
+
>
|
| 230 |
+
<Plus size={16} />
|
| 231 |
+
تسجيل دفعة ٨٠٠
|
| 232 |
+
</button>
|
| 233 |
<button
|
| 234 |
type="button"
|
| 235 |
onClick={() => statusMutation.mutate({ tenantId: tenant._id, status: tenant.status === "active" ? "suspended" : "active" })}
|
frontend/src/pages/Hero.jsx
CHANGED
|
@@ -48,7 +48,7 @@ const Hero = () => {
|
|
| 48 |
{ id: "dashboard", label: "لوحة التحكم", icon: LayoutDashboard },
|
| 49 |
{ id: "customers", label: "العملاء", icon: Users2 },
|
| 50 |
{ id: "inventory", label: "المخزون", icon: Package },
|
| 51 |
-
...(permissions.canViewSuppliers ? [{ id: "suppliers", label: "الم
|
| 52 |
...(permissions.canViewReports ? [{ id: "reports", label: "التقارير", icon: ReceiptText }] : []),
|
| 53 |
...(permissions.canManageUsers ? [{ id: "users", label: "المستخدمين", icon: ShieldCheck }] : []),
|
| 54 |
...(permissions.canManageCompany ? [{ id: "company", label: "الشركة", icon: Settings2 }] : []),
|
|
|
|
| 48 |
{ id: "dashboard", label: "لوحة التحكم", icon: LayoutDashboard },
|
| 49 |
{ id: "customers", label: "العملاء", icon: Users2 },
|
| 50 |
{ id: "inventory", label: "المخزون", icon: Package },
|
| 51 |
+
...(permissions.canViewSuppliers ? [{ id: "suppliers", label: "المعاملات", icon: ReceiptText }] : []),
|
| 52 |
...(permissions.canViewReports ? [{ id: "reports", label: "التقارير", icon: ReceiptText }] : []),
|
| 53 |
...(permissions.canManageUsers ? [{ id: "users", label: "المستخدمين", icon: ShieldCheck }] : []),
|
| 54 |
...(permissions.canManageCompany ? [{ id: "company", label: "الشركة", icon: Settings2 }] : []),
|
frontend/src/pages/Login.jsx
DELETED
|
@@ -1,137 +0,0 @@
|
|
| 1 |
-
import axios from 'axios';
|
| 2 |
-
import { toast } from 'react-toastify';
|
| 3 |
-
import { Lock, User, LogIn, Store, LoaderCircle } from 'lucide-react';
|
| 4 |
-
import { useFormik } from 'formik';
|
| 5 |
-
import * as Yup from 'yup';
|
| 6 |
-
import { useEffect, useState } from 'react';
|
| 7 |
-
import { useNavigate } from 'react-router-dom';
|
| 8 |
-
import { useAuth } from '../Context/AuthContext';
|
| 9 |
-
|
| 10 |
-
const apiUrl = import.meta.env.VITE_API_URL;
|
| 11 |
-
|
| 12 |
-
const Login = () => {
|
| 13 |
-
const [setupLoading, setSetupLoading] = useState(false);
|
| 14 |
-
const [hasAdmin, setHasAdmin] = useState(true);
|
| 15 |
-
const navigate = useNavigate();
|
| 16 |
-
const { login } = useAuth();
|
| 17 |
-
|
| 18 |
-
useEffect(() => {
|
| 19 |
-
axios.get(`${apiUrl}/auth/has-admin`)
|
| 20 |
-
.then((res) => setHasAdmin(res.data.hasAdmin))
|
| 21 |
-
.catch(() => setHasAdmin(true));
|
| 22 |
-
}, []);
|
| 23 |
-
|
| 24 |
-
const handleSetup = async () => {
|
| 25 |
-
try {
|
| 26 |
-
setSetupLoading(true);
|
| 27 |
-
const res = await axios.post(`${apiUrl}/auth/setup`);
|
| 28 |
-
toast.success(res.data.message);
|
| 29 |
-
|
| 30 |
-
if (res.data.credentials) {
|
| 31 |
-
toast.info(`Username: ${res.data.credentials.username} | Password: ${res.data.credentials.password}`);
|
| 32 |
-
}
|
| 33 |
-
|
| 34 |
-
setHasAdmin(true);
|
| 35 |
-
} catch (err) {
|
| 36 |
-
toast.error(err.response?.data?.message || 'Setup failed');
|
| 37 |
-
} finally {
|
| 38 |
-
setSetupLoading(false);
|
| 39 |
-
}
|
| 40 |
-
};
|
| 41 |
-
|
| 42 |
-
const formik = useFormik({
|
| 43 |
-
initialValues: { identifier: '', password: '' },
|
| 44 |
-
validationSchema: Yup.object({
|
| 45 |
-
identifier: Yup.string().required('Username or email is required'),
|
| 46 |
-
password: Yup.string().required('Password is required'),
|
| 47 |
-
}),
|
| 48 |
-
onSubmit: async (values, { setSubmitting }) => {
|
| 49 |
-
try {
|
| 50 |
-
const res = await login(values);
|
| 51 |
-
toast.success(`Welcome back ${res.user?.fullName || res.user?.username}`);
|
| 52 |
-
navigate('/');
|
| 53 |
-
} catch (err) {
|
| 54 |
-
toast.error(err.response?.data?.message || 'Invalid login credentials');
|
| 55 |
-
} finally {
|
| 56 |
-
setSubmitting(false);
|
| 57 |
-
}
|
| 58 |
-
},
|
| 59 |
-
});
|
| 60 |
-
|
| 61 |
-
return (
|
| 62 |
-
<div className="min-h-screen bg-slate-900 flex items-center justify-center p-4 relative overflow-hidden">
|
| 63 |
-
<div className="absolute top-[-10%] left-[-10%] w-96 h-96 bg-emerald-500/15 rounded-full blur-3xl"></div>
|
| 64 |
-
<div className="absolute bottom-[-10%] right-[-10%] w-96 h-96 bg-amber-500/10 rounded-full blur-3xl"></div>
|
| 65 |
-
|
| 66 |
-
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden relative z-10 animate-in fade-in zoom-in-95 duration-500">
|
| 67 |
-
<div className="bg-slate-50 border-b border-slate-100 p-8 text-center relative overflow-hidden">
|
| 68 |
-
<div className="absolute top-0 right-0 w-full h-1.5 bg-gradient-to-l from-emerald-500 to-amber-500"></div>
|
| 69 |
-
<div className="w-20 h-20 bg-emerald-100 text-emerald-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-inner rotate-3">
|
| 70 |
-
<Store size={40} />
|
| 71 |
-
</div>
|
| 72 |
-
<h1 className="text-3xl font-black text-slate-800 tracking-tight">Cloud Accounting Platform</h1>
|
| 73 |
-
<p className="text-slate-500 mt-2 font-medium">Sign in to manage your company, invoices, and staff</p>
|
| 74 |
-
</div>
|
| 75 |
-
|
| 76 |
-
<form onSubmit={formik.handleSubmit} className="p-8 space-y-6">
|
| 77 |
-
<div>
|
| 78 |
-
<label className="block text-sm font-bold text-slate-700 mb-2">Username or Email</label>
|
| 79 |
-
<div className="relative">
|
| 80 |
-
<div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
|
| 81 |
-
<User size={20} />
|
| 82 |
-
</div>
|
| 83 |
-
<input
|
| 84 |
-
name="identifier"
|
| 85 |
-
type="text"
|
| 86 |
-
value={formik.values.identifier}
|
| 87 |
-
onChange={formik.handleChange}
|
| 88 |
-
onBlur={formik.handleBlur}
|
| 89 |
-
className={`w-full pr-4 pl-12 py-3.5 bg-slate-50 border ${formik.touched.identifier && formik.errors.identifier ? 'border-rose-400 focus:ring-rose-500' : 'border-slate-200 focus:ring-emerald-500'} rounded-xl outline-none focus:ring-2 font-bold text-slate-700 transition-colors focus:bg-white`}
|
| 90 |
-
placeholder="Enter your username or email"
|
| 91 |
-
/>
|
| 92 |
-
</div>
|
| 93 |
-
{formik.touched.identifier && formik.errors.identifier && (
|
| 94 |
-
<p className="text-rose-500 text-xs font-bold mt-1.5">{formik.errors.identifier}</p>
|
| 95 |
-
)}
|
| 96 |
-
</div>
|
| 97 |
-
|
| 98 |
-
<div>
|
| 99 |
-
<label className="block text-sm font-bold text-slate-700 mb-2">Password</label>
|
| 100 |
-
<div className="relative">
|
| 101 |
-
<div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
|
| 102 |
-
<Lock size={20} />
|
| 103 |
-
</div>
|
| 104 |
-
<input
|
| 105 |
-
name="password"
|
| 106 |
-
type="password"
|
| 107 |
-
value={formik.values.password}
|
| 108 |
-
onChange={formik.handleChange}
|
| 109 |
-
onBlur={formik.handleBlur}
|
| 110 |
-
className={`w-full pr-4 pl-12 py-3.5 bg-slate-50 border ${formik.touched.password && formik.errors.password ? 'border-rose-400 focus:ring-rose-500' : 'border-slate-200 focus:ring-emerald-500'} rounded-xl outline-none focus:ring-2 font-bold text-slate-700 transition-colors focus:bg-white tracking-widest`}
|
| 111 |
-
placeholder="��������"
|
| 112 |
-
/>
|
| 113 |
-
</div>
|
| 114 |
-
{formik.touched.password && formik.errors.password && (
|
| 115 |
-
<p className="text-rose-500 text-xs font-bold mt-1.5">{formik.errors.password}</p>
|
| 116 |
-
)}
|
| 117 |
-
</div>
|
| 118 |
-
|
| 119 |
-
<button disabled={formik.isSubmitting} type="submit" className="w-full py-4 bg-emerald-600 text-white rounded-xl font-black text-lg hover:bg-emerald-700 disabled:opacity-50 transition-all shadow-lg shadow-emerald-600/30 flex justify-center items-center gap-2 hover:-translate-y-0.5 mt-2 border border-emerald-500">
|
| 120 |
-
{formik.isSubmitting ? <LoaderCircle className="w-4 h-4 animate-spin" /> : <><LogIn size={20} /> Sign In</>}
|
| 121 |
-
</button>
|
| 122 |
-
</form>
|
| 123 |
-
|
| 124 |
-
{!hasAdmin && (
|
| 125 |
-
<div className="p-4 bg-slate-50 text-center border-t border-slate-100 pb-5">
|
| 126 |
-
<button onClick={handleSetup} disabled={setupLoading} className="text-xs text-slate-500 hover:text-emerald-600 font-bold transition-colors">
|
| 127 |
-
Run first-time platform setup
|
| 128 |
-
</button>
|
| 129 |
-
</div>
|
| 130 |
-
)}
|
| 131 |
-
</div>
|
| 132 |
-
</div>
|
| 133 |
-
);
|
| 134 |
-
};
|
| 135 |
-
|
| 136 |
-
export default Login;
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/pages/Login_fixed.jsx
CHANGED
|
@@ -141,7 +141,7 @@ const Login = () => {
|
|
| 141 |
</button>
|
| 142 |
</form>
|
| 143 |
|
| 144 |
-
{!hasAdmin && (
|
| 145 |
<div className="p-4 bg-amber-50 text-center border-t border-amber-100 pb-5">
|
| 146 |
<p className="text-xs text-amber-700 font-medium mb-2">لم يتم العثور على مسؤول للمنصة. يرجى إعداد حساب أولاً.</p>
|
| 147 |
<button
|
|
@@ -163,10 +163,10 @@ const Login = () => {
|
|
| 163 |
إعداد حساب المسؤول
|
| 164 |
</button>
|
| 165 |
</div>
|
| 166 |
-
)}
|
| 167 |
</div>
|
| 168 |
|
| 169 |
-
{showSetupModal && (
|
| 170 |
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
|
| 171 |
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden" dir="rtl">
|
| 172 |
<div className="flex items-center justify-between p-6 border-b border-slate-100 bg-slate-50">
|
|
@@ -278,7 +278,7 @@ const Login = () => {
|
|
| 278 |
</div>
|
| 279 |
</div>
|
| 280 |
</div>
|
| 281 |
-
)}
|
| 282 |
</div>
|
| 283 |
);
|
| 284 |
};
|
|
|
|
| 141 |
</button>
|
| 142 |
</form>
|
| 143 |
|
| 144 |
+
{/* {!hasAdmin && (
|
| 145 |
<div className="p-4 bg-amber-50 text-center border-t border-amber-100 pb-5">
|
| 146 |
<p className="text-xs text-amber-700 font-medium mb-2">لم يتم العثور على مسؤول للمنصة. يرجى إعداد حساب أولاً.</p>
|
| 147 |
<button
|
|
|
|
| 163 |
إعداد حساب المسؤول
|
| 164 |
</button>
|
| 165 |
</div>
|
| 166 |
+
)} */}
|
| 167 |
</div>
|
| 168 |
|
| 169 |
+
{/* {showSetupModal && (
|
| 170 |
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
|
| 171 |
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden" dir="rtl">
|
| 172 |
<div className="flex items-center justify-between p-6 border-b border-slate-100 bg-slate-50">
|
|
|
|
| 278 |
</div>
|
| 279 |
</div>
|
| 280 |
</div>
|
| 281 |
+
)} */}
|
| 282 |
</div>
|
| 283 |
);
|
| 284 |
};
|
frontend/src/pages/Login_new.jsx
DELETED
|
@@ -1,2 +0,0 @@
|
|
| 1 |
-
// test file
|
| 2 |
-
const x = 1;
|
|
|
|
|
|
|
|
|
frontend/src/utils/formatters.js
CHANGED
|
@@ -21,4 +21,12 @@ export const formatDateTime = (value) =>
|
|
| 21 |
minute: "2-digit",
|
| 22 |
});
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
export const formatNumber = (value) => new Intl.NumberFormat("en-US").format(Number(value || 0));
|
|
|
|
| 21 |
minute: "2-digit",
|
| 22 |
});
|
| 23 |
|
| 24 |
+
export const formatBytes = (bytes) => {
|
| 25 |
+
const value = Number(bytes || 0);
|
| 26 |
+
if (value < 1024) return `${value} B`;
|
| 27 |
+
if (value < 1024 ** 2) return `${(value / 1024).toFixed(1)} KB`;
|
| 28 |
+
if (value < 1024 ** 3) return `${(value / 1024 ** 2).toFixed(1)} MB`;
|
| 29 |
+
return `${(value / 1024 ** 3).toFixed(1)} GB`;
|
| 30 |
+
};
|
| 31 |
+
|
| 32 |
export const formatNumber = (value) => new Intl.NumberFormat("en-US").format(Number(value || 0));
|
frontend/src/utils/permissions.js
CHANGED
|
@@ -19,9 +19,9 @@ export const getPermissions = (user) => {
|
|
| 19 |
canDeleteCustomers: canManageBusiness,
|
| 20 |
canViewInventory: isTenantUser,
|
| 21 |
canManageInventory: canManageBusiness,
|
| 22 |
-
canViewSuppliers:
|
| 23 |
canManageSuppliers: canManageBusiness,
|
| 24 |
-
canViewReports:
|
| 25 |
canManageUsers: canManageBusiness,
|
| 26 |
canManageCompany: canManageBusiness,
|
| 27 |
canManageTenants: role === "super_admin",
|
|
|
|
| 19 |
canDeleteCustomers: canManageBusiness,
|
| 20 |
canViewInventory: isTenantUser,
|
| 21 |
canManageInventory: canManageBusiness,
|
| 22 |
+
canViewSuppliers: isTenantUser,
|
| 23 |
canManageSuppliers: canManageBusiness,
|
| 24 |
+
canViewReports: isTenantUser,
|
| 25 |
canManageUsers: canManageBusiness,
|
| 26 |
canManageCompany: canManageBusiness,
|
| 27 |
canManageTenants: role === "super_admin",
|