Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 2x 2x 2x 2x 2x | const Order = require('../orders/order.model')
const Book = require('../books/book.model')
const { StatusCodes } = require('http-status-codes') // Added StatusCodes
/**
* @desc Get admin statistics
* @route GET /api/v1/admin/stats
* @access Private (Admin)
*/
const getAdminStats = async (req, res) => {
try {
// 1. Total number of orders
const totalOrders = await Order.countDocuments()
// 2. Total sales (sum of all totalPrice from orders)
const totalSalesData = await Order.aggregate([
{
$group: {
_id: null,
totalSales: { $sum: '$totalPrice' },
},
},
])
// 4. Trending books statistics:
const trendingBooksCount = await Book.aggregate([
{ $match: { trending: true } }, // Match only trending books
{ $count: 'trendingBooksCount' }, // Return the count of trending books
])
// If you want just the count as a number, you can extract it like this:
const trendingBooks =
trendingBooksCount.length > 0
? trendingBooksCount[0].trendingBooksCount
: 0
// 5. Total number of books
const totalBooks = await Book.countDocuments()
// 6. Monthly sales (group by month and sum total sales for each month)
const monthlySales = await Order.aggregate([
{
$group: {
_id: { $dateToString: { format: '%Y-%m', date: '$createdAt' } }, // Group by year and month
totalSales: { $sum: '$totalPrice' }, // Sum totalPrice for each month
totalOrders: { $sum: 1 }, // Count total orders for each month
},
},
{ $sort: { _id: 1 } },
])
// Result summary
res.status(StatusCodes.OK).json({
totalOrders,
totalSales: totalSalesData[0]?.totalSales || 0,
trendingBooks,
totalBooks,
monthlySales,
})
} catch (error) {
console.error('Error fetching admin stats:', error)
res
.status(StatusCodes.INTERNAL_SERVER_ERROR)
.json({ message: 'Failed to fetch admin stats' })
}
}
module.exports = {
getAdminStats,
}
|