Files
SupplierSystem/docs/audit/scripts/20260915-inventory-audit/diff-report.mjs
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

107 lines
7.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 只读:库存台账(inventory.quantity) 与 流水(inventory_logs) 的逐 SKU 差异 + 归因
import { createRequire } from 'node:module';
import { writeFileSync } from 'node:fs';
const require = createRequire('/home/ubuntu/harness/ai-fresh-delivery/server/index.js');
const { Pool } = require('pg');
const pool = new Pool({ connectionString: 'postgresql://hermes:Hermes_2026_DB@1.13.62.2:20538/ai_fresh_delivery', connectionTimeoutMillis: 20000, max: 2 });
const q = async (s, p) => (await pool.query(s, p)).rows;
// 会影响「累计入库量 quantity」的流水类型(按写入代码语义)
const QTY_UP = ['inspection_in', 'stock_in', 'processing_return'];
const QTY_DOWN = ['stock_in_void', 'stock_in_adjust'];
for (const T of ['tenant_br002', 'tenant_br003', 'tenant_br004']) {
const rows = await q(`
WITH inv AS (
SELECT sku_code, COUNT(*)::int batches, SUM(quantity)::numeric inv_qty,
ROUND(SUM(COALESCE(cost_price,0)*quantity)::numeric,2) inv_value,
SUM(available_qty)::numeric avail
FROM ${T}.inventory GROUP BY 1),
lg AS (
SELECT sku_code,
SUM(CASE WHEN operation_type = ANY($1) THEN quantity
WHEN operation_type = ANY($2) THEN -quantity ELSE 0 END)::numeric log_in,
COUNT(*)::int log_rows,
COUNT(*) FILTER (WHERE operation_type = ANY($1))::int in_rows,
MAX(created_at)::date last_log
FROM ${T}.inventory_logs GROUP BY 1),
orphan AS (
SELECT l.sku_code, SUM(CASE WHEN l.operation_type = ANY($1) THEN l.quantity ELSE 0 END)::numeric orphan_in,
COUNT(*)::int orphan_rows
FROM ${T}.inventory_logs l
WHERE NOT EXISTS (SELECT 1 FROM ${T}.inventory i WHERE i.batch_no = l.batch_no)
GROUP BY 1),
no_log AS (
SELECT i.sku_code, SUM(i.quantity)::numeric qty_without_inbound
FROM ${T}.inventory i
WHERE i.quantity > 0 AND NOT EXISTS (
SELECT 1 FROM ${T}.inventory_logs l WHERE l.batch_no = i.batch_no AND l.operation_type = ANY($1))
GROUP BY 1)
SELECT COALESCE(i.sku_code, g.sku_code) sku_code,
COALESCE(i.batches,0)::int batches,
ROUND(COALESCE(i.inv_qty,0)::numeric,2) inv_qty,
ROUND(COALESCE(g.log_in,0)::numeric,2) log_in,
ROUND((COALESCE(i.inv_qty,0) - COALESCE(g.log_in,0))::numeric,2) diff,
COALESCE(i.inv_value,0) inv_value,
ROUND(COALESCE(i.avail,0)::numeric,2) avail,
COALESCE(g.log_rows,0)::int log_rows,
COALESCE(o.orphan_rows,0)::int orphan_log_rows,
ROUND(COALESCE(o.orphan_in,0)::numeric,2) orphan_inbound_qty,
ROUND(COALESCE(n.qty_without_inbound,0)::numeric,2) qty_without_inbound_log,
g.last_log
FROM inv i FULL OUTER JOIN lg g ON g.sku_code = i.sku_code
LEFT JOIN orphan o ON o.sku_code = COALESCE(i.sku_code, g.sku_code)
LEFT JOIN no_log n ON n.sku_code = COALESCE(i.sku_code, g.sku_code)
WHERE ABS(COALESCE(i.inv_qty,0) - COALESCE(g.log_in,0)) > 0.01
ORDER BY ABS(COALESCE(i.inv_qty,0) - COALESCE(g.log_in,0)) DESC`,
[QTY_UP, QTY_DOWN]);
const header = 'sku_code,batches,inv_qty,log_in,diff,inv_value,avail,log_rows,orphan_log_rows,orphan_inbound_qty,qty_without_inbound_log,last_log';
const csv = [header, ...rows.map(r => [r.sku_code, r.batches, r.inv_qty, r.log_in, r.diff, r.inv_value, r.avail, r.log_rows, r.orphan_log_rows, r.orphan_inbound_qty, r.qty_without_inbound_log, r.last_log ? String(r.last_log).slice(0,10) : ''].join(','))].join('\n');
writeFileSync(`/home/ubuntu/harness/ai-fresh-delivery/tmp/inv-audit/diff-${T}.csv`, csv);
const absSum = rows.reduce((s, r) => s + Math.abs(Number(r.diff)), 0);
console.log(`\n===== ${T}: 差异 SKU ${rows.length} 个,绝对差合计 ${absSum.toFixed(2)} =====`);
console.log(' 归因分类:');
const cls = (r) => {
const d = Number(r.diff);
if (d < 0 && Number(r.orphan_inbound_qty) > 0 && Math.abs(d - (-Number(r.orphan_inbound_qty))) < 0.01)
return 'A. 批次行已删(流水保留)—— 差额=孤立批次入库量';
if (d < 0 && Number(r.orphan_inbound_qty) > 0) return 'B. 批次行部分被删 + 其它原因';
if (d < 0) return 'C. 台账少、流水多(其它)';
if (d > 0 && Number(r.qty_without_inbound_log) > 0 && Math.abs(d - Number(r.qty_without_inbound_log)) < 0.01)
return 'D. 有数量但无对应入库流水 —— 差额=无流水批次数量';
if (d > 0) return 'E. 台账多、流水少(其它)';
return 'F. 其它';
};
const buckets = new Map();
for (const r of rows) { const k = cls(r); const b = buckets.get(k) || { n: 0, diff: 0 }; b.n += 1; b.diff += Math.abs(Number(r.diff)); buckets.set(k, b); }
for (const [k, v] of [...buckets].sort((a, b) => b[1].diff - a[1].diff)) console.log(` ${k}: ${v.n} 个 SKU,绝对差 ${v.diff.toFixed(2)}`);
console.log(' Top5:');
for (const r of rows.slice(0, 5)) console.log(` ${r.sku_code} 台账 ${r.inv_qty} / 流水 ${r.log_in} = ${r.diff}(批次${r.batches} 孤立流水${r.orphan_log_rows}条=${r.orphan_inbound_qty} 无流水批次量=${r.qty_without_inbound_log})`);
}
console.log('\n\n===== 幽灵预留(status=10 但订单已送达/已结案)=====');
const ghosts = [];
for (const T of ['tenant_br002', 'tenant_br003', 'tenant_br004']) {
const rows = await q(`SELECT r.order_code, r.sku_code, r.qty::numeric qty, r.created_at::date created,
o.order_status, o.delivery_date::date delivery, c.company_name,
(SELECT ROUND(SUM(available_qty)::numeric,2) FROM ${T}.inventory i WHERE i.sku_code = r.sku_code) avail,
(SELECT COUNT(*) FROM ${T}.inventory_logs l WHERE l.sku_code = r.sku_code AND l.related_order_code = r.order_code) logs
FROM ${T}.inventory_reservations r
LEFT JOIN ${T}.orders o ON o.order_code = r.order_code
LEFT JOIN ${T}.customers c ON c.customer_code = o.customer_code
WHERE r.status = 10
ORDER BY r.created_at`, []);
console.log(`\n--- ${T}:status=10 共 ${rows.length} 条`);
for (const r of rows) {
const tag = Number(r.order_status) >= 45 ? '⚠️ 订单已送达/结案' : '(订单未送达,属正常占用)';
console.log(` ${r.order_code} ${r.sku_code} 预留 ${r.qty} 下单日 ${String(r.created).slice(0,10)} 订单状态 ${r.order_status} 该SKU可用 ${r.avail} 该单该SKU流水 ${r.logs} 条 ${tag}`);
ghosts.push({ tenant: T, ...r, created: String(r.created).slice(0, 10), delivery: r.delivery ? String(r.delivery).slice(0, 10) : '' });
}
}
const gh = ghosts.filter(g => Number(g.order_status) >= 45);
writeFileSync('/home/ubuntu/harness/ai-fresh-delivery/tmp/inv-audit/ghost-reservations.csv',
['tenant,order_code,sku_code,qty,order_status,delivery_date,created_at,customer,sku_available,order_logs',
...gh.map(g => [g.tenant, g.order_code, g.sku_code, g.qty, g.order_status, g.delivery, g.created, (g.company_name || '').replace(/,/g, ' '), g.avail, g.logs].join(','))].join('\n'));
console.log(`\n幽灵预留合计(订单状态>=45 仍占用):${gh.length} 条,数量 ${gh.reduce((s, g) => s + Number(g.qty), 0).toFixed(2)}`);
await pool.end();