32 lines
1.0 KiB
TypeScript
32 lines
1.0 KiB
TypeScript
import { Request, Response } from 'express'
|
|
import pool from '../utils/db'
|
|
import { RowDataPacket } from 'mysql2'
|
|
|
|
/**
|
|
* Filter products where stock/totalStock < 0.1, sorted by stock ascending.
|
|
* Pure logic extracted for testability.
|
|
*/
|
|
export function filterStockAlerts(
|
|
products: { id: number; name: string; style_no: string; stock: number; total_stock: number }[]
|
|
): typeof products {
|
|
return products
|
|
.filter((p) => p.total_stock > 0 && p.stock / p.total_stock < 0.1)
|
|
.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, total_stock
|
|
FROM products
|
|
WHERE total_stock > 0 AND stock / total_stock < 0.1
|
|
ORDER BY stock ASC`
|
|
)
|
|
res.json({ code: 0, data: rows })
|
|
} catch (err) {
|
|
console.error('getStockAlerts error:', err)
|
|
res.status(500).json({ code: 500, message: '获取库存预警失败' })
|
|
}
|
|
}
|