Files
SupplierSystem/scripts/repair-purchase-from-latest-inspection.cjs
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

148 lines
5.1 KiB
JavaScript

/**
* 按「订单+SKU 最近一次验收」重写 purchase 金额,消除重复验收累加。
* 若仍是一单一条 purchase,则按整单各 SKU 最近一次之和覆盖。
*
* node scripts/repair-purchase-from-latest-inspection.cjs [--dry-run] [--cycle=202607]
*/
const fs = require('fs');
const path = require('path');
const { Client } = require('../server/node_modules/pg');
function loadDatabaseUrl() {
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
const envPath = path.join(__dirname, '..', 'server', '.env');
const text = fs.readFileSync(envPath, 'utf8');
const m = text.match(/^DATABASE_URL\s*=\s*(.+)$/m);
return m ? m[1].trim().replace(/^["']|["']$/g, '') : null;
}
function r2(n) {
return Math.round(Number(n || 0) * 100) / 100;
}
const dryRun = process.argv.includes('--dry-run');
const cycleArg = process.argv.find((a) => a.startsWith('--cycle='));
const cycleFilter = cycleArg ? cycleArg.split('=')[1] : null;
(async () => {
const c = new Client({ connectionString: loadDatabaseUrl() });
await c.connect();
const orders = await c.query(
`
SELECT DISTINCT cd.order_code, o.cycle_code AS order_cycle, o.branch_code
FROM cost_details cd
JOIN orders o ON o.order_code = cd.order_code
WHERE cd.cost_type = 'purchase'
AND ($1::text IS NULL OR cd.cycle_code = $1 OR o.cycle_code = $1)
ORDER BY cd.order_code
`,
[cycleFilter]
);
let updated = 0;
let splitInserted = 0;
const diffs = [];
if (!dryRun) await c.query('BEGIN');
try {
for (const order of orders.rows) {
const orderCode = order.order_code;
const cycleCode = String(order.order_cycle || '').trim() || '202607';
const branchCode = order.branch_code || null;
const old = await c.query(
`SELECT id, sku_code, amount FROM cost_details
WHERE order_code = $1 AND cost_type = 'purchase'`,
[orderCode]
);
const oldTotal = r2(old.rows.reduce((s, r) => s + Number(r.amount || 0), 0));
const latestLines = await c.query(
`
SELECT DISTINCT ON (sku_code)
sku_code,
ROUND((COALESCE(actual_qty, 0) * COALESCE(purchase_price, 0))::numeric, 2) AS amt
FROM inspections
WHERE order_code = $1
AND sku_code IS NOT NULL AND TRIM(sku_code) <> ''
AND COALESCE(actual_qty, 0) > 0
AND COALESCE(purchase_price, 0) > 0
ORDER BY sku_code, inspection_time DESC NULLS LAST, created_at DESC, id DESC
`,
[orderCode]
);
if (!latestLines.rows.length) continue;
const newTotal = r2(latestLines.rows.reduce((s, r) => s + Number(r.amt || 0), 0));
const perSkuIndexExists = await c.query(
`SELECT 1 FROM pg_indexes WHERE indexname = 'uq_cost_details_purchase_order_sku' LIMIT 1`
);
const canSplit = Boolean(perSkuIndexExists.rowCount);
if (!dryRun) {
if (canSplit) {
await c.query(`DELETE FROM cost_details WHERE order_code = $1 AND cost_type = 'purchase'`, [
orderCode,
]);
for (const line of latestLines.rows) {
const ref = await c.query(
`SELECT id::text AS id FROM inspections
WHERE order_code = $1 AND sku_code = $2
ORDER BY inspection_time DESC NULLS LAST, created_at DESC
LIMIT 1`,
[orderCode, line.sku_code]
);
await c.query(
`INSERT INTO cost_details (
cycle_code, order_code, cost_type, cost_subtype, amount, status,
branch_code, sku_code, reference_type, reference_id, allocation_method, allocated_amount
) VALUES ($1,$2,'purchase','inspection_inbound',$3,10,$4,$5,'inspection',$6,'sku',$3)`,
[cycleCode, orderCode, Number(line.amt), branchCode, line.sku_code, ref.rows[0]?.id || null]
);
splitInserted += 1;
}
} else if (old.rows.length === 1) {
await c.query(
`UPDATE cost_details SET amount = $2, cycle_code = $3, cost_subtype = 'inspection_inbound'
WHERE id = $1`,
[old.rows[0].id, newTotal, cycleCode]
);
updated += 1;
} else {
for (const row of old.rows) {
const sku = String(row.sku_code || '').trim();
const match = latestLines.rows.find((l) => l.sku_code === sku);
if (!match) continue;
await c.query(`UPDATE cost_details SET amount = $2, cycle_code = $3 WHERE id = $1`, [
row.id,
Number(match.amt),
cycleCode,
]);
updated += 1;
}
}
}
diffs.push({
order_code: orderCode,
old_total: oldTotal,
new_total: newTotal,
delta: r2(newTotal - oldTotal),
sku_count: latestLines.rows.length,
});
}
if (!dryRun) await c.query('COMMIT');
} catch (e) {
if (!dryRun) await c.query('ROLLBACK');
throw e;
}
console.log(JSON.stringify({ dryRun, cycleFilter, updated, splitInserted, diffs }, null, 2));
await c.end();
})().catch((e) => {
console.error(e);
process.exit(1);
});