开发者口径:「仓库的货物靠独立进货进入,成本在进货单那块就已经计算了;后续下单被库存抵扣完毕,
那么这个订单的成本价就应该是零;如果缺少一部分需要自采,那填入的成本价应该是自采那一小部分的成本价。」
落地:
- inventoryStockCoverService:抵扣**不再调用**成本结转(成本留在进货那一笔:独立进货/验收入库写的
inventory_holding,因不挂订单号已被净利当期间费用扣除);开关 isStockCoverOutsourcedOnlyEnabled()
默认**关** —— 抵扣量默认 = 物理自由库存(物理可用 − 他单活跃预留),需旧口径时显式
STOCK_COVER_REQUIRE_OUTSOURCED=1 回退;已抵扣量的归属校验改看**预留行**(新口径不再有成本行),
存量成本行判据保留兼容。
- inventorySurplusCostService.postInventoryCoverPurchaseCost → **no-op**(保留签名,注释写明去向)。
- orderCostPostingService.upsertOrderSkuPurchaseCostFromUnitCost:两条路径都按**缺口量**记账
max(0, quantity − stock_cover_qty) × 成本价(全额抵扣 ⇒ 0)。
- mainSystemItemSkuMappingService:「可抵扣商品」列表 coverable_qty 默认用物理自由库存。
- 新增 scripts/repair-cover-cost-zero-caliber.ts(默认干跑;未结案重算;已结案/抵扣量已归零的残留只报,
需 --include-closed / --include-orphan-rows)。
真库 BR003 实测(干跑 → 执行):
- 未结案 2 张:ORD_API_20261013_BR003_0002 ¥72、_0004 ¥18 ⇒ 删除抵扣成本行、成本回补持有桶
(新行 reference_id='cover_zero_caliber:<订单>'),inventory_cover 行 13→11 条、¥1,291.70→¥1,201.70;
- 已结案 2 张只报不动:_0003(¥525.20 抵扣行 + order_goods 应下调 ¥238:四行全额抵扣 ⇒ 0)、
ORD_API_20261012_BR003_0002(¥520.50);
- 抵扣量已归零的残留 2 张只报不动:ORD_API_20261014_BR003_0001 ¥150、FIXTEST_COVERSKU_0001 ¥6。
测试:新增 coverPartNoOrderCost.test.ts(8 例);stockCover{Guard,OutsourcedOnly,ZeroReason} 三个旧口径
契约测试改为"显式打开回退开关"路径 + 重写结转侧为 no-op 断言。
回归:server 25 failed / 398 passed(失败文件集与基线逐一比对一致);root tsc 0;门禁 8/1/1。
270 lines
11 KiB
TypeScript
270 lines
11 KiB
TypeScript
/**
|
||
* 存量对账/重算:**抵扣部分不计订单成本**(2026-10-14 开发者口径,已批准)。
|
||
*
|
||
* 新口径:
|
||
* · 被库存抵扣的部分 **不计订单成本**(成本在独立进货/验收时就已入账,且被净利当期间费用扣除);
|
||
* · 订单成本只记**缺口部分** = `GREATEST(0, quantity − stock_cover_qty) × 成本价`;
|
||
* · 抵扣不再结转成本、不再冲减"账外持有"桶。
|
||
*
|
||
* 本脚本处理**存量数据**(新写入点已改,见 `docs/design/20261014-抵扣部分不计订单成本.md`):
|
||
* ① 删掉旧的 `stock_cover` 成本行(cost_source='inventory_cover');
|
||
* ② 把这些金额**回补到账外持有桶**(成本回到"已入损益的库存成本池",不进订单);
|
||
* ③ 把 `order_goods`(remark `unit_cost_sync`)按**缺口量**重算(全额抵扣 ⇒ 0)。
|
||
*
|
||
* 范围(开发者裁决):**默认只重算未结案单**(order_status < 90);已结案单只打印差异表,
|
||
* 除非显式 `--include-closed`(已结案单的成本会影响已出报表,建议人工确认后再跑)。
|
||
*
|
||
* 用法:
|
||
* cd server && npx tsx --env-file=.env scripts/repair-cover-cost-zero-caliber.ts # 干跑全部已登记分公司
|
||
* cd server && npx tsx --env-file=.env scripts/repair-cover-cost-zero-caliber.ts BR003
|
||
* cd server && npx tsx --env-file=.env scripts/repair-cover-cost-zero-caliber.ts --apply BR003
|
||
* cd server && npx tsx --env-file=.env scripts/repair-cover-cost-zero-caliber.ts --apply --include-closed BR003
|
||
*/
|
||
import { pool } from '../src/db';
|
||
import { runWithTenantDbContext } from '../src/services/tenantDbContext';
|
||
import { currentCycleCodeChina } from '../src/services/fixedCostService';
|
||
|
||
const APPLY = process.argv.includes('--apply');
|
||
const INCLUDE_CLOSED = process.argv.includes('--include-closed');
|
||
/** 抵扣量已归零、却仍留着 `inventory_cover` 成本行的历史/测试残留(默认只报不动) */
|
||
const INCLUDE_ORPHAN = process.argv.includes('--include-orphan-rows');
|
||
const BRANCH_ARGS = process.argv.filter((a) => /^BR\d+$/i.test(a)).map((a) => a.toUpperCase());
|
||
const round2 = (n: number) => Math.round((Number(n) || 0) * 100) / 100;
|
||
|
||
type OrderFix = {
|
||
orderCode: string;
|
||
orderStatus: number;
|
||
coverRows: Array<{ sku_code: string; amount: number }>;
|
||
coverTotal: number;
|
||
lineFixes: Array<{
|
||
orderItemId: string;
|
||
skuCode: string;
|
||
quantity: number;
|
||
coverQty: number;
|
||
unitCost: number;
|
||
expectedAmount: number;
|
||
currentAmount: number;
|
||
}>;
|
||
orderGoodsDelta: number;
|
||
};
|
||
|
||
async function collectOrderFixes(): Promise<OrderFix[]> {
|
||
const params: unknown[] = [];
|
||
const rows = await pool.query<{
|
||
order_code: string;
|
||
order_status: number;
|
||
order_item_id: string;
|
||
sku_code: string;
|
||
quantity: string;
|
||
stock_cover_qty: string;
|
||
unit_cost: string;
|
||
current_amount: string | null;
|
||
}>(
|
||
`SELECT o.order_code, o.order_status,
|
||
oi.id::text AS order_item_id, oi.sku_code,
|
||
COALESCE(oi.quantity,0)::numeric AS quantity,
|
||
COALESCE(oi.stock_cover_qty,0)::numeric AS stock_cover_qty,
|
||
COALESCE(oi.unit_cost,0)::numeric AS unit_cost,
|
||
(SELECT cd.amount FROM cost_details cd
|
||
WHERE cd.order_item_id = oi.id AND cd.cost_type = 'purchase'
|
||
AND COALESCE(cd.remark,'') = 'unit_cost_sync' LIMIT 1)::numeric AS current_amount
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
WHERE o.deleted_at IS NULL
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
AND COALESCE(oi.stock_cover_qty, 0) > 0
|
||
ORDER BY o.order_code, oi.sku_code`,
|
||
params
|
||
);
|
||
|
||
const byOrder = new Map<string, OrderFix>();
|
||
for (const row of rows.rows) {
|
||
const orderCode = String(row.order_code);
|
||
const bucket =
|
||
byOrder.get(orderCode) ||
|
||
({
|
||
orderCode,
|
||
orderStatus: Number(row.order_status) || 0,
|
||
coverRows: [],
|
||
coverTotal: 0,
|
||
lineFixes: [],
|
||
orderGoodsDelta: 0,
|
||
} satisfies OrderFix);
|
||
const quantity = Number(row.quantity) || 0;
|
||
const coverQty = Number(row.stock_cover_qty) || 0;
|
||
const unitCost = Number(row.unit_cost) || 0;
|
||
const expectedAmount = round2(Math.max(0, quantity - coverQty) * unitCost);
|
||
const currentAmount = row.current_amount == null ? 0 : Number(row.current_amount) || 0;
|
||
bucket.lineFixes.push({
|
||
orderItemId: String(row.order_item_id),
|
||
skuCode: String(row.sku_code || ''),
|
||
quantity,
|
||
coverQty,
|
||
unitCost,
|
||
expectedAmount,
|
||
currentAmount,
|
||
});
|
||
bucket.orderGoodsDelta = round2(bucket.orderGoodsDelta + (currentAmount - expectedAmount));
|
||
byOrder.set(orderCode, bucket);
|
||
}
|
||
|
||
{
|
||
// 全量取:包含"订单已删/抵扣量已归零"的残留成本行(只在报告里出现,默认不动)
|
||
const covers = await pool.query<{ order_code: string; sku_code: string; amount: string }>(
|
||
`SELECT order_code, sku_code, COALESCE(SUM(amount),0)::text AS amount
|
||
FROM cost_details
|
||
WHERE cost_source = 'inventory_cover'
|
||
GROUP BY order_code, sku_code`
|
||
);
|
||
for (const row of covers.rows) {
|
||
const orderCode = String(row.order_code);
|
||
const amount = Number(row.amount) || 0;
|
||
const bucket =
|
||
byOrder.get(orderCode) ||
|
||
({
|
||
orderCode,
|
||
orderStatus: -1, // -1 = 订单不存在/已删(纯残留)
|
||
coverRows: [],
|
||
coverTotal: 0,
|
||
lineFixes: [],
|
||
orderGoodsDelta: 0,
|
||
} satisfies OrderFix);
|
||
bucket.coverRows.push({ sku_code: String(row.sku_code || ''), amount });
|
||
bucket.coverTotal = round2(bucket.coverTotal + amount);
|
||
byOrder.set(orderCode, bucket);
|
||
}
|
||
}
|
||
return [...byOrder.values()];
|
||
}
|
||
|
||
async function applyOrderFix(fix: OrderFix, branch: string) {
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
// ① 删旧抵扣成本行
|
||
const deleted = await client.query(
|
||
`DELETE FROM cost_details WHERE order_code = $1 AND cost_source = 'inventory_cover'`,
|
||
[fix.orderCode]
|
||
);
|
||
// ② 金额回补到"账外持有"(成本已在进货时入损益,这里只把它放回期间费用池;不进订单)
|
||
if (fix.coverTotal > 0) {
|
||
const refId = `cover_zero_caliber:${fix.orderCode}`;
|
||
const existed = await client.query(
|
||
`SELECT 1 FROM cost_details WHERE reference_id = $1 AND cost_type = 'inventory_holding' LIMIT 1`,
|
||
[refId]
|
||
);
|
||
if (!existed.rowCount) {
|
||
await client.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, order_code, cost_type, cost_subtype, amount, status,
|
||
branch_code, sku_code, reference_type, reference_id, cost_source, remark
|
||
) VALUES ($1, NULL, 'inventory_holding', 'cover_caliber_return', $2, 20,
|
||
$3, NULL, 'caliber_fix', $4, 'cover_revert',
|
||
'[口径修复] 抵扣不再计入订单成本:成本回到持有桶')`,
|
||
[currentCycleCodeChina(), fix.coverTotal, branch, refId]
|
||
);
|
||
}
|
||
}
|
||
// ③ order_goods 按缺口量重算
|
||
for (const line of fix.lineFixes) {
|
||
if (line.currentAmount === line.expectedAmount) continue;
|
||
await client.query(
|
||
`UPDATE cost_details
|
||
SET amount = $2, allocated_amount = $2
|
||
WHERE order_item_id = $1::uuid AND cost_type = 'purchase'
|
||
AND COALESCE(remark,'') = 'unit_cost_sync'`,
|
||
[line.orderItemId, line.expectedAmount]
|
||
);
|
||
}
|
||
await client.query('COMMIT');
|
||
return deleted.rowCount || 0;
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
async function resolveBranches(): Promise<string[]> {
|
||
if (BRANCH_ARGS.length) return BRANCH_ARGS;
|
||
const r = await pool.query<{ branch_code: string }>(
|
||
`SELECT branch_code FROM public.branches ORDER BY branch_code`
|
||
);
|
||
return r.rows.map((row) => String(row.branch_code)).filter(Boolean);
|
||
}
|
||
|
||
async function main() {
|
||
const branches = await resolveBranches();
|
||
let fixedOrders = 0;
|
||
let coverTotal = 0;
|
||
let goodsDelta = 0;
|
||
let closedSkipped = 0;
|
||
let orphanSkipped = 0;
|
||
|
||
for (const branch of branches) {
|
||
await runWithTenantDbContext(branch, async () => {
|
||
const fixes = await collectOrderFixes();
|
||
const coverQtyOf = (f: OrderFix) =>
|
||
f.lineFixes.reduce((sum, line) => sum + line.coverQty, 0);
|
||
const closed = fixes.filter((f) => f.orderStatus >= 90 && coverQtyOf(f) > 0);
|
||
const orphan = fixes.filter((f) => coverQtyOf(f) <= 1e-9);
|
||
const open = fixes.filter((f) => f.orderStatus >= 0 && f.orderStatus < 90 && coverQtyOf(f) > 0);
|
||
console.log(
|
||
`\n════════ ${branch}:命中 ${fixes.length} 张单(未结案可重算 ${open.length} / 已结案只报 ${closed.length} / 抵扣量已归零的残留 ${orphan.length})════════`
|
||
);
|
||
for (const fix of fixes) {
|
||
const isClosed = fix.orderStatus >= 90;
|
||
const isOrphan = coverQtyOf(fix) <= 1e-9;
|
||
console.log(
|
||
` ${fix.orderCode}(状态 ${fix.orderStatus < 0 ? '订单不存在' : fix.orderStatus})` +
|
||
`抵扣成本行 ¥${fix.coverTotal.toFixed(2)},现存抵扣量 ${round2(coverQtyOf(fix))},` +
|
||
`order_goods 需下调 ¥${fix.orderGoodsDelta.toFixed(2)}` +
|
||
(isClosed ? ' ⚠️ 已结案:只报不动(需 --include-closed)' : '') +
|
||
(isOrphan ? ' ⚠️ 抵扣量已归零的残留:只报不动(需 --include-orphan-rows)' : '')
|
||
);
|
||
for (const line of fix.lineFixes) {
|
||
if (line.currentAmount === line.expectedAmount) continue;
|
||
console.log(
|
||
` ${line.skuCode} 量 ${line.quantity} − 抵扣 ${line.coverQty} = 缺口 ${round2(line.quantity - line.coverQty)}` +
|
||
` × ${line.unitCost} ⇒ 账本 ${line.currentAmount} → ${line.expectedAmount}`
|
||
);
|
||
}
|
||
coverTotal = round2(coverTotal + fix.coverTotal);
|
||
goodsDelta = round2(goodsDelta + fix.orderGoodsDelta);
|
||
if (isClosed && !INCLUDE_CLOSED) {
|
||
closedSkipped += 1;
|
||
continue;
|
||
}
|
||
if (isOrphan && !INCLUDE_ORPHAN) {
|
||
orphanSkipped += 1;
|
||
continue;
|
||
}
|
||
if (!APPLY) continue;
|
||
try {
|
||
const deleted = await applyOrderFix(fix, branch);
|
||
console.log(` → 已重算(删除抵扣成本行 ${deleted} 条,回补持有桶 ¥${fix.coverTotal.toFixed(2)})`);
|
||
fixedOrders += 1;
|
||
} catch (error) {
|
||
console.error(` → ❌ 失败:${(error as Error)?.message || error}`);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
console.log(
|
||
`\n${APPLY ? '已执行' : '干跑(未改数据)'}:命中抵扣成本 ¥${coverTotal.toFixed(2)},` +
|
||
`order_goods 应下调 ¥${goodsDelta.toFixed(2)},重算 ${fixedOrders} 张单` +
|
||
(closedSkipped ? `;已结案跳过 ${closedSkipped} 张(--include-closed 可一并处理)` : '') +
|
||
(orphanSkipped ? `;抵扣量已归零的残留跳过 ${orphanSkipped} 张(--include-orphan-rows 可一并处理)` : '') +
|
||
(APPLY ? '' : '\n确认无误后加 `--apply` 执行(幂等:抵扣行删掉后不再命中)。')
|
||
);
|
||
await pool.end();
|
||
}
|
||
|
||
main().catch(async (error) => {
|
||
console.error('[repair-cover-cost-zero-caliber] 失败:', error);
|
||
await pool.end();
|
||
process.exit(1);
|
||
});
|