#!/usr/bin/env npx tsx /** * 回填:按装车/分拣称重对齐订单结算量,并同步客户结算单 * 设计:docs/design/20260813-backfill-delivery-weigh-settlement-today.md * * 默认:上海时区「今天」配送日 + 已完成(≥90) + picked_weight>0 且与 quantity 不一致 * * cd server * npx tsx --env-file=.env scripts/backfill-delivery-weigh-settlement.ts * npx tsx --env-file=.env scripts/backfill-delivery-weigh-settlement.ts --execute * npx tsx --env-file=.env scripts/backfill-delivery-weigh-settlement.ts --day=2026-08-13 --execute * npx tsx --env-file=.env scripts/backfill-delivery-weigh-settlement.ts --branch=BR002 --execute */ import { pool } from '../src/db'; import { syncOrderItemFromPickingComplete } from '../src/services/orderItemSupplyUnitSync'; import { upsertCustomerStatementForOrder } from '../src/services/financeReconciliationService'; import { listActiveTenantBranches, runInBranchSchema } from '../src/services/tenantSchemaFallback'; import { formatChinaDate } from '../src/utils/chinaDate'; type Candidate = { branch_code: string | null; order_code: string; order_item_id: string; sku_code: string | null; item_name: string | null; unit: string | null; old_qty: number; picked_weight: number; }; function parseArgs(argv: string[]) { const opts = { execute: false, day: '' as string, branch: '' as string, order: '' as string, help: false, }; for (const arg of argv) { if (arg === '--execute') opts.execute = true; else if (arg === '--help' || arg === '-h') opts.help = true; else if (arg.startsWith('--day=')) opts.day = arg.slice('--day='.length).trim(); else if (arg.startsWith('--branch=')) opts.branch = arg.slice('--branch='.length).trim(); else if (arg.startsWith('--order=')) opts.order = arg.slice('--order='.length).trim(); } return opts; } async function listCandidatesInSchema(opts: { day: string; order?: string; }): Promise { const params: unknown[] = [opts.day]; let orderSql = ''; if (opts.order) { params.push(opts.order); orderSql = ` AND o.order_code = $${params.length}`; } const result = await pool.query( `WITH weigh AS ( SELECT DISTINCT ON (pi.order_item_id) pi.order_item_id, pi.order_code, pi.sku_code, pi.item_name, pi.unit, pi.picked_weight::float8 AS picked_weight FROM picking_items pi WHERE pi.order_item_id IS NOT NULL AND COALESCE(pi.picked_weight, 0) > 0 ORDER BY pi.order_item_id, pi.picked_weight DESC NULLS LAST ) SELECT o.branch_code, o.order_code, oi.id::text AS order_item_id, oi.sku_code, COALESCE(NULLIF(TRIM(oi.item_name), ''), w.item_name) AS item_name, COALESCE(NULLIF(TRIM(w.unit), ''), oi.unit) AS unit, COALESCE(oi.quantity, 0)::float8 AS old_qty, w.picked_weight FROM weigh w JOIN order_items oi ON oi.id = w.order_item_id JOIN orders o ON o.order_code = oi.order_code WHERE o.deleted_at IS NULL AND o.order_status >= 90 AND o.delivery_date = $1::date AND ABS(COALESCE(oi.quantity, 0) - w.picked_weight) > 0.0001 ${orderSql} ORDER BY o.order_code, oi.sort_order NULLS LAST, oi.id`, params ); return result.rows.map((row) => ({ branch_code: row.branch_code ? String(row.branch_code) : null, order_code: String(row.order_code), order_item_id: String(row.order_item_id), sku_code: row.sku_code ? String(row.sku_code) : null, item_name: row.item_name ? String(row.item_name) : null, unit: row.unit ? String(row.unit) : null, old_qty: Number(row.old_qty) || 0, picked_weight: Number(row.picked_weight) || 0, })); } async function collectCandidates(opts: { day: string; branch?: string; order?: string; }): Promise { if (opts.branch) { return runInBranchSchema(opts.branch, () => listCandidatesInSchema({ day: opts.day, order: opts.order }) ); } const tenants = await listActiveTenantBranches(); if (!tenants.length) { return listCandidatesInSchema({ day: opts.day, order: opts.order }); } const all: Candidate[] = []; for (const t of tenants) { const rows = await runInBranchSchema(t.branch_code, () => listCandidatesInSchema({ day: opts.day, order: opts.order }) ).catch((err) => { console.warn(`skip branch ${t.branch_code}:`, err instanceof Error ? err.message : err); return [] as Candidate[]; }); all.push(...rows); } return all; } async function applyOne(row: Candidate, branchHint: string | null): Promise { const runner = async () => { const client = await pool.connect(); try { await client.query('BEGIN'); await syncOrderItemFromPickingComplete(client, { orderItemId: row.order_item_id, settlementQty: row.picked_weight, settlementUnit: row.unit, }); await upsertCustomerStatementForOrder(row.order_code, client); await client.query('COMMIT'); } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); } }; const branch = row.branch_code || branchHint; if (branch) await runInBranchSchema(branch, runner); else await runner(); } async function main() { const opts = parseArgs(process.argv.slice(2)); if (opts.help) { console.log(`今日完成单:称重 → 结算量回填 默认 dry-run。参数: --day=YYYY-MM-DD 配送日(默认上海时区今天) --branch=BRxxx 限定分公司 --order=ORxxx 只处理单笔 --execute 真正写库 `); process.exit(0); } const day = opts.day || formatChinaDate(new Date()); const dryRun = !opts.execute; console.log( JSON.stringify( { mode: dryRun ? 'dry-run' : 'execute', day, branch: opts.branch || null, order: opts.order || null, }, null, 2 ) ); const rows = await collectCandidates({ day, branch: opts.branch || undefined, order: opts.order || undefined, }); console.log(`\n待对齐明细: ${rows.length}`); for (const row of rows) { console.log( [ row.order_code, row.branch_code || '-', row.item_name || row.sku_code || row.order_item_id, `${row.old_qty} → ${row.picked_weight}`, row.unit || '', ].join('\t') ); } if (dryRun) { console.log('\n(dry-run) 未写库。加 --execute 执行。'); await pool.end(); return; } const orderCodes = [...new Set(rows.map((r) => r.order_code))]; let ok = 0; let failed = 0; for (const row of rows) { try { await applyOne(row, opts.branch || null); ok += 1; console.log(`OK ${row.order_code} ${row.order_item_id} ${row.old_qty}→${row.picked_weight}`); } catch (error) { failed += 1; console.error( `FAIL ${row.order_code} ${row.order_item_id}:`, error instanceof Error ? error.message : error ); } } // 每行已 upsert 结算单;再按订单去重刷一次 total(sync 内已更新) console.log('\n汇总:', { lines_ok: ok, lines_failed: failed, orders: orderCodes.length }); await pool.end(); if (failed) process.exit(1); } main().catch(async (error) => { console.error(error); try { await pool.end(); } catch { /* ignore */ } process.exit(1); });