Files
2026-06-04 11:53:21 +08:00

38 lines
1.3 KiB
JavaScript

const { query } = require('../config/database')
async function getTodayStats(ctx) {
const today = new Date()
const todayStart = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')} 00:00:00`
const todayEnd = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')} 23:59:59`
const orderResult = await query(
'SELECT COUNT(*) as orderCount, COALESCE(SUM(total_price), 0) as totalSales FROM orders WHERE created_at >= ? AND created_at <= ? AND status IN ("paid", "completed")',
[todayStart, todayEnd]
)
const customerResult = await query(
'SELECT COUNT(DISTINCT user_id) as customerCount FROM orders WHERE created_at >= ? AND created_at <= ?',
[todayStart, todayEnd]
)
const stockThreshold = parseInt(process.env.STOCK_WARN_THRESHOLD) || 10
const lowStockResult = await query(
'SELECT COUNT(*) as lowStockCount FROM goods WHERE stock < ? AND status = 1',
[stockThreshold]
)
ctx.body = {
code: 200,
data: {
sales: orderResult[0].totalSales,
orders: orderResult[0].orderCount,
customers: customerResult[0].customerCount,
lowStockCount: lowStockResult[0].lowStockCount
}
}
}
module.exports = {
getTodayStats
}