2026-05-26 09:18:48 +08:00
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 ]
)
2026-06-03 14:15:55 +08:00
const stockThreshold = parseInt ( process . env . STOCK _WARN _THRESHOLD ) || 10
const lowStockResult = await query (
'SELECT COUNT(*) as lowStockCount FROM goods WHERE stock < ? AND status != 0' ,
[ stockThreshold ]
)
2026-05-26 09:18:48 +08:00
ctx . body = {
code : 200 ,
data : {
sales : orderResult [ 0 ] . totalSales ,
orders : orderResult [ 0 ] . orderCount ,
2026-06-03 14:15:55 +08:00
customers : customerResult [ 0 ] . customerCount ,
lowStockCount : lowStockResult [ 0 ] . lowStockCount
2026-05-26 09:18:48 +08:00
}
}
}
module . exports = {
getTodayStats
}