Files
SupplierSystem/server/scripts/fix-self-purchase-accumulated-actual.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

246 lines
11 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.
#!/usr/bin/env node
/**
* 存量修复:自采单「分批入库」时 purchase_orders.actual_qty 只留首批。
*
* 背景与口径见 docs/design/20260913-self-purchase-partial-inbound-qty.md
* 代码侧修复见 inspectionComplianceService.writeAccumulatedPurchaseActual(2026-09-13)。
* 本脚本把同一判定与口径一次性应用到历史数据:
* - 只处理自采(采购单无供应商):分批补收走的是自采链路;
* - 累计 = 该自采单下「全部已完成批次」之和(重验复用同一行覆盖,不会重复计数);
* - 只修「显示偏低」:累计 <= 现值直接跳过,绝不自动下调;
* - 归属判定:现值必须能确认是流程自己写的(实收为空 / 单据未入库 / 现值 == 此前批次合计
* / 现值 == 最后一批数量)才覆盖,其余视为人工改量,只报告不动;
* - 只写 actual_qty 与 total_amount(= 实收 × 成本价),不碰 purchase_status、不碰库存。
*
* 用法(在 server/ 下执行):
* 干跑(默认,只读): node --env-file=.env scripts/fix-self-purchase-accumulated-actual.mjs --since=2026-08-01
* 正式执行: node --env-file=.env scripts/fix-self-purchase-accumulated-actual.mjs --since=2026-08-01 --apply
* 参数:
* --apply 真正写库(事务提交);缺省为干跑
* --tenant=tenant_br002 只处理指定 schema(可重复);缺省自动发现 tenant_br*
* --since=YYYY-MM-DD 只处理该建单日之后的采购单;缺省不限
* --out=PATH 审计 JSON(含改前值,回滚依据)落盘路径
*/
import { Pool } from 'pg';
import { writeFileSync } from 'node:fs';
const args = process.argv.slice(2);
const apply = args.includes('--apply');
const tenantsArg = args.filter((a) => a.startsWith('--tenant=')).map((a) => a.split('=')[1]);
const since = (args.find((a) => a.startsWith('--since=')) || '').split('=')[1] || null;
const outPath =
(args.find((a) => a.startsWith('--out=')) || '').split('=')[1] ||
`/tmp/fix-self-purchase-actual-${apply ? 'applied' : 'dryrun'}-${Date.now()}.json`;
const EPS = 0.011;
const round2 = (n) => Math.round(n * 100) / 100;
const round3 = (n) => Math.round(n * 1000) / 1000;
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
/** 自采口径:无供应商 / INTERNAL / UNASSIGNED 视为同一口径(对齐 sqlSelfPurchaseSupplierEquiv) */
function selfPurchaseSupplierEquiv(left, right) {
return `(
(
(NULLIF(TRIM(COALESCE(${left}, '')), '') IS NULL
OR UPPER(TRIM(${left})) IN ('INTERNAL', 'UNASSIGNED'))
AND (NULLIF(TRIM(COALESCE(${right}, '')), '') IS NULL
OR UPPER(TRIM(${right})) IN ('INTERNAL', 'UNASSIGNED'))
)
OR COALESCE(TRIM(${left}), '') = COALESCE(TRIM(${right}), '')
)`;
}
async function discoverTenants(client) {
if (tenantsArg.length) return tenantsArg;
const r = await client.query(
`SELECT table_schema AS s
FROM information_schema.tables
WHERE table_name = 'purchase_orders' AND table_schema LIKE 'tenant_%'
ORDER BY 1`
);
return r.rows.map((x) => x.s);
}
function scanSql(schema) {
const supplierEquiv = selfPurchaseSupplierEquiv('i.supplier_code', 'po.supplier_code');
const sinceClause = since ? `AND (po.created_at AT TIME ZONE 'Asia/Shanghai')::date >= DATE '${since}'` : '';
return `
SELECT po.purchase_code,
po.order_code,
po.sku_code,
k.sku_name,
po.actual_qty,
po.actual_price,
po.total_amount,
po.purchase_status,
(po.created_at AT TIME ZONE 'Asia/Shanghai')::date AS created_day,
COALESCE(agg.q, 0) AS insp_qty,
COALESCE(agg.n, 0) AS batch_cnt,
COALESCE(agg.fu, 0) AS follow_up_cnt,
COALESCE(agg.q_prior, 0) AS prior_qty,
agg.q_last AS last_qty
FROM ${schema}.purchase_orders po
LEFT JOIN ${schema}.skus k ON k.sku_code = po.sku_code
LEFT JOIN LATERAL (
SELECT sum(x.actual_qty) AS q,
count(*) AS n,
count(*) FILTER (WHERE x.processing_details ? 'partial_follow_up_of') AS fu,
sum(x.actual_qty) FILTER (WHERE x.rn < x.cnt) AS q_prior,
max(x.actual_qty) FILTER (WHERE x.rn = x.cnt) AS q_last
FROM (
SELECT i.actual_qty, i.processing_details,
row_number() OVER (ORDER BY i.created_at ASC, i.id) AS rn,
count(*) OVER () AS cnt
FROM ${schema}.inspections i
WHERE i.order_code = po.order_code
AND i.sku_code IS NOT DISTINCT FROM po.sku_code
AND ${supplierEquiv}
AND (i.inspection_time IS NOT NULL OR COALESCE(i.quality_rating, '') <> '')
AND COALESCE(i.quality_rating, '') NOT LIKE '%不合格%'
AND COALESCE(i.actual_qty, 0) > 0
AND (i.processing_details->>'purchase_code' = po.purchase_code
OR COALESCE(i.processing_details->'purchase_codes', '[]'::jsonb) ? po.purchase_code)
) x
) agg ON TRUE
WHERE COALESCE(NULLIF(TRIM(po.supplier_code), ''), '') = ''
${sinceClause}
ORDER BY po.created_at ASC`;
}
/** 与 writeAccumulatedPurchaseActual 同一归属判定;返回 null 表示保留现值 */
function decide(row) {
const stored = row.actual_qty === null ? null : Number(row.actual_qty);
const accumulated = round3(Number(row.insp_qty) || 0);
const status = Number(row.purchase_status) || 0;
const prior = round3(Number(row.prior_qty) || 0);
const last = row.last_qty === null ? null : round3(Number(row.last_qty) || 0);
if (!(accumulated > 0)) return { action: 'skip', reason: '无已完成批次' };
if (stored !== null && accumulated + EPS < stored) return { action: 'skip', reason: '累计低于现值,不自动下调' };
if (stored !== null && Math.abs(accumulated - stored) < EPS) return { action: 'skip', reason: '已一致' };
const flowWritten =
stored === null ||
status < 30 ||
Math.abs(stored - prior) < EPS ||
(last !== null && Math.abs(stored - last) < EPS);
if (!flowWritten) return { action: 'skip', reason: '疑似人工改量(现值与批次记录不符),保留现值' };
return { action: 'update', accumulated, reason: '本流程写入的首批量,按批次累计回写' };
}
async function processTenant(client, schema) {
const { rows } = await client.query(scanSql(schema));
const changes = [];
const skipped = [];
for (const row of rows) {
const verdict = decide(row);
if (verdict.action === 'skip') {
if (verdict.reason !== '已一致' && verdict.reason !== '无已完成批次') skipped.push({ ...row, reason: verdict.reason });
continue;
}
const price = row.actual_price === null ? null : Number(row.actual_price);
const newAmount = price === null ? null : round2(verdict.accumulated * price);
changes.push({
schema,
purchase_code: row.purchase_code,
order_code: row.order_code,
sku_code: row.sku_code,
sku_name: row.sku_name,
created_day: row.created_day,
purchase_status: row.purchase_status,
batches: Number(row.batch_cnt),
follow_ups: Number(row.follow_up_cnt),
old_qty: row.actual_qty === null ? null : Number(row.actual_qty),
new_qty: verdict.accumulated,
actual_price: price,
old_amount: row.total_amount === null ? null : Number(row.total_amount),
new_amount: newAmount,
});
}
return { changes, skipped };
}
async function main() {
const client = await pool.connect();
try {
await client.query('BEGIN READ ONLY');
const tenants = await discoverTenants(client);
const report = { generated_at: new Date().toISOString(), mode: apply ? 'apply' : 'dry-run', since, tenants: {} };
let totalChanges = 0;
let totalQty = 0;
let totalAmount = 0;
for (const schema of tenants) {
const { changes, skipped } = await processTenant(client, schema);
report.tenants[schema] = { changes, skipped };
totalChanges += changes.length;
totalQty = round3(totalQty + changes.reduce((s, c) => s + (c.new_qty - (c.old_qty || 0)), 0));
totalAmount = round2(totalAmount + changes.reduce((s, c) => s + ((c.new_amount || 0) - (c.old_amount || 0)), 0));
console.log(
`[${schema}] 待修正 ${changes.length} 单,保留(疑似人工改量等)${skipped.length} 单`
);
for (const c of changes) {
console.log(
` ${c.purchase_code} ${c.sku_name || c.sku_code} 建单 ${c.created_day} 状态 ${c.purchase_status} ` +
`批次 ${c.batches}(补收 ${c.follow_ups}):实收 ${c.old_qty} → ${c.new_qty},` +
`金额 ${c.old_amount} → ${c.new_amount}`
);
}
for (const s of skipped) {
console.log(
` [保留] ${s.purchase_code} ${s.sku_name || s.sku_code}:现值 ${s.actual_qty} vs 批次合计 ${round3(Number(s.insp_qty))}(${s.reason})`
);
}
}
report.summary = { changed_orders: totalChanges, qty_gap: totalQty, amount_gap: totalAmount };
if (!apply) {
await client.query('ROLLBACK');
writeFileSync(outPath, JSON.stringify(report, null, 2));
console.log(`\n干跑完成:${totalChanges} 单,缺口 +${totalQty} / +${totalAmount};审计文件 ${outPath}`);
console.log('未写库(事务已回滚)。正式执行请加 --apply');
return;
}
// 正式执行:重新在一个可写事务内扫描 + 逐条 UPDATE,任一条对不上就整体回滚
await client.query('ROLLBACK');
await client.query('BEGIN');
let applied = 0;
for (const schema of tenants) {
const { changes } = await processTenant(client, schema);
for (const c of changes) {
const res = await client.query(
`UPDATE ${schema}.purchase_orders
SET actual_qty = $2::numeric,
total_amount = CASE WHEN $3::numeric IS NULL THEN total_amount ELSE $3::numeric END
WHERE purchase_code = $1
AND actual_qty IS NOT DISTINCT FROM $4::numeric`,
[c.purchase_code, c.new_qty, c.new_amount, c.old_qty]
);
if (res.rowCount !== 1) {
throw new Error(
`${c.purchase_code} 更新影响 ${res.rowCount} 行(期望 1)——期间有并发写入,已整体回滚`
);
}
applied += 1;
}
}
await client.query('COMMIT');
writeFileSync(outPath, JSON.stringify(report, null, 2));
console.log(`\n已提交:${applied} 单,缺口 +${totalQty} / +${totalAmount};审计文件 ${outPath}`);
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
throw error;
} finally {
client.release();
await pool.end();
}
}
main().catch((error) => {
console.error('FATAL:', error.message);
process.exit(1);
});