来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
285 lines
8.8 KiB
JavaScript
285 lines
8.8 KiB
JavaScript
/**
|
|
* 将历史「一单一条 purchase」按验收入账拆为 order+sku。
|
|
*
|
|
* 用法:
|
|
* node scripts/backfill-purchase-cost-by-inspection.cjs [--dry-run] [--cycle=202607]
|
|
*
|
|
* 默认读 server/.env 的 DATABASE_URL。
|
|
*/
|
|
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');
|
|
if (!fs.existsSync(envPath)) return null;
|
|
const text = fs.readFileSync(envPath, 'utf8');
|
|
const m = text.match(/^DATABASE_URL\s*=\s*(.+)$/m);
|
|
return m ? m[1].trim().replace(/^["']|["']$/g, '') : null;
|
|
}
|
|
|
|
const args = process.argv.slice(2);
|
|
const dryRun = args.includes('--dry-run');
|
|
const cycleArg = args.find((a) => a.startsWith('--cycle='));
|
|
const cycleFilter = cycleArg ? cycleArg.split('=')[1] : null;
|
|
|
|
function round2(n) {
|
|
return Math.round(Number(n || 0) * 100) / 100;
|
|
}
|
|
|
|
(async () => {
|
|
const databaseUrl = loadDatabaseUrl();
|
|
if (!databaseUrl) {
|
|
console.error('DATABASE_URL not found');
|
|
process.exit(1);
|
|
}
|
|
|
|
const c = new Client({ connectionString: databaseUrl });
|
|
await c.connect();
|
|
|
|
const before = await c.query(
|
|
`
|
|
SELECT order_code,
|
|
COUNT(*)::int AS purchase_rows,
|
|
SUM(amount)::numeric AS purchase_total,
|
|
array_agg(DISTINCT sku_code) AS sku_codes
|
|
FROM cost_details
|
|
WHERE cost_type = 'purchase'
|
|
AND ($1::text IS NULL OR cycle_code = $1)
|
|
GROUP BY order_code
|
|
ORDER BY order_code
|
|
`,
|
|
[cycleFilter]
|
|
);
|
|
|
|
console.log('=== Before: purchase by order ===');
|
|
console.log(JSON.stringify(before.rows, null, 2));
|
|
|
|
// 仅处理仍存在的订单(孤儿 purchase 在事务开头删除,不回填)
|
|
const orders = await c.query(
|
|
`
|
|
SELECT o.order_code, o.cycle_code, o.branch_code
|
|
FROM orders o
|
|
WHERE EXISTS (
|
|
SELECT 1 FROM cost_details cd
|
|
WHERE cd.order_code = o.order_code AND cd.cost_type = 'purchase'
|
|
AND ($1::text IS NULL OR cd.cycle_code = $1 OR o.cycle_code = $1)
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1 FROM inspections i
|
|
WHERE i.order_code = o.order_code
|
|
AND ($1::text IS NULL OR o.cycle_code = $1)
|
|
)
|
|
ORDER BY o.order_code
|
|
`,
|
|
[cycleFilter]
|
|
);
|
|
|
|
const report = {
|
|
dryRun,
|
|
cycleFilter,
|
|
ordersProcessed: 0,
|
|
rowsDeleted: 0,
|
|
rowsInserted: 0,
|
|
orphanPurchaseRemoved: 0,
|
|
diffs: [],
|
|
topSkuAfter: [],
|
|
};
|
|
|
|
if (!dryRun) await c.query('BEGIN');
|
|
|
|
try {
|
|
// 清理已删除订单的孤儿 purchase,避免 SKU 毛利/排行被虚增成本拉爆
|
|
const orphanDel = dryRun
|
|
? await c.query(
|
|
`SELECT COUNT(*)::int AS n FROM cost_details cd
|
|
WHERE cd.cost_type = 'purchase'
|
|
AND cd.order_code IS NOT NULL
|
|
AND ($1::text IS NULL OR cd.cycle_code = $1)
|
|
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code)`,
|
|
[cycleFilter]
|
|
)
|
|
: await c.query(
|
|
`DELETE FROM cost_details cd
|
|
WHERE cd.cost_type = 'purchase'
|
|
AND cd.order_code IS NOT NULL
|
|
AND ($1::text IS NULL OR cd.cycle_code = $1)
|
|
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code)
|
|
RETURNING id`,
|
|
[cycleFilter]
|
|
);
|
|
report.orphanPurchaseRemoved = dryRun
|
|
? Number(orphanDel.rows[0]?.n || 0)
|
|
: orphanDel.rowCount || 0;
|
|
if (dryRun) {
|
|
console.log('orphan purchase rows (would delete):', report.orphanPurchaseRemoved);
|
|
} else {
|
|
report.rowsDeleted += report.orphanPurchaseRemoved;
|
|
console.log('orphan purchase rows deleted:', report.orphanPurchaseRemoved);
|
|
}
|
|
|
|
for (const order of orders.rows) {
|
|
const orderCode = order.order_code;
|
|
const cycleCode = String(order.cycle_code || '').trim();
|
|
const branchCode = order.branch_code || null;
|
|
|
|
const oldPurchase = await c.query(
|
|
`SELECT COALESCE(SUM(amount), 0)::numeric AS amt, COUNT(*)::int AS n
|
|
FROM cost_details WHERE order_code = $1 AND cost_type = 'purchase'`,
|
|
[orderCode]
|
|
);
|
|
const oldAmt = round2(oldPurchase.rows[0]?.amt);
|
|
|
|
const bySku = await c.query(
|
|
`
|
|
SELECT i.sku_code,
|
|
ROUND(SUM(COALESCE(i.actual_qty, 0) * COALESCE(i.purchase_price, 0))::numeric, 2) AS amt
|
|
FROM inspections i
|
|
WHERE i.order_code = $1
|
|
AND i.sku_code IS NOT NULL AND TRIM(i.sku_code) <> ''
|
|
AND COALESCE(i.actual_qty, 0) > 0
|
|
AND COALESCE(i.purchase_price, 0) > 0
|
|
GROUP BY i.sku_code
|
|
HAVING SUM(COALESCE(i.actual_qty, 0) * COALESCE(i.purchase_price, 0)) > 0
|
|
`,
|
|
[orderCode]
|
|
);
|
|
|
|
let skuRows = bySku.rows.map((r) => ({
|
|
sku_code: String(r.sku_code),
|
|
amount: round2(r.amt),
|
|
}));
|
|
|
|
if (skuRows.length === 0) {
|
|
const prep = await c.query(
|
|
`
|
|
SELECT sp.sku_code,
|
|
ROUND(SUM(COALESCE(sp.prepare_qty, 0) * COALESCE(sp.purchase_price, 0))::numeric, 2) AS amt
|
|
FROM supplier_preparations sp
|
|
WHERE sp.order_code = $1
|
|
AND COALESCE(sp.is_stockout, false) = false
|
|
AND COALESCE(sp.transferred_to_purchase, false) = false
|
|
AND sp.sku_code IS NOT NULL AND TRIM(sp.sku_code) <> ''
|
|
GROUP BY sp.sku_code
|
|
HAVING SUM(COALESCE(sp.prepare_qty, 0) * COALESCE(sp.purchase_price, 0)) > 0
|
|
`,
|
|
[orderCode]
|
|
);
|
|
skuRows = prep.rows.map((r) => ({
|
|
sku_code: String(r.sku_code),
|
|
amount: round2(r.amt),
|
|
}));
|
|
}
|
|
|
|
if (skuRows.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
const newAmt = round2(skuRows.reduce((s, r) => s + r.amount, 0));
|
|
|
|
if (!dryRun) {
|
|
const del = await c.query(
|
|
`DELETE FROM cost_details WHERE order_code = $1 AND cost_type = 'purchase' RETURNING id`,
|
|
[orderCode]
|
|
);
|
|
report.rowsDeleted += del.rowCount || 0;
|
|
|
|
for (const row of skuRows) {
|
|
// 取该 SKU 任一验收 id 作为 reference(可空)
|
|
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, row.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,
|
|
row.amount,
|
|
branchCode,
|
|
row.sku_code,
|
|
ref.rows[0]?.id || null,
|
|
]
|
|
);
|
|
report.rowsInserted += 1;
|
|
}
|
|
}
|
|
|
|
report.ordersProcessed += 1;
|
|
report.diffs.push({
|
|
order_code: orderCode,
|
|
old_purchase_total: oldAmt,
|
|
new_purchase_total: newAmt,
|
|
delta: round2(newAmt - oldAmt),
|
|
sku_count: skuRows.length,
|
|
});
|
|
}
|
|
|
|
if (!dryRun) await c.query('COMMIT');
|
|
} catch (e) {
|
|
if (!dryRun) await c.query('ROLLBACK');
|
|
throw e;
|
|
}
|
|
|
|
const afterPurchase = await c.query(
|
|
`
|
|
SELECT cd.sku_code, s.sku_name, SUM(cd.amount)::numeric AS purchase_cost
|
|
FROM cost_details cd
|
|
LEFT JOIN skus s ON s.sku_code = cd.sku_code
|
|
WHERE cd.cost_type = 'purchase'
|
|
AND ($1::text IS NULL OR cd.cycle_code = $1)
|
|
AND cd.sku_code IS NOT NULL
|
|
GROUP BY cd.sku_code, s.sku_name
|
|
ORDER BY SUM(cd.amount) DESC
|
|
LIMIT 10
|
|
`,
|
|
[cycleFilter]
|
|
);
|
|
report.topSkuAfter = afterPurchase.rows;
|
|
|
|
const afterOrders = await c.query(
|
|
`
|
|
SELECT order_code, COUNT(*)::int AS purchase_rows, SUM(amount)::numeric AS purchase_total
|
|
FROM cost_details
|
|
WHERE cost_type = 'purchase' AND ($1::text IS NULL OR cycle_code = $1)
|
|
GROUP BY order_code
|
|
ORDER BY order_code
|
|
`,
|
|
[cycleFilter]
|
|
);
|
|
|
|
console.log('\n=== Diffs (order totals) ===');
|
|
console.log(JSON.stringify(report.diffs, null, 2));
|
|
console.log('\n=== After: purchase by order ===');
|
|
console.log(JSON.stringify(afterOrders.rows, null, 2));
|
|
console.log('\n=== Top SKU purchase after ===');
|
|
console.log(JSON.stringify(report.topSkuAfter, null, 2));
|
|
console.log('\n=== Summary ===');
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
dryRun: report.dryRun,
|
|
cycleFilter: report.cycleFilter,
|
|
ordersProcessed: report.ordersProcessed,
|
|
rowsDeleted: report.rowsDeleted,
|
|
rowsInserted: report.rowsInserted,
|
|
orphanPurchaseRemoved: report.orphanPurchaseRemoved,
|
|
},
|
|
null,
|
|
2
|
|
)
|
|
);
|
|
|
|
await c.end();
|
|
})().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|