#!/usr/bin/env npx tsx /** * 运维回冲:已发车但无分拣/核货出库流水的订单,补扣 available_qty * * 用法(在 server 目录): * npx tsx --env-file=.env scripts/backfill-delivery-loading-outbound.ts * npx tsx --env-file=.env scripts/backfill-delivery-loading-outbound.ts --branch=BR002 --since=2026-07-01 * npx tsx --env-file=.env scripts/backfill-delivery-loading-outbound.ts --branch=BR002 --execute * npx tsx --env-file=.env scripts/backfill-delivery-loading-outbound.ts --order=SO-xxx --execute * * 默认 dry-run,不加 --execute 不会写库。 */ import { backfillDeliveryLoadingOutboundForOrder, listOrdersMissingDeliveryOutbound, type BackfillOrderResult, } from '../src/services/inventoryOutboundService'; import { listActiveTenantBranches, runInBranchSchema } from '../src/services/tenantSchemaFallback'; import { pool } from '../src/db'; function parseArgs(argv: string[]) { const opts = { execute: false, branch: undefined as string | undefined, order: undefined as string | undefined, since: undefined as string | undefined, limit: 500, 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('--branch=')) opts.branch = arg.slice('--branch='.length).trim(); else if (arg.startsWith('--order=')) opts.order = arg.slice('--order='.length).trim(); else if (arg.startsWith('--since=')) opts.since = arg.slice('--since='.length).trim(); else if (arg.startsWith('--limit=')) { opts.limit = Math.max(1, Number(arg.slice('--limit='.length)) || 500); } } return opts; } function printHelp() { console.log(`历史发车未扣库回冲 默认 dry-run。参数: --branch=BRxxx 限定分公司 --order=ORxxx 只处理单笔订单 --since=YYYY-MM-DD 配送日起 --limit=N 最多处理订单数(默认 500) --execute 真正扣库写流水 `); } async function listCandidates(opts: { branch?: string; order?: string; since?: string; limit: number; }) { if (opts.branch) { return runInBranchSchema(opts.branch, () => listOrdersMissingDeliveryOutbound({ branchCode: opts.branch, orderCode: opts.order, since: opts.since, limit: opts.limit, }) ); } if (opts.order) { // 先在 public / 当前连接找订单分公司,再进 schema const found = await pool.query( `SELECT order_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`, [opts.order] ); let branchCode = found.rows[0]?.branch_code ? String(found.rows[0].branch_code) : null; if (!branchCode) { const tenants = await listActiveTenantBranches(); for (const t of tenants) { const hit = await runInBranchSchema(t.branch_code, async () => { const r = await pool.query( `SELECT order_code, branch_code FROM orders WHERE order_code = $1 LIMIT 1`, [opts.order] ); return r.rows[0] || null; }); if (hit) { branchCode = String(hit.branch_code || t.branch_code); break; } } } if (!branchCode) return []; return runInBranchSchema(branchCode, () => listOrdersMissingDeliveryOutbound({ orderCode: opts.order, since: opts.since, limit: opts.limit, }) ); } // 全部分公司:扫 active tenant const tenants = await listActiveTenantBranches(); if (!tenants.length) { return listOrdersMissingDeliveryOutbound({ since: opts.since, limit: opts.limit, }); } const all: Awaited> = []; let remaining = opts.limit; for (const t of tenants) { if (remaining <= 0) break; const rows = await runInBranchSchema(t.branch_code, () => listOrdersMissingDeliveryOutbound({ branchCode: t.branch_code, since: opts.since, limit: remaining, }) ); all.push(...rows); remaining = opts.limit - all.length; } return all; } async function runOne( orderCode: string, branchCode: string | null, dryRun: boolean ): Promise { const runner = () => backfillDeliveryLoadingOutboundForOrder(orderCode, { dryRun, remark: `配送核货出库回冲 ${orderCode}`, }); if (branchCode) return runInBranchSchema(branchCode, runner); return runner(); } async function main() { const opts = parseArgs(process.argv.slice(2)); if (opts.help) { printHelp(); process.exit(0); } const dryRun = !opts.execute; console.log( JSON.stringify( { mode: dryRun ? 'dry-run' : 'execute', branch: opts.branch || null, order: opts.order || null, since: opts.since || null, limit: opts.limit, }, null, 2 ) ); const candidates = await listCandidates(opts); console.log(`\n候选订单: ${candidates.length}`); const summary = { planned: 0, deducted: 0, skipped: 0, failed: 0 }; const failures: BackfillOrderResult[] = []; for (const row of candidates) { const result = await runOne(row.order_code, row.branch_code, dryRun); const lineCount = result.lines?.length || 0; const qtySum = (result.lines || []).reduce((s, l) => s + l.qty, 0); console.log( [ result.order_code, result.branch_code || '-', result.status, result.reason || result.error || '', `lines=${lineCount}`, `qty=${qtySum}`, ].join('\t') ); if (result.status === 'planned') summary.planned += 1; else if (result.status === 'deducted') summary.deducted += 1; else if (result.status === 'skipped') summary.skipped += 1; else { summary.failed += 1; failures.push(result); } } console.log('\n汇总:', summary); if (failures.length) { console.log('\n失败明细:'); for (const f of failures) { console.log(`- ${f.order_code}: ${f.error || f.reason}`); } } if (dryRun) { console.log('\n[dry-run] 未写库。确认后加 --execute'); } await pool.end(); process.exit(summary.failed > 0 ? 2 : 0); } main().catch(async (err) => { console.error(err); try { await pool.end(); } catch { /* ignore */ } process.exit(1); });