Files
SupplierSystem/server/scripts/repair-returned-line-inbound.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库: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 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

168 lines
7.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 存量修复:因「退货红冲行的入库被当成新行已入库」而被错误关单(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<Target>(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);
}
);