Files
SupplierSystem/scripts/prod-diagnose-margin.sh
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

134 lines
5.0 KiB
Bash

#!/bin/bash
set -eu
cd /opt/ai-fresh-delivery/server
node <<'NODE'
require('./dist/env.js').loadEnv();
const { pool } = require('./dist/db.js').pool ? { pool: require('./dist/db.js').pool } : require('./dist/db.js');
function safe(n) {
const v = Number(n);
return Number.isFinite(v) ? v : 0;
}
(async () => {
const cycle = process.argv[1] || new Date().toISOString().slice(0, 7).replace('-', '');
console.log('cycle_code:', cycle);
const orders = await pool.query(`SELECT order_code FROM orders WHERE cycle_code = $1`, [cycle]);
const orderCodes = orders.rows.map((r) => r.order_code);
console.log('orders_in_cycle:', orderCodes.length);
const costByType = await pool.query(
`SELECT cost_type, COUNT(*)::int AS cnt,
SUM(COALESCE(allocated_amount, amount, 0))::numeric AS total
FROM cost_details WHERE cycle_code = $1
GROUP BY cost_type ORDER BY total DESC NULLS LAST`,
[cycle]
);
console.log('\n=== cost_details by type ===');
for (const r of costByType.rows) {
console.log(`${r.cost_type}: count=${r.cnt} total=${Number(r.total).toFixed(2)}`);
}
const purchaseBySku = await pool.query(
`SELECT sku_code, SUM(COALESCE(allocated_amount, amount, 0))::numeric AS purchase
FROM cost_details
WHERE cycle_code = $1 AND LOWER(cost_type) = 'purchase' AND sku_code IS NOT NULL
GROUP BY sku_code ORDER BY purchase DESC LIMIT 15`,
[cycle]
);
console.log('\n=== top purchase cost by sku ===');
for (const r of purchaseBySku.rows) {
console.log(`${r.sku_code}: purchase=${Number(r.purchase).toFixed(2)}`);
}
if (!orderCodes.length) {
await pool.end();
return;
}
const revenueBySku = await pool.query(
`SELECT oi.sku_code,
SUM(COALESCE(oi.quantity,0))::numeric AS qty,
SUM(COALESCE(oi.amount, oi.price * oi.quantity, 0))::numeric AS revenue
FROM order_items oi
WHERE oi.order_code = ANY($1::text[])
GROUP BY oi.sku_code
HAVING SUM(COALESCE(oi.quantity,0)) > 0
ORDER BY revenue ASC NULLS FIRST
LIMIT 20`,
[orderCodes]
);
console.log('\n=== lowest revenue skus (margin risk) ===');
for (const r of revenueBySku.rows) {
const purchase = purchaseBySku.rows.find((p) => p.sku_code === r.sku_code);
const pc = purchase ? Number(purchase.purchase) : 0;
const rev = Number(r.revenue);
const margin = rev > 0 ? ((rev - pc) / rev) * 100 : null;
console.log(
`${r.sku_code}: qty=${Number(r.qty)} revenue=${rev.toFixed(2)} purchase=${pc.toFixed(2)} margin=${margin == null ? 'n/a' : margin.toFixed(1) + '%'}`
);
}
const lossAll = await pool.query(
`SELECT sku_code, SUM(COALESCE(loss_qty,0))::numeric AS loss_qty
FROM inspections WHERE sku_code IS NOT NULL
GROUP BY sku_code ORDER BY loss_qty DESC LIMIT 10`
);
console.log('\n=== top loss_qty (ALL TIME, not cycle filtered!) ===');
for (const r of lossAll.rows) {
console.log(`${r.sku_code}: loss_qty=${Number(r.loss_qty)}`);
}
const outliers = ['SKU98275980670', 'SKU98266204815'];
const items = await pool.query(
`SELECT oi.order_code, oi.sku_code, oi.item_name, oi.quantity, oi.price, oi.amount
FROM order_items oi
JOIN orders o ON o.order_code = oi.order_code
WHERE o.cycle_code = $1 AND oi.sku_code = ANY($2::text[])`,
[cycle, outliers]
);
console.log('\n=== outlier order_items ===');
console.log(JSON.stringify(items.rows, null, 2));
const costs = await pool.query(
`SELECT sku_code, cost_type, amount, allocated_amount, order_code
FROM cost_details WHERE cycle_code = $1 AND sku_code = ANY($2::text[])`,
[cycle, outliers]
);
console.log('\n=== outlier cost_details ===');
console.log(JSON.stringify(costs.rows, null, 2));
const totalRev = await pool.query(
`SELECT SUM(COALESCE(oi.amount, oi.price * oi.quantity, 0))::numeric AS revenue
FROM order_items oi JOIN orders o ON o.order_code = oi.order_code WHERE o.cycle_code = $1`,
[cycle]
);
const totalPurchase = await pool.query(
`SELECT SUM(COALESCE(allocated_amount, amount, 0))::numeric AS purchase
FROM cost_details WHERE cycle_code = $1 AND LOWER(cost_type) = 'purchase'`,
[cycle]
);
const rev = Number(totalRev.rows[0]?.revenue || 0);
const pur = Number(totalPurchase.rows[0]?.purchase || 0);
const weightedMargin = rev > 0 ? ((rev - pur) / rev) * 100 : 0;
console.log('\n=== cycle totals ===');
console.log(`revenue=${rev.toFixed(2)} purchase=${pur.toFixed(2)} weighted_margin=${weightedMargin.toFixed(1)}%`);
const mpOrders = await pool.query(
`SELECT o.order_code, o.total_amount,
(SELECT SUM(COALESCE(oi.amount, oi.price*oi.quantity,0)) FROM order_items oi WHERE oi.order_code=o.order_code) AS item_rev
FROM orders o WHERE o.cycle_code = $1 AND o.order_code LIKE 'ORD_MP_%'`,
[cycle]
);
console.log('\n=== ORD_MP orders in cycle ===');
console.log(JSON.stringify(mpOrders.rows, null, 2));
await pool.end();
})().catch(async (e) => {
console.error('FAIL', e.message);
await pool.end();
process.exit(1);
});
NODE