来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
231 lines
9.8 KiB
TypeScript
231 lines
9.8 KiB
TypeScript
/**
|
||
* 供应商结算头金额口径修复(**数据修复脚本**):
|
||
* 步骤 1:把「纯行级扣量」从表头 `deduction_amount` 摘出来(还原应付)
|
||
* 步骤 2:重算未结清行的 `unpaid_amount`(待付 = 应付 − 已付)
|
||
*
|
||
* 与迁移 `migrations/20260922_supplier_statement_amount_caliber.sql` 同一口径;
|
||
* 本脚本用于**预览(默认 dry-run)**与本地执行,生产走迁移。
|
||
*
|
||
* ⚠️ 只允许对本地库运行(脚本会拒绝非 localhost 的 DATABASE_URL)。
|
||
* 运行(server 目录):
|
||
* npm run repair:supplier-statement-amounts # 预览(不写)
|
||
* npm run repair:supplier-statement-amounts -- --execute # 本地执行
|
||
* npm run repair:supplier-statement-amounts -- --branch br002
|
||
*
|
||
* 设计:docs/design/20260922-supplier-statement-payable-caliber.md
|
||
*/
|
||
import pg from 'pg';
|
||
|
||
const { Pool } = pg;
|
||
const LOCAL_HOSTS = ['127.0.0.1', 'localhost', '::1'];
|
||
const round2 = (n: number) => Math.round(n * 100) / 100;
|
||
const money = (n: number | null | undefined) =>
|
||
n == null ? '—' : Number(n).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||
|
||
type Args = { execute: boolean; branches: string[] };
|
||
function parseArgs(argv: string[]): Args {
|
||
const out: Args = { execute: false, branches: [] };
|
||
for (let i = 0; i < argv.length; i += 1) {
|
||
const [flag, value] = [argv[i], argv[i + 1]];
|
||
if (flag === '--execute') out.execute = true;
|
||
if (flag === '--branch' && value) out.branches.push(value.trim().toLowerCase());
|
||
}
|
||
return out;
|
||
}
|
||
|
||
type Step1Row = {
|
||
schema: string;
|
||
statement_no: string;
|
||
cycle_code: string;
|
||
deduction_before: string;
|
||
payable_before: string;
|
||
unpaid_before: string | null;
|
||
net: string;
|
||
paid: string;
|
||
payable_after: number;
|
||
unpaid_after: number;
|
||
};
|
||
|
||
const STEP1_SELECT = (schema: string) => `
|
||
SELECT ss.statement_no, ss.cycle_code,
|
||
ss.deduction_amount AS deduction_before,
|
||
ss.payable_amount AS payable_before,
|
||
ss.unpaid_amount AS unpaid_before,
|
||
COALESCE(ss.paid_amount, 0)::numeric AS paid,
|
||
COALESCE(l.net, 0)::numeric AS net
|
||
FROM ${schema}.supplier_statements ss
|
||
JOIN (
|
||
SELECT statement_no,
|
||
COALESCE(SUM(line_amount) FILTER (WHERE line_counted), 0)::numeric AS net,
|
||
COALESCE(SUM(deduction_amount) FILTER (WHERE line_counted), 0)::numeric AS line_ded,
|
||
COUNT(*) FILTER (WHERE line_counted)::int AS live_lines
|
||
FROM (
|
||
SELECT sl.statement_no, sl.line_amount, sl.deduction_amount,
|
||
(COALESCE(sl.is_voided, false) = false
|
||
AND (sl.order_code IS NULL
|
||
OR EXISTS (SELECT 1 FROM ${schema}.orders o
|
||
WHERE o.order_code = sl.order_code AND o.deleted_at IS NULL))) AS line_counted
|
||
FROM ${schema}.statement_lines sl
|
||
WHERE sl.statement_type = 'supplier'
|
||
) t
|
||
GROUP BY statement_no
|
||
) l ON l.statement_no = ss.statement_no
|
||
WHERE l.live_lines > 0
|
||
AND COALESCE(ss.deduction_amount, 0) > 0
|
||
AND ABS(COALESCE(ss.deduction_amount, 0) - l.line_ded) < 0.005
|
||
AND COALESCE(ss.statement_status, 0) < 30
|
||
ORDER BY ss.cycle_code, ss.statement_no`;
|
||
|
||
const STEP2_SELECT = (schema: string) => `
|
||
SELECT ss.statement_no, ss.cycle_code,
|
||
ss.payable_amount AS payable_before,
|
||
ss.unpaid_amount AS unpaid_before,
|
||
COALESCE(ss.paid_amount, 0)::numeric AS paid,
|
||
GREATEST(0, ROUND(COALESCE(ss.payable_amount, ss.total_amount, 0) - COALESCE(ss.paid_amount, 0), 2)) AS unpaid_after
|
||
FROM ${schema}.supplier_statements ss
|
||
WHERE COALESCE(ss.statement_status, 0) < 30
|
||
AND ss.unpaid_amount IS DISTINCT FROM GREATEST(
|
||
0, ROUND(COALESCE(ss.payable_amount, ss.total_amount, 0) - COALESCE(ss.paid_amount, 0), 2)
|
||
)
|
||
ORDER BY ss.cycle_code, ss.statement_no`;
|
||
|
||
async function main() {
|
||
const args = parseArgs(process.argv.slice(2));
|
||
const url = String(process.env.DATABASE_URL || '');
|
||
if (!url) throw new Error('缺少 DATABASE_URL(用 --env-file=.env 运行)');
|
||
const host = (() => {
|
||
try {
|
||
return new URL(url).hostname;
|
||
} catch {
|
||
return '';
|
||
}
|
||
})();
|
||
if (!LOCAL_HOSTS.includes(host)) {
|
||
throw new Error(`拒绝运行:DATABASE_URL 指向非本地库 (${host || 'unknown'})。生产请走迁移。`);
|
||
}
|
||
|
||
const pool = new Pool({ connectionString: url, statement_timeout: 60000 });
|
||
const client = await pool.connect();
|
||
try {
|
||
const schemas = (
|
||
await client.query(
|
||
`SELECT nspname FROM pg_namespace
|
||
WHERE (nspname LIKE 'tenant\\_%' OR nspname IN ('tenant_template'))
|
||
ORDER BY 1`
|
||
)
|
||
).rows
|
||
.map((r: any) => String(r.nspname))
|
||
.filter((s) => (args.branches.length ? args.branches.includes(s.replace(/^tenant_/, '')) : true));
|
||
|
||
console.log(`模式:${args.execute ? '**执行**(会写库)' : '预览(不写)'} 库:${host} schema:${schemas.join(', ')}`);
|
||
let total1 = 0;
|
||
let total2 = 0;
|
||
|
||
for (const schema of schemas) {
|
||
const cols = async (table: string, col: string) =>
|
||
(
|
||
await client.query(
|
||
`SELECT 1 FROM information_schema.columns WHERE table_schema=$1 AND table_name=$2 AND column_name=$3`,
|
||
[schema, table, col]
|
||
)
|
||
).rowCount === 1;
|
||
|
||
const headOk = (await cols('supplier_statements', 'unpaid_amount')) &&
|
||
(await cols('supplier_statements', 'deduction_amount')) &&
|
||
(await cols('supplier_statements', 'payable_amount'));
|
||
if (!headOk) {
|
||
console.log(`\n[${schema}] 跳过:表或缺列`);
|
||
continue;
|
||
}
|
||
const step1Ok = headOk && (await cols('statement_lines', 'deduction_amount')) && (await cols('statement_lines', 'is_voided'));
|
||
|
||
await client.query('BEGIN');
|
||
try {
|
||
if (step1Ok) {
|
||
const rows = (await client.query(STEP1_SELECT(schema))).rows as any[];
|
||
console.log(`\n[${schema}] 步骤 1:还原纯行级扣量的表头 ${rows.length} 行(合计扣款 ${money(rows.reduce((s, r) => s + Number(r.deduction_before || 0), 0))})`);
|
||
for (const r of rows) {
|
||
const payableAfter = round2(Number(r.net));
|
||
const unpaidAfter = round2(Math.max(0, payableAfter - Number(r.paid || 0)));
|
||
console.log(
|
||
` ${r.statement_no} (${r.cycle_code}) 扣款 ${money(r.deduction_before)}→0 应付 ${money(r.payable_before)}→${money(payableAfter)} 待付 ${money(r.unpaid_before)}→${money(unpaidAfter)}`
|
||
);
|
||
}
|
||
if (args.execute && rows.length) {
|
||
const res = await client.query(`
|
||
WITH line_agg AS (
|
||
SELECT statement_no,
|
||
COALESCE(SUM(line_amount) FILTER (WHERE line_counted), 0)::numeric AS net,
|
||
COALESCE(SUM(deduction_amount) FILTER (WHERE line_counted), 0)::numeric AS line_ded,
|
||
COUNT(*) FILTER (WHERE line_counted)::int AS live_lines
|
||
FROM (
|
||
SELECT sl.statement_no, sl.line_amount, sl.deduction_amount,
|
||
(COALESCE(sl.is_voided, false) = false
|
||
AND (sl.order_code IS NULL
|
||
OR EXISTS (SELECT 1 FROM ${schema}.orders o
|
||
WHERE o.order_code = sl.order_code AND o.deleted_at IS NULL))) AS line_counted
|
||
FROM ${schema}.statement_lines sl
|
||
WHERE sl.statement_type = 'supplier'
|
||
) t
|
||
GROUP BY statement_no
|
||
)
|
||
UPDATE ${schema}.supplier_statements ss
|
||
SET deduction_amount = 0,
|
||
payable_amount = GREATEST(0, ROUND(line_agg.net, 2)),
|
||
unpaid_amount = GREATEST(0, ROUND(line_agg.net - COALESCE(ss.paid_amount, 0), 2))
|
||
FROM line_agg
|
||
WHERE line_agg.statement_no = ss.statement_no
|
||
AND line_agg.live_lines > 0
|
||
AND COALESCE(ss.deduction_amount, 0) > 0
|
||
AND ABS(COALESCE(ss.deduction_amount, 0) - line_agg.line_ded) < 0.005
|
||
AND COALESCE(ss.statement_status, 0) < 30`);
|
||
console.log(` → 已更新 ${res.rowCount} 行`);
|
||
}
|
||
total1 += rows.length;
|
||
} else {
|
||
console.log(`\n[${schema}] 步骤 1 跳过:statement_lines 缺 deduction_amount/is_voided`);
|
||
}
|
||
|
||
const rows2 = (await client.query(STEP2_SELECT(schema))).rows as any[];
|
||
console.log(`\n[${schema}] 步骤 2:修正 unpaid_amount ${rows2.length} 行`);
|
||
for (const r of rows2) {
|
||
console.log(
|
||
` ${r.statement_no} (${r.cycle_code}) 应付 ${money(r.payable_before)} 待付 ${money(r.unpaid_before)}→${money(r.unpaid_after)}`
|
||
);
|
||
}
|
||
if (args.execute && rows2.length) {
|
||
const res = await client.query(`
|
||
UPDATE ${schema}.supplier_statements ss
|
||
SET unpaid_amount = GREATEST(
|
||
0, ROUND(COALESCE(ss.payable_amount, ss.total_amount, 0) - COALESCE(ss.paid_amount, 0), 2)
|
||
)
|
||
WHERE COALESCE(ss.statement_status, 0) < 30
|
||
AND ss.unpaid_amount IS DISTINCT FROM GREATEST(
|
||
0, ROUND(COALESCE(ss.payable_amount, ss.total_amount, 0) - COALESCE(ss.paid_amount, 0), 2)
|
||
)`);
|
||
console.log(` → 已更新 ${res.rowCount} 行`);
|
||
}
|
||
total2 += rows2.length;
|
||
|
||
if (args.execute) await client.query('COMMIT');
|
||
else await client.query('ROLLBACK');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
console.log(
|
||
`\n合计:步骤1 ${total1} 行 / 步骤2 ${total2} 行${args.execute ? '(已提交)' : '(预览,未写库)'}`
|
||
);
|
||
} finally {
|
||
client.release();
|
||
await pool.end();
|
||
}
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error);
|
||
process.exit(1);
|
||
});
|