来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
369 lines
12 KiB
JavaScript
369 lines
12 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 历史合单客单:大青椒补入库 + 发车放行(一次性)
|
||
* 设计:docs/design/20260731-pepper-guest-inbound-release.md
|
||
*
|
||
* 用法(生产机):
|
||
* node scripts/prod-repair-pepper-guest-inbound-release.mjs # dry-run
|
||
* node scripts/prod-repair-pepper-guest-inbound-release.mjs --execute
|
||
*/
|
||
import pg from 'pg';
|
||
import { readFileSync, existsSync } from 'fs';
|
||
import { resolve, dirname } from 'path';
|
||
import { fileURLToPath } from 'url';
|
||
|
||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||
const EXECUTE = process.argv.includes('--execute');
|
||
|
||
const ORDER = 'ORD_MP_1785397841321WP0Q';
|
||
const SKU = 'SKU78661416041';
|
||
const ITEM = '大青椒';
|
||
const QTY = 14;
|
||
const BRANCH = 'BR002';
|
||
const SCHEMA = 'tenant_br002';
|
||
const OLD_PO = 'PUR17853976599417c66779';
|
||
const ORDER_ITEM_ID = 'e145b670-8eed-4ce8-91ac-5d8fe437665b';
|
||
|
||
function loadDatabaseUrl() {
|
||
const candidates = [
|
||
resolve(__dirname, '../.env'),
|
||
'/opt/ai-fresh-delivery/server/.env',
|
||
];
|
||
for (const p of candidates) {
|
||
if (!existsSync(p)) continue;
|
||
const m = readFileSync(p, 'utf8').match(/^DATABASE_URL=(.+)$/m);
|
||
if (m) return m[1].trim().replace(/^["']|["']$/g, '');
|
||
}
|
||
throw new Error('DATABASE_URL not found');
|
||
}
|
||
|
||
function newBatchNo() {
|
||
const d = new Date();
|
||
const ymd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
|
||
return `IN${ymd}${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
|
||
}
|
||
|
||
function newPurchaseCode() {
|
||
return `PUR${Date.now()}REP${Math.floor(Math.random() * 1000)}`;
|
||
}
|
||
|
||
async function main() {
|
||
const pool = new pg.Pool({ connectionString: loadDatabaseUrl() });
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query(`SET search_path TO ${SCHEMA}, public`);
|
||
|
||
const order = await client.query(
|
||
`SELECT order_code, order_status, branch_code, delivery_date::text
|
||
FROM orders WHERE order_code = $1`,
|
||
[ORDER]
|
||
);
|
||
if (!order.rowCount) throw new Error(`订单不存在 ${ORDER}`);
|
||
console.log('ORDER', order.rows[0]);
|
||
|
||
const task = await client.query(
|
||
`SELECT task_code, task_status, person_code, start_time::text
|
||
FROM delivery_tasks WHERE order_code = $1 ORDER BY created_at DESC LIMIT 1`,
|
||
[ORDER]
|
||
);
|
||
console.log('TASK', task.rows[0] || null);
|
||
|
||
const avail = await client.query(
|
||
`SELECT COALESCE(SUM(available_qty),0)::float AS avail
|
||
FROM inventory WHERE sku_code = $1 AND branch_code = $2 AND available_qty > 0`,
|
||
[SKU, BRANCH]
|
||
);
|
||
console.log('AVAIL_BEFORE', avail.rows[0].avail);
|
||
|
||
const existingIn = await client.query(
|
||
`SELECT id, inbound_batch_no, actual_qty, compliance_status
|
||
FROM inspections
|
||
WHERE order_code = $1 AND sku_code = $2 AND compliance_status >= 40
|
||
AND inbound_batch_no IS NOT NULL
|
||
LIMIT 1`,
|
||
[ORDER, SKU]
|
||
);
|
||
console.log('EXISTING_INBOUND', existingIn.rows[0] || null);
|
||
|
||
const oldPo = await client.query(
|
||
`SELECT purchase_code, actual_price, purchase_price, actual_qty, purchase_qty
|
||
FROM purchase_orders WHERE purchase_code = $1`,
|
||
[OLD_PO]
|
||
);
|
||
const cost =
|
||
Number(oldPo.rows[0]?.actual_price) ||
|
||
Number(oldPo.rows[0]?.purchase_price) ||
|
||
2.5;
|
||
console.log('COST_PRICE', cost, 'from', oldPo.rows[0] || null);
|
||
|
||
if (!EXECUTE) {
|
||
console.log('DRY-RUN:将补入库', QTY, '斤并放行发车。加 --execute 执行');
|
||
return;
|
||
}
|
||
|
||
await client.query('BEGIN');
|
||
|
||
let batchNo = existingIn.rows[0]?.inbound_batch_no
|
||
? String(existingIn.rows[0].inbound_batch_no)
|
||
: null;
|
||
|
||
if (!batchNo) {
|
||
batchNo = newBatchNo();
|
||
const purchaseCode = newPurchaseCode();
|
||
|
||
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, 'PUR001', '伏磊',
|
||
$4, $5, $4, $5, $6,
|
||
30, false, 'order_no_supplier', $7,
|
||
$8, $9
|
||
)`,
|
||
[
|
||
purchaseCode,
|
||
ORDER,
|
||
SKU,
|
||
QTY,
|
||
cost,
|
||
Math.round(QTY * cost * 100) / 100,
|
||
ORDER_ITEM_ID,
|
||
`运维补建:历史合单客单大青椒缺入库,按订货量 ${QTY} 补采完成(原挂 ${OLD_PO})`,
|
||
BRANCH,
|
||
]
|
||
);
|
||
|
||
await client.query(
|
||
`UPDATE order_item_fulfillments
|
||
SET purchase_code = $2, inventory_cover_qty = 0, updated_at = NOW()
|
||
WHERE order_item_id = $1::uuid`,
|
||
[ORDER_ITEM_ID, purchaseCode]
|
||
);
|
||
|
||
const insp = await client.query(
|
||
`INSERT INTO inspections (
|
||
order_code, sku_code, supplier_code, prepare_qty, actual_qty, purchase_price,
|
||
batch_no, branch_code, source_type, item_name, unit,
|
||
quality_rating, loss_qty, compliance_status, inspection_time, inbound_batch_no,
|
||
processing_details
|
||
) VALUES (
|
||
$1, $2, NULL, $3, $3, $4,
|
||
$5, $6, 'purchase', $7, '斤',
|
||
'A', 0, 40, NOW(), $8,
|
||
$9::jsonb
|
||
) RETURNING id`,
|
||
[
|
||
ORDER,
|
||
SKU,
|
||
QTY,
|
||
cost,
|
||
`BT${Date.now().toString(36).toUpperCase()}`,
|
||
BRANCH,
|
||
ITEM,
|
||
batchNo,
|
||
JSON.stringify({ purchase_code: purchaseCode, repair: 'pepper_guest_inbound_20260731' }),
|
||
]
|
||
);
|
||
|
||
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, $3, NULL, $4, 10, $5, (NOW() AT TIME ZONE 'Asia/Shanghai')::date)`,
|
||
[batchNo, SKU, QTY, cost, BRANCH]
|
||
);
|
||
|
||
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, $3, $4, $5)`,
|
||
[
|
||
batchNo,
|
||
SKU,
|
||
QTY,
|
||
ORDER,
|
||
`运维补入库 ${insp.rows[0].id} 历史合单客单放行`,
|
||
]
|
||
);
|
||
|
||
await client.query(
|
||
`INSERT INTO inventory_reservations (
|
||
order_item_id, order_code, sku_code, branch_code, qty, status
|
||
)
|
||
SELECT $1::uuid, $2, $3, $4, $5, 10
|
||
WHERE NOT EXISTS (
|
||
SELECT 1 FROM inventory_reservations
|
||
WHERE order_item_id = $1::uuid AND status = 10
|
||
)`,
|
||
[ORDER_ITEM_ID, ORDER, SKU, BRANCH, QTY]
|
||
);
|
||
|
||
console.log('INBOUND_OK', { batchNo, purchaseCode, inspectionId: insp.rows[0].id });
|
||
} else {
|
||
// 已有验收:确保批次可用足够
|
||
const inv = await client.query(
|
||
`SELECT id, available_qty FROM inventory WHERE batch_no = $1 FOR UPDATE`,
|
||
[batchNo]
|
||
);
|
||
const cur = Number(inv.rows[0]?.available_qty) || 0;
|
||
if (cur + 1e-9 < QTY) {
|
||
const need = Math.round((QTY - cur) * 100) / 100;
|
||
await client.query(
|
||
`UPDATE inventory
|
||
SET available_qty = available_qty + $2,
|
||
quantity = GREATEST(quantity, available_qty + $2)
|
||
WHERE batch_no = $1`,
|
||
[batchNo, need]
|
||
);
|
||
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, 'adjust', $3, $4, $5, $6, $7)`,
|
||
[
|
||
batchNo,
|
||
SKU,
|
||
need,
|
||
cur,
|
||
cur + need,
|
||
ORDER,
|
||
'运维补足可用:历史合单客单发车放行',
|
||
]
|
||
);
|
||
console.log('TOPPED_UP', { batchNo, from: cur, add: need });
|
||
} else {
|
||
console.log('INBOUND_ALREADY', batchNo, 'avail', cur);
|
||
}
|
||
}
|
||
|
||
// 发车扣库
|
||
const hasOut = await client.query(
|
||
`SELECT 1 FROM inventory_logs
|
||
WHERE related_order_code = $1
|
||
AND operation_type IN ('picking_out','delivery_loading_out')
|
||
LIMIT 1`,
|
||
[ORDER]
|
||
);
|
||
|
||
if (!hasOut.rowCount) {
|
||
// 按核货明细 FIFO 扣减(仅本单大青椒等已装车行)
|
||
const items = await client.query(
|
||
`SELECT pi.id, pi.pick_code, pi.item_name, pi.sku_code,
|
||
COALESCE(pi.loaded_qty,0)::float AS loaded,
|
||
COALESCE(pi.picked_qty,0)::float AS picked,
|
||
COALESCE(pi.required_qty,0)::float AS required
|
||
FROM picking_items pi
|
||
WHERE pi.order_code = $1
|
||
ORDER BY pi.sort_order NULLS LAST, pi.created_at ASC`,
|
||
[ORDER]
|
||
);
|
||
|
||
for (const row of items.rows) {
|
||
const sku = String(row.sku_code || '').trim();
|
||
if (!sku) continue;
|
||
const qty =
|
||
row.loaded > 0 ? row.loaded : row.picked > 0 ? row.picked : row.required;
|
||
if (qty <= 0) continue;
|
||
|
||
let remaining = qty;
|
||
const batches = await client.query(
|
||
`SELECT id, batch_no, available_qty
|
||
FROM inventory
|
||
WHERE sku_code = $1 AND available_qty > 0 AND branch_code = $2
|
||
ORDER BY expiry_date ASC NULLS LAST, created_at ASC
|
||
FOR UPDATE`,
|
||
[sku, BRANCH]
|
||
);
|
||
for (const batch of batches.rows) {
|
||
if (remaining <= 1e-9) break;
|
||
const before = Number(batch.available_qty) || 0;
|
||
const deduct = Math.min(before, remaining);
|
||
const after = Math.round((before - deduct) * 100) / 100;
|
||
remaining = Math.round((remaining - deduct) * 100) / 100;
|
||
await client.query(`UPDATE inventory SET available_qty = $1 WHERE id = $2`, [
|
||
after,
|
||
batch.id,
|
||
]);
|
||
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, 'delivery_loading_out', $3, $4, $5, $6, $7)`,
|
||
[
|
||
batch.batch_no,
|
||
sku,
|
||
deduct,
|
||
before,
|
||
after,
|
||
ORDER,
|
||
`运维放行发车扣库 ${task.rows[0]?.task_code || ORDER}`,
|
||
]
|
||
);
|
||
}
|
||
if (remaining > 1e-6) {
|
||
throw new Error(`${row.item_name || sku} 扣库后仍缺 ${remaining}`);
|
||
}
|
||
}
|
||
|
||
await client.query(
|
||
`UPDATE inventory_reservations
|
||
SET status = 20, updated_at = NOW()
|
||
WHERE order_code = $1 AND status = 10`,
|
||
[ORDER]
|
||
);
|
||
console.log('OUTBOUND_OK', items.rows.length, 'lines');
|
||
} else {
|
||
console.log('OUTBOUND_SKIP already_outbound');
|
||
}
|
||
|
||
const taskCode = task.rows[0]?.task_code;
|
||
if (taskCode) {
|
||
await client.query(
|
||
`UPDATE delivery_tasks
|
||
SET task_status = GREATEST(task_status, 20),
|
||
start_time = COALESCE(start_time, NOW())
|
||
WHERE task_code = $1`,
|
||
[taskCode]
|
||
);
|
||
}
|
||
|
||
const upd = await client.query(
|
||
`UPDATE orders
|
||
SET order_status = 60, updated_at = NOW()
|
||
WHERE order_code = $1 AND order_status < 60
|
||
RETURNING order_code, order_status`,
|
||
[ORDER]
|
||
);
|
||
console.log('ORDER_STATUS', upd.rows[0] || order.rows[0]);
|
||
|
||
await client.query('COMMIT');
|
||
|
||
const after = await client.query(
|
||
`SELECT o.order_status, dt.task_status, dt.start_time::text,
|
||
(SELECT COALESCE(SUM(available_qty),0)::float FROM inventory
|
||
WHERE sku_code = $2 AND branch_code = $3) AS sku_avail,
|
||
(SELECT COUNT(*)::int FROM inventory_logs
|
||
WHERE related_order_code = $1 AND operation_type = 'delivery_loading_out') AS out_logs,
|
||
(SELECT COUNT(*)::int FROM inventory_logs
|
||
WHERE related_order_code = $1 AND operation_type = 'inspection_in'
|
||
AND sku_code = $2) AS in_logs
|
||
FROM orders o
|
||
LEFT JOIN delivery_tasks dt ON dt.order_code = o.order_code
|
||
WHERE o.order_code = $1`,
|
||
[ORDER, SKU, BRANCH]
|
||
);
|
||
console.log('FINAL', after.rows[0]);
|
||
} catch (e) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw e;
|
||
} finally {
|
||
client.release();
|
||
await pool.end();
|
||
}
|
||
}
|
||
|
||
main().catch((e) => {
|
||
console.error(e);
|
||
process.exit(1);
|
||
});
|