/** * 存量修复:因「退货红冲行的入库被当成新行已入库」而被错误关单(status=30)且**没有待验**的 * 仓内加工成品自采单,重开为 20(待仓验)并补齐待验记录。 * * ⚠️ 只允许对本地库运行(脚本拒绝非 localhost 的 DATABASE_URL)。 * 默认 **dry-run**(只列目标),加 `--apply` 才写;写入走的都是既有业务函数,且逐单事务。 * * 运行(server 目录): * npx tsx --env-file=.env scripts/repair-returned-line-inbound.ts # 干跑 * npx tsx --env-file=.env scripts/repair-returned-line-inbound.ts --apply # 执行 * * 背景与判定见 docs/design/20260922-inbound-attribution-after-order-item-return.md */ import pg from 'pg'; import { ensurePurchaseInspectionForCompletedPurchase } from '../src/services/inspectionComplianceService'; import { recalcDemandSheetFromInspections } from '../src/services/processingDemandSheetService'; const { Pool } = pg; function assertLocalDatabase(url: string) { const host = (() => { try { return new URL(url).hostname; } catch { return ''; } })(); if (!['127.0.0.1', 'localhost', '::1'].includes(host)) { throw new Error(`拒绝运行:DATABASE_URL 指向非本地库 (${host || 'unknown'})`); } } type Target = { order_code: string; sku_code: string; purchase_code: string; purchase_status: number; purchase_qty: string | null; remark: string | null; returned_item: string; }; /** * 目标 = 满足全部条件: * 1) 该 SKU 存在**已退货**的订单行,且它有一条「有效入库」的验收行(inbound_batch_no 非空、 * compliance_status>=40、actual_qty>0)——即被红冲但验收行保留的那条; * 2) 存在**未退货**的同 SKU 订单行,其履约指向一张自采单; * 3) 该自采单 purchase_status = 30(已被错误关单); * 4) 该自采单**没有任何验收行**引用(既无待验也无已入库)。 */ const FIND_TARGETS_SQL = ` SELECT DISTINCT po.order_code, po.sku_code, po.purchase_code, po.purchase_status, po.purchase_qty, po.remark, roi.item_name AS returned_item FROM purchase_orders po JOIN order_item_fulfillments f ON f.purchase_code = po.purchase_code JOIN order_items oi ON oi.id = f.order_item_id AND COALESCE(oi.is_returned, false) = false JOIN order_items roi ON roi.order_code = po.order_code AND roi.sku_code IS NOT DISTINCT FROM po.sku_code AND COALESCE(roi.is_returned, false) = true WHERE po.purchase_status = 30 AND EXISTS ( SELECT 1 FROM inspections i WHERE i.order_code = roi.order_code AND i.sku_code IS NOT DISTINCT FROM roi.sku_code AND i.compliance_status >= 40 AND NULLIF(TRIM(i.inbound_batch_no), '') IS NOT NULL AND COALESCE(i.actual_qty, 0) > 0 ) AND NOT EXISTS ( SELECT 1 FROM inspections i2 WHERE i2.order_code = po.order_code AND i2.sku_code IS NOT DISTINCT FROM po.sku_code AND ( NULLIF(TRIM(i2.processing_details->>'purchase_code'), '') = po.purchase_code OR COALESCE(i2.processing_details->'purchase_codes', '[]'::jsonb) ? po.purchase_code ) ) ORDER BY po.order_code, po.purchase_code`; async function main() { const url = String(process.env.DATABASE_URL || ''); if (!url) throw new Error('缺少 DATABASE_URL(用 npx tsx --env-file=.env 运行)'); assertLocalDatabase(url); const apply = process.argv.includes('--apply'); const schema = `tenant_${String(process.env.REPAIR_BRANCH || 'br004').toLowerCase()}`; const pool = new Pool({ connectionString: url, max: 2 }); const client = await pool.connect(); await client.query(`SET search_path TO ${schema}, public`); try { const found = await client.query(FIND_TARGETS_SQL); console.log(`租户 ${schema}:命中 ${found.rowCount} 张需修复的自采单${apply ? '' : '(干跑,不写入)'}`); for (const t of found.rows) { console.log( ` - ${t.order_code} / ${t.sku_code}(原行「${t.returned_item}」已退货)→ 自采单 ${t.purchase_code}` + ` status=${t.purchase_status} qty=${t.purchase_qty} remark=${t.remark || ''}` ); } if (!apply) { console.log('\n加 --apply 执行:把上述自采单重开为 20 并补齐待验。'); return; } for (const t of found.rows) { const purchaseCode = String(t.purchase_code); const orderCode = String(t.order_code); await client.query('BEGIN'); try { await client.query( `UPDATE purchase_orders SET purchase_status = 20, remark = CASE WHEN COALESCE(remark, '') = '' THEN '退货红冲后重开待仓验(存量修复)' ELSE remark || ';退货红冲后重开待仓验(存量修复)' END WHERE purchase_code = $1 AND purchase_status = 30`, [purchaseCode] ); await ensurePurchaseInspectionForCompletedPurchase(client, purchaseCode); // 加工单净重可能仍沿用被红冲行的实收(本单 7 斤)→ 建完待验后重算 const tasks = await client.query( `SELECT DISTINCT di.task_id FROM processing_demand_items di JOIN processing_tasks pt ON pt.id = di.task_id AND pt.source_type = 'demand' WHERE di.order_code = $1 AND di.sku_code = $2 AND pt.process_status < 50`, [orderCode, t.sku_code] ); for (const row of tasks.rows) { await recalcDemandSheetFromInspections(String(row.task_id), client); } await client.query('COMMIT'); if (tasks.rowCount) console.log(` 重算加工单:${tasks.rows.map((r) => r.task_id).join(', ')}`); } catch (err) { await client.query('ROLLBACK').catch(() => undefined); console.error(` ✘ ${purchaseCode} 修复失败:`, (err as Error).message); continue; } const after = await client.query( `SELECT po.purchase_status, (SELECT count(*)::int FROM inspections i WHERE i.order_code = po.order_code AND i.sku_code IS NOT DISTINCT FROM po.sku_code AND (NULLIF(TRIM(i.processing_details->>'purchase_code'), '') = po.purchase_code OR COALESCE(i.processing_details->'purchase_codes', '[]'::jsonb) ? po.purchase_code) ) AS inspections, (SELECT count(*)::int FROM inspections i WHERE i.order_code = po.order_code AND i.sku_code IS NOT DISTINCT FROM po.sku_code AND i.inspection_time IS NULL) AS pending FROM purchase_orders po WHERE po.purchase_code = $1`, [purchaseCode] ); console.log(` ✔ ${purchaseCode} → ${JSON.stringify(after.rows[0])}(订单 ${orderCode})`); } } finally { client.release(); await pool.end(); } } main().then( () => process.exit(0), (e) => { console.error('FATAL', (e as Error).message); process.exit(1); } );