Files
SupplierSystem/scripts/backfill-purchase-ledger-from-unit-cost.cjs
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

138 lines
5.1 KiB
JavaScript
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.
/**
* 一套账 9丙:有 unit_cost、缺采购账本行 → 补 purchase;
* 有采购行 → 用账本金额反写 unit_cost(按 qty 均摊单价)。
*
* 用法(在 server 目录或根目录,需 DATABASE_URL):
* node scripts/backfill-purchase-ledger-from-unit-cost.cjs [--dry-run] [--branch=CODE]
*/
/* eslint-disable no-console */
const path = require('path');
const fs = require('fs');
const { Client } = require('pg');
function loadEnv() {
const candidates = [
path.join(__dirname, '../server/.env'),
path.join(__dirname, '../.env'),
];
for (const p of candidates) {
if (!fs.existsSync(p)) continue;
for (const line of fs.readFileSync(p, 'utf8').split(/\r?\n/)) {
const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
if (!m || process.env[m[1]]) continue;
let v = m[2].trim();
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
v = v.slice(1, -1);
}
process.env[m[1]] = v;
}
}
}
async function main() {
loadEnv();
const dryRun = process.argv.includes('--dry-run');
const branchArg = process.argv.find((a) => a.startsWith('--branch='));
const branch = branchArg ? branchArg.slice('--branch='.length).trim() : '';
const url = process.env.ADMIN_DATABASE_URL || process.env.DATABASE_URL;
if (!url) {
console.error('缺少 DATABASE_URL');
process.exit(1);
}
const client = new Client({ connectionString: url });
await client.connect();
const branchSql = branch ? 'AND o.branch_code = $1' : '';
const params = branch ? [branch] : [];
// 9甲:有 unit_cost 合计金额、无非加菜 purchase 行 → 补行
const missing = await client.query(
`SELECT o.order_code, oi.sku_code, o.cycle_code, o.branch_code,
SUM(COALESCE(oi.quantity,0))::numeric AS qty,
SUM(COALESCE(oi.quantity,0) * COALESCE(oi.unit_cost,0))::numeric AS amt
FROM orders o
JOIN order_items oi ON oi.order_code = o.order_code
WHERE o.deleted_at IS NULL
AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> ''
AND COALESCE(oi.unit_cost, 0) > 0
${branchSql}
AND NOT EXISTS (
SELECT 1 FROM cost_details cd
WHERE cd.order_code = o.order_code AND cd.cost_type = 'purchase'
AND cd.sku_code = oi.sku_code
AND COALESCE(cd.cost_source, '') IS DISTINCT FROM 'extra_dish'
)
GROUP BY o.order_code, oi.sku_code, o.cycle_code, o.branch_code
HAVING SUM(COALESCE(oi.quantity,0) * COALESCE(oi.unit_cost,0)) > 0`,
params
);
console.log(`补采购行候选: ${missing.rowCount}${dryRun ? ' (dry-run)' : ''}`);
let inserted = 0;
if (!dryRun) {
for (const row of missing.rows) {
const cycle =
String(row.cycle_code || '').trim() ||
`${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}`;
const amt = Math.round(Number(row.amt || 0) * 100) / 100;
try {
await client.query(
`INSERT INTO cost_details (
cycle_code, cost_type, cost_subtype, amount, order_code, sku_code,
allocation_method, allocated_amount, status, branch_code, cost_source, remark
) VALUES ($1, 'purchase', 'order_goods', $2, $3, $4, 'sku', $2, 20, $5, 'supplier', 'backfill_unit_cost')`,
[cycle, amt, row.order_code, row.sku_code, row.branch_code]
);
inserted += 1;
} catch (e) {
if (e.code !== '23505') console.error(row.order_code, row.sku_code, e.message);
}
}
}
// 9乙:有采购行 → 回写 unit_cost = amount/qty
const rewrite = await client.query(
`SELECT cd.order_code, cd.sku_code,
SUM(COALESCE(cd.amount,0))::numeric AS amt,
(
SELECT COALESCE(SUM(COALESCE(oi.quantity,0)),0)
FROM order_items oi
WHERE oi.order_code = cd.order_code AND oi.sku_code = cd.sku_code
)::numeric AS qty
FROM cost_details cd
JOIN orders o ON o.order_code = cd.order_code AND o.deleted_at IS NULL
WHERE cd.cost_type = 'purchase'
AND cd.sku_code IS NOT NULL AND TRIM(cd.sku_code) <> ''
AND COALESCE(cd.cost_source, '') IS DISTINCT FROM 'extra_dish'
${branchSql.replace(/o\.branch_code/g, 'o.branch_code')}
GROUP BY cd.order_code, cd.sku_code
HAVING SUM(COALESCE(cd.amount,0)) > 0`,
params
);
console.log(`回写 unit_cost 候选: ${rewrite.rowCount}${dryRun ? ' (dry-run)' : ''}`);
let updated = 0;
if (!dryRun) {
for (const row of rewrite.rows) {
const qty = Number(row.qty) || 0;
if (!(qty > 0)) continue;
const unit = Math.round((Number(row.amt) / qty) * 10000) / 10000;
const r = await client.query(
`UPDATE order_items SET unit_cost = $1::numeric
WHERE order_code = $2 AND sku_code = $3
AND COALESCE(unit_cost,0) IS DISTINCT FROM $1::numeric`,
[unit, row.order_code, row.sku_code]
);
updated += r.rowCount || 0;
}
}
console.log(JSON.stringify({ dryRun, branch: branch || null, inserted, unitCostRowsTouched: updated }, null, 2));
await client.end();
}
main().catch((e) => {
console.error(e);
process.exit(1);
});