Skip to content
Open

Mav #31

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 14 additions & 16 deletions backend/Routes/AdminRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,40 +205,38 @@ router.get('/total-inventory', async (req, res) => {
router.get('/revenue', async (req, res) => {
try {
// Calculate revenue from product sales
const productRevenue = await Product.aggregate([
const revenue = await User.aggregate([
{
$project: {
totalRevenue: { $multiply: ["$cost", "$unitsRented"] }
$unwind: "$Rented" // Unwind the Rented array
},
{
$match: {
"Rented.Live": true // Match documents where Live status is true
}
},
{
$group: {
_id: null,
revenue: { $sum: "$totalRevenue" }
$project: {
totalRevenue: {
$multiply: ["$Rented.Quantity", "$Rented.Price", "$Rented.RentDuration"]
}
}
}
]);

// Calculate total loan
const totalLoan = await User.aggregate([
},
{
$group: {
_id: null,
totalLoan: { $sum: "$Rented.Loan" }
revenue: { $sum: "$totalRevenue" }
}
}
]);

// Calculate total revenue
const revenue = productRevenue[0].revenue + totalLoan[0].totalLoan;

res.json({ revenue: revenue });
res.json({ revenue: revenue.length > 0 ? revenue[0].revenue : 0 });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server Error" });
}
});


router.get('/total-customers', async (req, res) => {
try {
const totalCustomers = await User.countDocuments();
Expand Down
81 changes: 81 additions & 0 deletions backend/Routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -615,5 +615,86 @@ router.get('/notifications/:userId', async (req, res) => {
}
});

router.get('/time-due/:userId/:orderId', async (req, res) => {
const userId = req.params.userId;
const orderId = req.params.orderId;

try {
// Find the user by ID
const user = await User.findById(userId);

if (!user) {
return res.status(404).json({ message: "User not found" });
}

// Find the order by ID in the user's rented array
const order = user.Rented.find(order => order._id.toString() === orderId);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Consider using a more efficient method to find orders.

Using find on an array can be inefficient for large datasets. Consider indexing or a more direct query method if performance is a concern.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment correct?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment helpful?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the comment type correct?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the comment area correct?


if (!order) {
return res.status(404).json({ message: "Order not found" });
}

// Check if live status is true
if (order.Live) {
// Calculate time due in months
const rentDuration = order.RentDuration; // Rent duration in months
const startDate = new Date(order.Date); // Date the product was rented
const currentDate = new Date(); // Current date
const monthsDiff = (currentDate.getFullYear() - startDate.getFullYear()) * 12 + (currentDate.getMonth() - startDate.getMonth());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (edge_case_not_handled): Potential issue with month difference calculation.

This calculation might not account for partial months or correct boundary conditions around year changes. Consider edge cases or a library to handle date differences.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment correct?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment helpful?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the comment type correct?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the comment area correct?

const timeDue = rentDuration - monthsDiff;

res.json({ timeDue: timeDue });
} else {
res.json({ message: "Order is not active" });
}
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server Error" });
}
});

router.get('/total-loan/:userId/:orderId', async (req, res) => {
const userId = req.params.userId;
const orderId = req.params.orderId;

try {
// Find the user by ID
const user = await User.findById(userId);

if (!user) {
return res.status(404).json({ message: "User not found" });
}

// Find the order by ID in the user's rented array
const order = user.Rented.find(order => order._id.toString() === orderId);

if (!order) {
return res.status(404).json({ message: "Order not found" });
}

// Calculate total loan
let totalLoan = 0;

if (order.Live) {
const rentDuration = order.RentDuration; // Rent duration in months
const startDate = new Date(order.Date); // Date the product was rented
const currentDate = new Date(); // Current date
const monthsDiff = (currentDate.getFullYear() - startDate.getFullYear()) * 12 + (currentDate.getMonth() - startDate.getMonth());
const timeDue = rentDuration - monthsDiff;

// If time due is negative, calculate total loan
if (timeDue < 0) {
totalLoan = Math.abs(timeDue) * order.Quantity * order.Price;
}
}

res.json({ totalLoan: totalLoan });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server Error" });
}
});


module.exports = router;

45 changes: 36 additions & 9 deletions backend/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,19 +106,46 @@ const UserSchema = new mongoose.Schema({

UserSchema.methods.calculateDueTime = function() {
this.Rented.forEach(item => {
const rentDuration = item.RentDuration; // Rent duration in months
const startDate = item.Date; // Date the product was rented
const currentDate = new Date(); // Current date

// Calculate due time in months
const dueTime = rentDuration - Math.floor((currentDate - startDate) / (30 * 24 * 60 * 60 * 1000));

// Update TimeDue field with the calculated due time
item.TimeDue = dueTime;
if (item.Live) {
const rentDuration = item.RentDuration; // Rent duration in months
const startDate = item.Date; // Date the product was rented
const currentDate = new Date(); // Current date

// Calculate due time in months
const dueTime = rentDuration - Math.floor((currentDate - startDate) / (30 * 24 * 60 * 60 * 1000));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Inconsistent date handling might lead to errors.

Using a fixed 30-day month might introduce inaccuracies in calculations, especially over longer periods or different month lengths. Consider using a date library for more accurate calculations.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment correct?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment helpful?


// Update TimeDue field with the calculated due time
item.TimeDue = dueTime;
}
});
// Save the changes to the user document
return this.save();
};

UserSchema.methods.calculateLoan = function() {
this.Rented.forEach(item => {
if (item.Live) {
const rentDuration = item.RentDuration; // Rent duration in months
const startDate = item.Date; // Date the product was rented
const currentDate = new Date(); // Current date

// Calculate due time in months
const dueTime = rentDuration - Math.floor((currentDate - startDate) / (30 * 24 * 60 * 60 * 1000));

// If due time is negative, calculate loan
if (dueTime < 0) {
item.Loan = Math.abs(dueTime) * item.Quantity * item.Price;
} else {
item.Loan = 0; // If due time is not negative, set loan to 0
}
} else {
item.Loan = 0; // If status is not live, set loan to 0
}
});
// Save the changes to the user document
return this.save();
};


const User = mongoose.model("User", UserSchema);
module.exports = User;