#!/usr/bin/env node /** * 定点补数:BR002 两单「小苹果」缺失的已完成自采单、履约、验收入库。 * 范围写死,可重复跑。完结单入库 available_qty=0。不写独立入库、不写 cost_details。 * * 默认 dry-run: * node --env-file=.env scripts/backfill-missing-self-purchase-xiaopingguo.cjs * 本地写入: * node --env-file=.env scripts/backfill-missing-self-purchase-xiaopingguo.cjs --execute --allow-local * 生产(API 机、该机 server/.env): * node --env-file=.env scripts/backfill-missing-self-purchase-xiaopingguo.cjs --execute --prod */ const { Pool } = require('pg'); const BRANCH = 'BR002'; const TARGETS = [ { orderCode: 'ORD_WEB_20260915_BR002_0001', itemId: '8be642a0-766e-4983-a21f-7d9502b4d7a6', skuCode: 'SKU78661926693', }, { orderCode: 'ORD_WEB_20260915_BR002_0003', itemId: 'aa1e7bd0-9056-440b-8da3-4a5d7c6c5f83', skuCode: 'SKU78661926693', }, ]; function parseArgs(argv) { return { execute: argv.includes('--execute'), prod: argv.includes('--prod'), allowLocal: argv.includes('--allow-local'), help: argv.includes('--help') || argv.includes('-h'), }; } function databaseUrl() { const url = String(process.env.DATABASE_URL || '').trim(); if (!url) throw new Error('缺少 DATABASE_URL'); return url; } function describeUrl(url) { const u = new URL(url); const host = u.hostname || 'unknown'; const database = decodeURIComponent(u.pathname.replace(/^\//, '') || ''); const local = host === '127.0.0.1' || host === 'localhost' || host === '::1'; return { host, database, local }; } function newBatchNo(ymd = '20260915') { return `IN${ymd}${Math.random().toString(36).slice(2, 8).toUpperCase()}`; } async function withTenant(pool, fn) { const client = await pool.connect(); try { await client.query(`SELECT set_config('app.branch_code', $1, false)`, [BRANCH]); await client.query(`SET search_path TO tenant_br002, public`); return await fn(client); } finally { client.release(); } } async function inspectOne(client, orderCode, itemId, skuCode) { const item = await client.query( `SELECT oi.id::text AS id, oi.order_code, oi.item_name, oi.sku_code, oi.quantity::float AS quantity, oi.unit, oi.unit_cost::float AS unit_cost, oi.supplier_code, o.order_status, o.branch_code FROM order_items oi JOIN orders o ON o.order_code = oi.order_code WHERE oi.id = $1::uuid AND oi.order_code = $2 AND oi.sku_code = $3`, [itemId, orderCode, skuCode] ); const po = await client.query( `SELECT purchase_code, purchase_status FROM purchase_orders WHERE order_code = $1 AND source_id = $2 AND purchase_status <> 40 LIMIT 1`, [orderCode, itemId] ); const sibling = await client.query( `SELECT purchaser_code, purchaser_name FROM purchase_orders WHERE order_code = $1 AND NULLIF(TRIM(purchaser_code), '') IS NOT NULL ORDER BY created_at ASC LIMIT 1`, [orderCode] ); const inbound = await client.query( `SELECT id::text AS id, inbound_batch_no FROM inspections WHERE order_code = $1 AND sku_code = $2 AND source_type = 'purchase' AND NULLIF(TRIM(inbound_batch_no), '') IS NOT NULL LIMIT 1`, [orderCode, skuCode] ); return { row: item.rows[0], existingPo: po.rows[0], existingInbound: inbound.rows[0], purchaser: sibling.rows[0], }; } async function backfillPo(client, params) { const purchaseCode = `PURB${Date.now()}${String(params.itemId).slice(-4)}${Math.floor(Math.random() * 1000)}`; const qty = Number(params.quantity) || 0; const cost = Math.max(0, Number(params.unitCost) || 0); await client.query( `INSERT INTO purchase_orders ( purchase_code, order_code, sku_code, supplier_code, purchaser_code, purchaser_name, purchase_qty, purchase_price, actual_qty, actual_price, total_amount, purchase_status, is_temporary_supplier, source_type, source_id, remark, branch_code ) VALUES ( $1, $2, $3, NULL, $4, $5, $6, $7, $6, $7, $8, 30, false, 'order_no_supplier', $9, '[补数] 完成单补已完成自采', $10 )`, [ purchaseCode, params.orderCode, params.skuCode, params.purchaserCode, params.purchaserName, qty, cost, qty * cost, params.itemId, params.branchCode, ] ); await client.query( `INSERT INTO order_item_fulfillments ( order_item_id, order_code, supplier_preparation_id, purchase_code, inventory_cover_qty, updated_at ) VALUES ($1::uuid, $2, NULL, $3, 0, NOW()) ON CONFLICT (order_item_id) DO UPDATE SET order_code = EXCLUDED.order_code, supplier_preparation_id = NULL, purchase_code = EXCLUDED.purchase_code, inventory_cover_qty = 0, updated_at = NOW()`, [params.itemId, params.orderCode, purchaseCode] ); return purchaseCode; } async function backfillInbound(client, params) { const qty = Number(params.quantity) || 0; const cost = Math.max(0, Number(params.unitCost) || 0); const batchNo = newBatchNo(); const details = JSON.stringify({ purchase_code: params.purchaseCode, purchase_codes: [params.purchaseCode], history_backfill: true, }); const inserted = await client.query( `INSERT INTO inspections ( order_code, sku_code, supplier_code, prepare_qty, actual_qty, purchase_price, batch_no, inbound_batch_no, branch_code, source_type, processing_details, item_name, unit, quality_rating, compliance_status, inspection_time ) VALUES ( $1, $2, NULL, $3, $3, $4, $5, $5, $6, 'purchase', $7::jsonb, $8, $9, '合格', 40, TIMESTAMPTZ '2026-09-15 21:41:00+08' ) RETURNING id::text AS id`, [ params.orderCode, params.skuCode, qty, cost || null, batchNo, params.branchCode, details, params.itemName, params.unit || '斤', ] ); const inspectionId = String(inserted.rows[0]?.id || ''); await client.query( `INSERT INTO inventory ( batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status, branch_code, production_date ) VALUES ($1, $2, $3, 0, NULL, $4, 10, $5, DATE '2026-09-15')`, [batchNo, params.skuCode, qty, cost || null, params.branchCode] ); await client.query( `INSERT INTO inventory_logs ( batch_no, sku_code, operation_type, quantity, before_qty, after_qty, related_order_code, remark ) VALUES ($1, $2, 'inspection_in', $3, 0, 0, $4, $5)`, [ batchNo, params.skuCode, qty, params.orderCode, `验收入库 ${inspectionId}(订单已完结,不形成可用库存)`, ] ); return { inspectionId, batchNo }; } async function main() { const opts = parseArgs(process.argv.slice(2)); if (opts.help) { console.log(`定点补 BR002 两单小苹果自采+入库 dry-run: node --env-file=.env scripts/backfill-missing-self-purchase-xiaopingguo.cjs 本地写入: node --env-file=.env scripts/backfill-missing-self-purchase-xiaopingguo.cjs --execute --allow-local 生产写入: node --env-file=.env scripts/backfill-missing-self-purchase-xiaopingguo.cjs --execute --prod `); return; } const url = databaseUrl(); const target = describeUrl(url); console.log(`DB ${target.host}/${target.database} local=${target.local} execute=${opts.execute}`); if (opts.execute) { if (target.local && !opts.allowLocal) { throw new Error('当前 DATABASE_URL 是本机库。本地写入请加 --allow-local'); } if (!target.local && !opts.prod) { throw new Error('当前 DATABASE_URL 不是本机。写入生产必须加 --prod'); } } const pool = new Pool({ connectionString: url, max: 2 }); try { await withTenant(pool, async (client) => { for (const targetItem of TARGETS) { const found = await inspectOne(client, targetItem.orderCode, targetItem.itemId, targetItem.skuCode); if (!found.row) { console.log(`SKIP missing ${targetItem.orderCode} ${targetItem.itemId}`); continue; } const line = `${targetItem.orderCode} ${found.row.item_name} qty=${found.row.quantity}`; if (!opts.execute) { console.log( `DRY ${line} po=${found.existingPo?.purchase_code || '-'} inbound=${found.existingInbound?.inbound_batch_no || '-'}` ); continue; } await client.query('BEGIN'); try { let purchaseCode = found.existingPo?.purchase_code || ''; if (!purchaseCode) { purchaseCode = await backfillPo(client, { orderCode: targetItem.orderCode, itemId: targetItem.itemId, skuCode: targetItem.skuCode, quantity: found.row.quantity, unitCost: found.row.unit_cost, branchCode: found.row.branch_code || BRANCH, purchaserCode: found.purchaser?.purchaser_code || null, purchaserName: found.purchaser?.purchaser_name || null, }); console.log(`OK po ${purchaseCode} ${line}`); } else { console.log(`KEEP po ${purchaseCode} ${line}`); } if (found.existingInbound?.inbound_batch_no) { console.log(`KEEP inbound ${found.existingInbound.inbound_batch_no} ${line}`); } else { const inbound = await backfillInbound(client, { orderCode: targetItem.orderCode, skuCode: targetItem.skuCode, itemName: found.row.item_name, quantity: found.row.quantity, unit: found.row.unit, unitCost: found.row.unit_cost, branchCode: found.row.branch_code || BRANCH, purchaseCode, }); console.log(`OK inbound ${inbound.batchNo} inspection=${inbound.inspectionId} ${line}`); } await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; } } }); } finally { await pool.end(); } } main().catch((err) => { console.error(err instanceof Error ? err.message : err); process.exitCode = 1; });