#!/usr/bin/env node /** * 生产修复:自采 status=20 断环对账 * 用法:在 API 机 /opt/ai-fresh-delivery/server 下 * NODE_PATH=./node_modules node /tmp/prod-repair-po20-inbound-loop.cjs * 可选:传入采购单号限制范围 */ const fs = require('fs'); const path = require('path'); const { pathToFileURL } = require('url'); async function loadDbUrl() { const envPath = '/opt/ai-fresh-delivery/server/.env'; const env = fs.readFileSync(envPath, 'utf8'); return env.match(/^DATABASE_URL=(.+)$/m)[1].trim().replace(/^["']|["']$/g, ''); } async function main() { process.chdir('/opt/ai-fresh-delivery/server'); process.env.DATABASE_URL = process.env.DATABASE_URL || (await loadDbUrl()); // 用编译后的 dist 若存在,否则直接动态 import ts 不可靠;改用内联 SQL + ensure 逻辑副本 const pg = require('pg'); const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const filterCodes = process.argv.slice(2).filter(Boolean); const rows = filterCodes.length ? ( await pool.query( `SELECT purchase_code, order_code, sku_code, supplier_code, actual_qty, purchase_qty FROM purchase_orders WHERE purchase_code = ANY($1::text[]) AND purchase_status = 20`, [filterCodes] ) ).rows : ( await pool.query( `SELECT purchase_code, order_code, sku_code, supplier_code, actual_qty, purchase_qty FROM purchase_orders WHERE purchase_status = 20 ORDER BY created_at DESC NULLS LAST LIMIT 200` ) ).rows; const summary = { scanned: 0, closed: [], ensured: [], reset: [], skipped: [] }; for (const po of rows) { summary.scanned += 1; const code = po.purchase_code; const client = await pool.connect(); try { await client.query('BEGIN'); const pending = await client.query( `SELECT 1 FROM inspections WHERE NULLIF(TRIM(processing_details->>'purchase_code'), '') = $1 AND inspection_time IS NULL AND COALESCE(NULLIF(TRIM(inbound_batch_no), ''), '') = '' AND COALESCE(compliance_status, 0) < 40 LIMIT 1`, [code] ); if (pending.rowCount) { summary.skipped.push(code); await client.query('COMMIT'); continue; } const success = await client.query( `SELECT 1 FROM inspections WHERE order_code IS NOT DISTINCT FROM $1 AND COALESCE(supplier_code, '') = COALESCE($3, '') AND sku_code IS NOT DISTINCT FROM $2 AND inspection_time IS NOT NULL AND NULLIF(TRIM(inbound_batch_no), '') IS NOT NULL AND COALESCE(quality_rating, '') NOT IN ('D', '不合格') AND COALESCE(compliance_status, 0) <> 30 AND ( NULLIF(TRIM(processing_details->>'purchase_code'), '') IS NOT DISTINCT FROM $4 OR NULLIF(TRIM(processing_details->>'purchase_code'), '') IS NULL ) LIMIT 1`, [po.order_code || null, po.sku_code, po.supplier_code || null, code] ); if (success.rowCount) { await client.query( `UPDATE purchase_orders SET purchase_status = 30 WHERE purchase_code = $1 AND purchase_status = 20`, [code] ); summary.closed.push(code); await client.query('COMMIT'); continue; } const qty = Number(po.actual_qty ?? po.purchase_qty) || 0; if (qty > 0) { // 无成功入库:插入待验自采验收(与 ensure 对齐的最小实现) const exists = await client.query( `SELECT 1 FROM inspections WHERE NULLIF(TRIM(processing_details->>'purchase_code'), '') = $1 AND inspection_time IS NULL LIMIT 1`, [code] ); if (!exists.rowCount) { const d = new Date(); const batch = `IN${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}${Math.random().toString(36).slice(2, 8).toUpperCase()}`; const branch = ( await client.query(`SELECT branch_code FROM purchase_orders WHERE purchase_code = $1`, [code]) ).rows[0]?.branch_code; await client.query( `INSERT INTO inspections ( order_code, sku_code, supplier_code, prepare_qty, purchase_price, batch_no, branch_code, source_type, processing_details ) VALUES ($1,$2,$3,$4,$5,$6,$7,'purchase',$8::jsonb)`, [ po.order_code || null, po.sku_code, po.supplier_code || null, qty, null, batch, branch || null, JSON.stringify({ purchase_code: code }), ] ); } summary.ensured.push(code); await client.query('COMMIT'); continue; } await client.query( `UPDATE purchase_orders SET purchase_status = 10 WHERE purchase_code = $1 AND purchase_status = 20`, [code] ); summary.reset.push(code); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK').catch(() => undefined); throw e; } finally { client.release(); } } console.log(JSON.stringify(summary, null, 2)); await pool.end(); } main().catch((e) => { console.error(e); process.exit(1); });