JewelryMall/server/src/controllers/stockAlert.ts
2026-03-19 19:33:13 +08:00

32 lines
937 B
TypeScript

import { Request, Response } from 'express'
import pool from '../utils/db'
import { RowDataPacket } from 'mysql2'
/**
* Filter products where stock < 20, sorted by stock ascending.
* Pure logic extracted for testability.
*/
export function filterStockAlerts(
products: { id: number; name: string; style_no: string; stock: number }[]
): typeof products {
return products
.filter((p) => p.stock < 20)
.sort((a, b) => a.stock - b.stock)
}
// GET /api/admin/stock-alerts
export async function getStockAlerts(_req: Request, res: Response): Promise<void> {
try {
const [rows] = await pool.execute<RowDataPacket[]>(
`SELECT id, name, style_no, stock
FROM products
WHERE stock < 20
ORDER BY stock ASC`
)
res.json({ code: 0, data: rows })
} catch (err) {
console.error('getStockAlerts error:', err)
res.status(500).json({ code: 500, message: '获取库存预警失败' })
}
}