-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.js
More file actions
57 lines (47 loc) · 1.63 KB
/
analytics.js
File metadata and controls
57 lines (47 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const express = require("express");
const router = express.Router(); // This line MUST be here
const Product = require("../models/Product");
const Order = require("../models/Order");
const auth = require("../middleware/authMiddleware");
// @desc Get analytics for logged-in artist
// @route GET /api/analytics
// @access Private (Artist only)
router.get("/", auth, async (req, res) => {
try {
if (req.user.role !== "artist") {
return res.status(403).json({ message: "Access denied. Artists only." });
}
const artistId = req.user.id;
// Total products uploaded by artist
const totalProducts = await Product.countDocuments({ artistId });
// Find all orders that contain at least one of the artist's products
const orders = await Order.find({ "items.artistId": artistId });
let ongoingOrders = 0;
let completedOrders = 0;
let totalEarnings = 0;
orders.forEach((order) => {
// Check the status of the entire order
if (order.status === "completed") {
completedOrders++;
} else if (order.status === "ongoing") {
ongoingOrders++;
}
// Calculate earnings from this order
order.items.forEach((item) => {
if (item.artistId.toString() === artistId.toString()) {
totalEarnings += item.priceAtPurchase * item.quantity;
}
});
});
res.json({
totalProducts,
ongoingOrders,
completedOrders,
totalEarnings,
});
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server error" });
}
});
module.exports = router;