来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
180 lines
6.1 KiB
JavaScript
180 lines
6.1 KiB
JavaScript
/**
|
|
* Fix purchase cost_details inflated by summing duplicate inspections.
|
|
* Correct amount = SUM(latest inspection actual_qty * purchase_price per SKU).
|
|
*
|
|
* Usage:
|
|
* node --env-file=.env scripts/prod-fix-inflated-purchase-costs.cjs
|
|
* node --env-file=.env scripts/prod-fix-inflated-purchase-costs.cjs --execute
|
|
*/
|
|
const { Pool } = require('pg');
|
|
|
|
const execute = process.argv.includes('--execute');
|
|
|
|
async function main() {
|
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
|
|
const rows = await pool.query(`
|
|
WITH latest AS (
|
|
SELECT order_code, sku_code, amt FROM (
|
|
SELECT DISTINCT ON (order_code, sku_code)
|
|
order_code, sku_code,
|
|
ROUND((COALESCE(actual_qty,0) * COALESCE(purchase_price,0))::numeric, 2) AS amt
|
|
FROM inspections
|
|
WHERE order_code IS NOT NULL
|
|
AND sku_code IS NOT NULL AND TRIM(sku_code) <> ''
|
|
AND COALESCE(actual_qty,0) > 0
|
|
AND COALESCE(purchase_price,0) > 0
|
|
ORDER BY order_code, sku_code, inspection_time DESC NULLS LAST, created_at DESC, id DESC
|
|
) t
|
|
),
|
|
correct AS (
|
|
SELECT order_code, ROUND(SUM(amt)::numeric, 2) AS correct_amt, COUNT(*) AS sku_count
|
|
FROM latest
|
|
GROUP BY order_code
|
|
),
|
|
ledger AS (
|
|
SELECT order_code,
|
|
COUNT(*) AS cost_rows,
|
|
ROUND(SUM(COALESCE(allocated_amount, amount, 0))::numeric, 2) AS ledger_amt,
|
|
MIN(id::text) AS sample_id
|
|
FROM cost_details
|
|
WHERE cost_type = 'purchase'
|
|
GROUP BY order_code
|
|
)
|
|
SELECT l.order_code, o.cycle_code, o.total_amount,
|
|
l.cost_rows, l.ledger_amt, c.correct_amt, c.sku_count,
|
|
ROUND((l.ledger_amt - c.correct_amt)::numeric, 2) AS over_amt
|
|
FROM ledger l
|
|
JOIN correct c ON c.order_code = l.order_code
|
|
LEFT JOIN orders o ON o.order_code = l.order_code
|
|
WHERE l.ledger_amt > c.correct_amt + 0.01
|
|
ORDER BY (l.ledger_amt - c.correct_amt) DESC
|
|
`);
|
|
|
|
const overTotal = rows.rows.reduce((s, r) => s + Number(r.over_amt), 0);
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
execute,
|
|
inflatedOrders: rows.rows.length,
|
|
overTotal,
|
|
sample: rows.rows.slice(0, 15),
|
|
},
|
|
null,
|
|
2
|
|
)
|
|
);
|
|
|
|
if (!execute) {
|
|
console.log('\nDry-run only. Re-run with --execute to rewrite cost_details.');
|
|
await pool.end();
|
|
return;
|
|
}
|
|
|
|
const client = await pool.connect();
|
|
let updated = 0;
|
|
try {
|
|
await client.query('BEGIN');
|
|
for (const row of rows.rows) {
|
|
const orderCode = row.order_code;
|
|
const correctAmt = Number(row.correct_amt);
|
|
|
|
// Per-SKU amounts for proper multi-row ledger if possible
|
|
const perSku = await client.query(
|
|
`SELECT sku_code, amt FROM (
|
|
SELECT DISTINCT ON (sku_code)
|
|
sku_code,
|
|
ROUND((COALESCE(actual_qty,0)*COALESCE(purchase_price,0))::numeric,2) AS amt
|
|
FROM inspections
|
|
WHERE order_code = $1
|
|
AND sku_code IS NOT NULL AND TRIM(sku_code) <> ''
|
|
AND COALESCE(actual_qty,0) > 0
|
|
AND COALESCE(purchase_price,0) > 0
|
|
ORDER BY sku_code, inspection_time DESC NULLS LAST, created_at DESC, id DESC
|
|
) t`,
|
|
[orderCode]
|
|
);
|
|
|
|
const existing = await client.query(
|
|
`SELECT id, sku_code, amount FROM cost_details
|
|
WHERE order_code = $1 AND cost_type = 'purchase'
|
|
ORDER BY created_at ASC`,
|
|
[orderCode]
|
|
);
|
|
|
|
if (existing.rows.length === 1) {
|
|
// Legacy one-row: store order total on that row
|
|
await client.query(`UPDATE cost_details SET amount = $2, status = 20 WHERE id = $1`, [
|
|
existing.rows[0].id,
|
|
correctAmt,
|
|
]);
|
|
updated += 1;
|
|
} else {
|
|
// Multi-row: update matching sku or set first row to total after deleting extras
|
|
// Prefer rewrite: delete and re-insert per sku keeping cycle/branch from first row
|
|
const meta = await client.query(
|
|
`SELECT cycle_code, branch_code FROM orders WHERE order_code = $1`,
|
|
[orderCode]
|
|
);
|
|
const cycle = meta.rows[0]?.cycle_code || existing.rows[0]?.cycle_code;
|
|
const branch = meta.rows[0]?.branch_code || null;
|
|
await client.query(
|
|
`DELETE FROM cost_details WHERE order_code = $1 AND cost_type = 'purchase'`,
|
|
[orderCode]
|
|
);
|
|
for (const sku of perSku.rows) {
|
|
if (Number(sku.amt) <= 0) continue;
|
|
await client.query(
|
|
`INSERT INTO cost_details (
|
|
cycle_code, order_code, cost_type, cost_subtype, amount, status,
|
|
branch_code, sku_code, reference_type, reference_id
|
|
) VALUES ($1,$2,'purchase','inspection_inbound',$3,20,$4,$5,'inspection_rebuild', $2)`,
|
|
[cycle, orderCode, Number(sku.amt), branch, sku.sku_code]
|
|
);
|
|
}
|
|
updated += 1;
|
|
}
|
|
}
|
|
await client.query('COMMIT');
|
|
console.log(`Updated ${updated} orders`);
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw e;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
|
|
// Re-check finance overview numbers
|
|
const weekStart = new Date();
|
|
weekStart.setDate(weekStart.getDate() - 7);
|
|
const weekStartIso = weekStart.toISOString();
|
|
const check = await pool.query(
|
|
`WITH week_orders AS (
|
|
SELECT order_code, total_amount FROM orders
|
|
WHERE order_status >= 90 AND updated_at >= $1
|
|
)
|
|
SELECT
|
|
ROUND(SUM(wo.total_amount)::numeric,2) AS revenue,
|
|
ROUND(COALESCE(SUM(CASE WHEN LOWER(COALESCE(cd.cost_type,''))='purchase_applied' THEN 0
|
|
ELSE COALESCE(cd.allocated_amount, cd.amount, 0) END),0)::numeric,2) AS cost
|
|
FROM week_orders wo
|
|
LEFT JOIN cost_details cd ON cd.order_code = wo.order_code`,
|
|
[weekStartIso]
|
|
);
|
|
const rev = Number(check.rows[0].revenue);
|
|
const cost = Number(check.rows[0].cost);
|
|
console.log({
|
|
weekRevenue: rev,
|
|
weekCost: cost,
|
|
weekGross: Math.round((rev - cost) * 100) / 100,
|
|
marginPct: rev > 0 ? Math.round(((rev - cost) / rev) * 1000) / 10 : 0,
|
|
});
|
|
|
|
await pool.end();
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|