来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
319 lines
12 KiB
JavaScript
319 lines
12 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 全量订单明细履约覆盖修复。
|
||
*
|
||
* 默认 dry-run:
|
||
* node scripts/prod-repair-order-item-fulfillment.cjs
|
||
* 显式执行:
|
||
* node scripts/prod-repair-order-item-fulfillment.cjs --apply
|
||
*
|
||
* 已完成订单只补 is_history_repair=true 的关闭记录;未完成订单补正常待办。
|
||
*/
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
|
||
function loadDotEnv(file) {
|
||
if (!fs.existsSync(file)) return;
|
||
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
||
const match = line.match(/^([A-Z0-9_]+)=(.*)$/);
|
||
if (!match || process.env[match[1]]) continue;
|
||
process.env[match[1]] = match[2].trim().replace(/^["']|["']$/g, '');
|
||
}
|
||
}
|
||
|
||
function newCode(prefix) {
|
||
return `${prefix}${Date.now()}${Math.random().toString(36).slice(2, 7).toUpperCase()}`;
|
||
}
|
||
|
||
async function main() {
|
||
loadDotEnv(path.join(process.cwd(), 'server', '.env'));
|
||
loadDotEnv(path.join(process.cwd(), '.env'));
|
||
loadDotEnv('/opt/ai-fresh-delivery/server/.env');
|
||
if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL 未配置');
|
||
|
||
const { Pool } = require('pg');
|
||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||
const apply = process.argv.includes('--apply');
|
||
const summary = {
|
||
mode: apply ? 'apply' : 'dry-run',
|
||
scanned: 0,
|
||
linkedPurchase: 0,
|
||
linkedPreparation: 0,
|
||
createdPurchase: 0,
|
||
createdPreparation: 0,
|
||
blocked: [],
|
||
};
|
||
|
||
try {
|
||
const schema = await pool.query(
|
||
`SELECT to_regclass('public.order_item_fulfillments') AS table_name`
|
||
);
|
||
if (!schema.rows[0]?.table_name) {
|
||
throw new Error('请先执行迁移 20260768_order_item_fulfillment_links.sql');
|
||
}
|
||
|
||
const gaps = await pool.query(
|
||
`SELECT oi.id::text AS id, oi.order_code, oi.sku_code, oi.item_name,
|
||
oi.quantity, oi.unit, oi.price, oi.supplier_code, oi.branch_code,
|
||
o.order_status, o.updated_at
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code
|
||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = oi.id
|
||
LEFT JOIN supplier_preparations sp ON sp.id = f.supplier_preparation_id
|
||
LEFT JOIN purchase_orders po ON po.purchase_code = f.purchase_code
|
||
WHERE NOT (
|
||
(
|
||
f.supplier_preparation_id IS NOT NULL
|
||
AND sp.id IS NOT NULL
|
||
AND COALESCE(sp.is_stockout, false) = false
|
||
AND COALESCE(sp.transferred_to_purchase, false) = false
|
||
)
|
||
OR (
|
||
f.purchase_code IS NOT NULL
|
||
AND po.purchase_code IS NOT NULL
|
||
AND po.purchase_status < 80
|
||
AND po.purchase_status <> 40
|
||
)
|
||
)
|
||
ORDER BY o.order_status ASC, oi.order_code ASC, oi.sort_order ASC NULLS LAST`
|
||
);
|
||
|
||
for (const item of gaps.rows) {
|
||
summary.scanned += 1;
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
|
||
// 1. 精确 source_id 自采,或缺货备货转出的自采。
|
||
const purchase = await client.query(
|
||
`SELECT po.purchase_code
|
||
FROM purchase_orders po
|
||
WHERE po.order_code = $1
|
||
AND po.purchase_status < 80
|
||
AND po.purchase_status <> 40
|
||
AND (
|
||
po.source_id = $2
|
||
OR po.source_id IN (
|
||
SELECT sp.id::text
|
||
FROM supplier_preparations sp
|
||
WHERE sp.order_code = $1
|
||
AND sp.sku_code IS NOT DISTINCT FROM $3
|
||
AND sp.supplier_code IS NOT DISTINCT FROM $4
|
||
)
|
||
)
|
||
ORDER BY po.created_at DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[item.order_code, item.id, item.sku_code, item.supplier_code]
|
||
);
|
||
if (purchase.rowCount) {
|
||
summary.linkedPurchase += 1;
|
||
if (apply) {
|
||
await client.query(
|
||
`INSERT INTO order_item_fulfillments
|
||
(order_item_id, order_code, purchase_code, updated_at)
|
||
VALUES ($1::uuid, $2, $3, NOW())
|
||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||
supplier_preparation_id = NULL,
|
||
purchase_code = EXCLUDED.purchase_code,
|
||
updated_at = NOW()`,
|
||
[item.id, item.order_code, purchase.rows[0].purchase_code]
|
||
);
|
||
}
|
||
await client.query(apply ? 'COMMIT' : 'ROLLBACK');
|
||
continue;
|
||
}
|
||
|
||
// 2. 有效聚合备货。
|
||
const prep = await client.query(
|
||
`SELECT id
|
||
FROM supplier_preparations
|
||
WHERE order_code = $1
|
||
AND sku_code IS NOT DISTINCT FROM $2
|
||
AND supplier_code IS NOT DISTINCT FROM $3
|
||
AND COALESCE(is_stockout, false) = false
|
||
AND COALESCE(transferred_to_purchase, false) = false
|
||
ORDER BY created_at ASC
|
||
LIMIT 1`,
|
||
[item.order_code, item.sku_code, item.supplier_code]
|
||
);
|
||
if (prep.rowCount) {
|
||
summary.linkedPreparation += 1;
|
||
if (apply) {
|
||
await client.query(
|
||
`INSERT INTO order_item_fulfillments
|
||
(order_item_id, order_code, supplier_preparation_id, updated_at)
|
||
VALUES ($1::uuid, $2, $3::uuid, NOW())
|
||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||
supplier_preparation_id = EXCLUDED.supplier_preparation_id,
|
||
purchase_code = NULL,
|
||
updated_at = NOW()`,
|
||
[item.id, item.order_code, prep.rows[0].id]
|
||
);
|
||
}
|
||
await client.query(apply ? 'COMMIT' : 'ROLLBACK');
|
||
continue;
|
||
}
|
||
|
||
const completed = Number(item.order_status) >= 90;
|
||
const supplierCode = String(item.supplier_code || '').trim();
|
||
|
||
if (supplierCode && item.sku_code) {
|
||
const existingPrep = await client.query(
|
||
`SELECT id FROM supplier_preparations
|
||
WHERE order_code = $1 AND sku_code = $2 AND supplier_code = $3
|
||
ORDER BY created_at ASC LIMIT 1`,
|
||
[item.order_code, item.sku_code, supplierCode]
|
||
);
|
||
const preparationId = existingPrep.rows[0]?.id || null;
|
||
summary.createdPreparation += preparationId ? 0 : 1;
|
||
summary.linkedPreparation += preparationId ? 1 : 0;
|
||
if (apply) {
|
||
let id = preparationId;
|
||
if (id) {
|
||
await client.query(
|
||
`UPDATE supplier_preparations
|
||
SET prepare_qty = GREATEST(COALESCE(prepare_qty, 0), $2),
|
||
prepare_status = $3,
|
||
is_stockout = false,
|
||
transferred_to_purchase = false,
|
||
stockout_reason = NULL,
|
||
is_history_repair = $4,
|
||
prepare_time = CASE WHEN $4 THEN COALESCE(prepare_time, $5, NOW()) ELSE prepare_time END
|
||
WHERE id = $1`,
|
||
[
|
||
id,
|
||
Number(item.quantity) || 0,
|
||
completed ? 30 : 10,
|
||
completed,
|
||
item.updated_at,
|
||
]
|
||
);
|
||
} else {
|
||
const inserted = await client.query(
|
||
`INSERT INTO supplier_preparations (
|
||
order_code, supplier_code, sku_code, item_name, prepare_qty,
|
||
purchase_price, prepare_status, branch_code, unit, prepare_time,
|
||
is_history_repair, is_stockout, transferred_to_purchase
|
||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,false,false)
|
||
RETURNING id`,
|
||
[
|
||
item.order_code,
|
||
supplierCode,
|
||
item.sku_code,
|
||
item.item_name,
|
||
Number(item.quantity) || 0,
|
||
Number(item.price) || 0,
|
||
completed ? 30 : 10,
|
||
item.branch_code,
|
||
item.unit,
|
||
completed ? item.updated_at || new Date() : null,
|
||
completed,
|
||
]
|
||
);
|
||
id = inserted.rows[0].id;
|
||
}
|
||
await client.query(
|
||
`INSERT INTO order_item_fulfillments
|
||
(order_item_id, order_code, supplier_preparation_id, updated_at)
|
||
VALUES ($1::uuid,$2,$3::uuid,NOW())
|
||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||
supplier_preparation_id=EXCLUDED.supplier_preparation_id,
|
||
purchase_code=NULL,
|
||
updated_at=NOW()`,
|
||
[item.id, item.order_code, id]
|
||
);
|
||
}
|
||
await client.query(apply ? 'COMMIT' : 'ROLLBACK');
|
||
continue;
|
||
}
|
||
|
||
const purchaser = await client.query(
|
||
`SELECT pu.purchaser_code, pu.purchaser_name
|
||
FROM purchaser_users pu
|
||
LEFT JOIN profiles p ON p.id = pu.user_id
|
||
WHERE pu.status = 1
|
||
AND (p.branch_code = $1 OR p.branch_code IS NULL)
|
||
ORDER BY CASE WHEN p.branch_code = $1 THEN 0 ELSE 1 END,
|
||
pu.is_primary DESC NULLS LAST, pu.created_at ASC
|
||
LIMIT 1`,
|
||
[item.branch_code]
|
||
);
|
||
if (!purchaser.rowCount && !completed) {
|
||
summary.blocked.push({
|
||
order_code: item.order_code,
|
||
order_item_id: item.id,
|
||
reason: '未配置采购员',
|
||
});
|
||
await client.query('ROLLBACK');
|
||
continue;
|
||
}
|
||
|
||
summary.createdPurchase += 1;
|
||
if (apply) {
|
||
const purchaseCode = newCode(completed ? 'HISTPUR' : 'REPAIRPUR');
|
||
await client.query(
|
||
`INSERT INTO purchase_orders (
|
||
purchase_code, order_code, sku_code, supplier_code,
|
||
purchaser_code, purchaser_name, purchase_qty, purchase_price,
|
||
purchase_status, is_temporary_supplier, source_type, source_id,
|
||
remark, branch_code, is_history_repair
|
||
) VALUES ($1,$2,$3,NULL,$4,$5,$6,$7,$8,false,$9,$10,$11,$12,$13)`,
|
||
[
|
||
purchaseCode,
|
||
item.order_code,
|
||
item.sku_code,
|
||
purchaser.rows[0]?.purchaser_code || 'HISTORY_REPAIR',
|
||
purchaser.rows[0]?.purchaser_name || '历史修复',
|
||
Number(item.quantity) || 0,
|
||
Number(item.price) || 0,
|
||
completed ? 30 : 10,
|
||
completed ? 'history_repair' : 'coverage_repair',
|
||
item.id,
|
||
completed ? '历史订单履约覆盖修复(关闭记录)' : '订单明细履约覆盖修复',
|
||
item.branch_code,
|
||
completed,
|
||
]
|
||
);
|
||
await client.query(
|
||
`INSERT INTO order_item_fulfillments
|
||
(order_item_id, order_code, purchase_code, updated_at)
|
||
VALUES ($1::uuid,$2,$3,NOW())
|
||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||
supplier_preparation_id=NULL,
|
||
purchase_code=EXCLUDED.purchase_code,
|
||
updated_at=NOW()`,
|
||
[item.id, item.order_code, purchaseCode]
|
||
);
|
||
}
|
||
await client.query(apply ? 'COMMIT' : 'ROLLBACK');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
summary.blocked.push({
|
||
order_code: item.order_code,
|
||
order_item_id: item.id,
|
||
reason: error.message,
|
||
});
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
const remaining = await pool.query(
|
||
`SELECT COUNT(*)::int AS count
|
||
FROM order_items oi
|
||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = oi.id
|
||
WHERE f.order_item_id IS NULL`
|
||
);
|
||
summary.remainingUnlinked = Number(remaining.rows[0]?.count) || 0;
|
||
console.log(JSON.stringify(summary, null, 2));
|
||
if (apply && summary.blocked.length) process.exitCode = 2;
|
||
} finally {
|
||
await pool.end();
|
||
}
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error.message || error);
|
||
process.exit(1);
|
||
});
|