feat(入库成本): 核心写路径 —— 改批次成本并重算未结算订单的抵扣账本(口径甲,第 1 步)
按开发者 2026-10-14 裁定实现(设计文 docs/design/20261014-入库列表改批次成本(并重算抵扣账本).md):
新增 server/src/services/inventoryBatchCostService.ts,提供
· previewBatchCostImpact({batchNo,newCost}) —— 弹窗用:列出受影响订单行、金额前后、已结算跳过清单;
· applyBatchCostChange({batchNo,newCost,remark,operatorId}) —— 同事务:改 inventory.cost_price
+ 按该行**实际抵扣的批次**重算未结算订单的 cost_details(inventory_cover) + 留痕。
守卫:备注必填(同 /inventory/adjust 口径);已结算(客户结算单已确认 statement_status>=20)不回改并返回清单;
只改成本、不动在库量/预留;写 inventory_logs(operation_type='adjust',before/after= 3.00→3.50)+ writeAuditLog。
⚠️ 关键实现点(实测踩到):受影响批次的来源**必须与展示同源** —— 用 listStockCoverBatches
(manual → 计划 picking_items.outbound_batches → FIFO 三级回落);直接读 order_items.cover_batches
只拿到"我方指定"那一级,多数行为空 ⇒ 实测算出 0 个受影响订单。
真库实测(BR002 苹果批次 IN20261014EXTXBZ ¥3 → ¥3.5):预览 affected=1(抵扣 30 斤 ¥90→¥105);
应用后抵扣账本 ¥90→¥105、「订单商品成本」页库存成本 ¥159→¥174、整行成本 ¥256→¥271(两处同步);
改回 ¥3 全部复原(幂等);inventory_logs 两条(¥3.00→¥3.50 / ¥3.50→¥3.00,带备注)。
下一步(下一轮):A 预览/写路由 → D 入库列表入口 + 风险弹窗 → E 三语弹窗文案。
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { listStockCoverBatches } from './stockCoverBatchQueryService';
|
||||
|
||||
/**
|
||||
* **改批次入库成本 + 重算未结算订单的抵扣账本**(开发者 2026-10-14,口径「甲」)。
|
||||
*
|
||||
* 需求原话:「库存抵扣的成本也是可以改的,他如果修改了,那么关联的那个几个批次的成本,就变成一样
|
||||
* 统一进行修改;不过改这个需要告知他风险,触发弹窗,比如说修改了这个值之后,哪几个批次它的入库价格
|
||||
* 会进行变动」「他如果想改的话只能去**入库列表**里面找到这个批次进行修改,订单这块还是只能读,
|
||||
* 不然的话万一他这个批次被多个订单扣除」。
|
||||
*
|
||||
* 口径(甲):改批次 `inventory.cost_price` ⇒ **同事务**按 `order_items.cover_batches` 重算
|
||||
* **未结算**订单的 `cost_details(cost_source='inventory_cover')` 金额 ⇒ 账本仍是唯一真相源,
|
||||
* 「订单商品成本」页的库存成本跟着变,与订单详情(动态按批次算)保持一致。
|
||||
*
|
||||
* 守卫(库存 + 财务冻结面):
|
||||
* · 备注**必填**(与 `POST /inventory/adjust` 同口径);
|
||||
* · 写 `inventory_logs`(`operation_type='adjust'`)+ `writeAuditLog`,变更前后值齐全;
|
||||
* · **已结算**订单(客户结算单已确认 `statement_status >= 20`)的抵扣账本**不回改**,返回清单告知;
|
||||
* · 只改这一个批次的成本,**不动**在库量/预留/其它字段。
|
||||
*
|
||||
* 设计:docs/design/20261014-入库列表改批次成本(并重算抵扣账本).md
|
||||
*/
|
||||
export type BatchCostImpactOrderRow = {
|
||||
order_code: string;
|
||||
sku_code: string;
|
||||
item_name: string | null;
|
||||
cover_qty: number;
|
||||
/** 该(订单×SKU)当前账本结转额 */
|
||||
before_amount: number;
|
||||
/** 按新价重算后的结转额 */
|
||||
after_amount: number;
|
||||
/** 已结算 ⇒ 不回改 */
|
||||
skipped?: 'settled';
|
||||
};
|
||||
|
||||
export type BatchCostImpact = {
|
||||
batch_no: string;
|
||||
sku_code: string;
|
||||
unit: string | null;
|
||||
before_cost: number;
|
||||
after_cost: number;
|
||||
rows: BatchCostImpactOrderRow[];
|
||||
/** 会真正被改写的(未结算)订单×SKU 数 */
|
||||
affected_count: number;
|
||||
/** 因已结算被跳过的行数 */
|
||||
skipped_count: number;
|
||||
};
|
||||
|
||||
type Db = Pick<PoolClient, 'query'>;
|
||||
const round2 = (n: number) => Math.round((Number(n) || 0) * 100) / 100;
|
||||
const trim = (v: unknown) => String(v ?? '').trim();
|
||||
|
||||
type CoverBatchJson = Array<{ batch_no?: string; qty?: number }>;
|
||||
|
||||
/** `cover_batches` 可能是数组、也可能是 {batches:[...]} 包裹;统一取数组 */
|
||||
function parseCoverBatches(raw: unknown): CoverBatchJson {
|
||||
if (!raw) return [];
|
||||
let value: unknown = raw;
|
||||
if (typeof raw === 'string') {
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
if (Array.isArray(value)) return value as CoverBatchJson;
|
||||
if (value && typeof value === 'object') {
|
||||
const inner = (value as { batches?: unknown }).batches;
|
||||
if (Array.isArray(inner)) return inner as CoverBatchJson;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
async function loadBatch(db: Db, batchNo: string, branchCode?: string | null) {
|
||||
const branch = trim(branchCode) || null;
|
||||
const res = await db.query<{
|
||||
id: string;
|
||||
batch_no: string;
|
||||
sku_code: string | null;
|
||||
cost_price: number | null;
|
||||
}>(
|
||||
`SELECT id, batch_no, sku_code, COALESCE(cost_price, 0)::float AS cost_price
|
||||
FROM inventory
|
||||
WHERE batch_no = $1
|
||||
AND ($2::text IS NULL OR branch_code IS NOT DISTINCT FROM $2)
|
||||
ORDER BY id
|
||||
LIMIT 1`,
|
||||
[batchNo, branch]
|
||||
);
|
||||
return res.rows[0] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览:改这个批次的成本会影响哪些订单行、金额怎么变(**只读**,弹窗用)。
|
||||
* 不传 `newCost` 时按"当前价"算(即 before == after,仅列受影响清单)。
|
||||
*/
|
||||
export async function previewBatchCostImpact(input: {
|
||||
batchNo: string;
|
||||
newCost?: number | null;
|
||||
branchCode?: string | null;
|
||||
}): Promise<BatchCostImpact | null> {
|
||||
const batchNo = trim(input.batchNo);
|
||||
if (!batchNo) return null;
|
||||
const batch = await loadBatch(pool as never, batchNo, input.branchCode);
|
||||
if (!batch) return null;
|
||||
return buildImpact(pool as never, {
|
||||
batchNo,
|
||||
skuCode: trim(batch.sku_code),
|
||||
beforeCost: Number(batch.cost_price) || 0,
|
||||
afterCost: input.newCost == null ? Number(batch.cost_price) || 0 : Number(input.newCost) || 0,
|
||||
branchCode: input.branchCode,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用:改批次成本 + 重算未结算订单的抵扣账本 + 留痕(**写**,同事务)。
|
||||
*/
|
||||
export async function applyBatchCostChange(input: {
|
||||
batchNo: string;
|
||||
newCost: number;
|
||||
remark: string;
|
||||
operatorId?: string | null;
|
||||
branchCode?: string | null;
|
||||
client?: PoolClient;
|
||||
}): Promise<BatchCostImpact> {
|
||||
const batchNo = trim(input.batchNo);
|
||||
const remark = trim(input.remark);
|
||||
const newCost = Number(input.newCost);
|
||||
if (!batchNo) throw Object.assign(new Error('缺少批次号'), { status: 400, code: 'invalid_batch' });
|
||||
if (!remark) {
|
||||
throw Object.assign(new Error('改入库成本必须填写备注'), { status: 400, code: 'remark_required' });
|
||||
}
|
||||
if (!Number.isFinite(newCost) || newCost < 0) {
|
||||
throw Object.assign(new Error('入库成本必须是不小于 0 的数字'), { status: 400, code: 'invalid_cost' });
|
||||
}
|
||||
|
||||
const ownsClient = !input.client;
|
||||
const client = input.client || (await pool.connect());
|
||||
try {
|
||||
if (ownsClient) await client.query('BEGIN');
|
||||
const batch = await loadBatch(client, batchNo, input.branchCode);
|
||||
if (!batch) {
|
||||
throw Object.assign(new Error('批次不存在或不属于当前分公司'), { status: 404, code: 'batch_not_found' });
|
||||
}
|
||||
const skuCode = trim(batch.sku_code);
|
||||
const beforeCost = Number(batch.cost_price) || 0;
|
||||
if (Math.abs(beforeCost - newCost) < 1e-9) {
|
||||
// 价格没变:不写日志、不动账本,直接返回影响面(幂等)
|
||||
const impact = await buildImpact(client, { batchNo, skuCode, beforeCost, afterCost: newCost, branchCode: input.branchCode });
|
||||
if (ownsClient) await client.query('COMMIT');
|
||||
return impact;
|
||||
}
|
||||
|
||||
const impact = await buildImpact(client, { batchNo, skuCode, beforeCost, afterCost: newCost, branchCode: input.branchCode });
|
||||
|
||||
// ① 改批次成本(只动成本,不动在库量/预留)
|
||||
await client.query(`UPDATE inventory SET cost_price = $2::numeric WHERE id = $1::uuid`, [
|
||||
batch.id,
|
||||
newCost,
|
||||
]);
|
||||
|
||||
// ② 口径甲:重算**未结算**订单的抵扣账本行
|
||||
for (const row of impact.rows) {
|
||||
if (row.skipped === 'settled') continue;
|
||||
await client.query(
|
||||
`UPDATE cost_details
|
||||
SET amount = $3::numeric, allocated_amount = $3::numeric
|
||||
WHERE order_code = $1 AND sku_code = $2 AND cost_source = 'inventory_cover'`,
|
||||
[row.order_code, row.sku_code, row.after_amount]
|
||||
);
|
||||
}
|
||||
|
||||
// ③ 留痕:inventory_logs(与库存调整同表同口径)+ 审计
|
||||
await client.query(
|
||||
`INSERT INTO inventory_logs (
|
||||
batch_no, sku_code, operation_type, quantity, before_qty, after_qty,
|
||||
related_order_code, operator_id, remark
|
||||
) VALUES ($1, $2, 'adjust', 0::numeric, $3::numeric, $4::numeric, NULL, $5, $6)`,
|
||||
[batchNo, skuCode, beforeCost, newCost, trim(input.operatorId) || null, remark]
|
||||
);
|
||||
await writeAuditLog({
|
||||
operatorId: trim(input.operatorId) || null,
|
||||
operationType: 'inventory_batch_cost_adjust',
|
||||
targetTable: 'inventory',
|
||||
targetId: String(batch.id),
|
||||
oldValue: { batch_no: batchNo, sku_code: skuCode, cost_price: beforeCost },
|
||||
newValue: {
|
||||
batch_no: batchNo,
|
||||
sku_code: skuCode,
|
||||
cost_price: newCost,
|
||||
remark,
|
||||
recalculated_orders: impact.rows.filter((r) => r.skipped !== 'settled').length,
|
||||
skipped_settled: impact.skipped_count,
|
||||
},
|
||||
});
|
||||
|
||||
if (ownsClient) await client.query('COMMIT');
|
||||
return impact;
|
||||
} catch (error) {
|
||||
if (ownsClient) await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
if (ownsClient) client.release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 影响面:哪些订单行抵扣了这个批次、金额前后、是否已结算被跳过。
|
||||
*
|
||||
* ⚠️ **批次来源必须与展示同源**:用 `listStockCoverBatches`(manual → 计划 `picking_items.outbound_batches`
|
||||
* → FIFO 三级回落),而不是直接读 `order_items.cover_batches`(那只是"我方指定"那一级,多数行为空——
|
||||
* 2026-10-14 实测:直接读它得到 0 个受影响订单)。
|
||||
*/
|
||||
async function buildImpact(
|
||||
db: Db,
|
||||
input: { batchNo: string; skuCode: string; beforeCost: number; afterCost: number; branchCode?: string | null }
|
||||
): Promise<BatchCostImpact> {
|
||||
const candidates = await db.query<{ order_code: string; item_name: string | null; settled: boolean }>(
|
||||
`SELECT DISTINCT oi.order_code,
|
||||
MIN(oi.item_name) AS item_name,
|
||||
-- 已结算判定:该单出现在**客户结算单**明细里且结算单已确认(statement_status >= 20)
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM statement_lines sl
|
||||
JOIN customer_statements cs ON cs.statement_no = sl.statement_no
|
||||
WHERE sl.order_code = oi.order_code
|
||||
AND sl.statement_type = 'customer'
|
||||
AND COALESCE(cs.statement_status, 0) >= 20
|
||||
) AS settled
|
||||
FROM order_items oi
|
||||
WHERE COALESCE(oi.stock_cover_qty, 0) > 0
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND oi.sku_code = $1
|
||||
GROUP BY oi.order_code`,
|
||||
[input.skuCode]
|
||||
);
|
||||
|
||||
const rows: BatchCostImpactOrderRow[] = [];
|
||||
for (const cand of candidates.rows) {
|
||||
// 与展示同源:该单这一 SKU 实际抵扣的批次(含各批次成本价)
|
||||
const resolved = await listStockCoverBatches({
|
||||
orderCode: String(cand.order_code),
|
||||
branchCode: input.branchCode,
|
||||
});
|
||||
const hit = (resolved.items || []).find((i) => trim(i.sku_code) === input.skuCode);
|
||||
if (!hit) continue;
|
||||
const batches = (hit.batches || []).filter((b) => Number(b.qty) > 0);
|
||||
const usesTarget = batches.some((b) => trim(b.batch_no) === input.batchNo);
|
||||
if (!usesTarget) continue; // 该行没用到这个批次
|
||||
const sumWith = (cost: number) =>
|
||||
round2(
|
||||
batches.reduce((sum, b) => {
|
||||
const price =
|
||||
trim(b.batch_no) === input.batchNo ? cost : Number(b.cost_price) || 0;
|
||||
return sum + (Number(b.qty) || 0) * price;
|
||||
}, 0)
|
||||
);
|
||||
rows.push({
|
||||
order_code: trim(cand.order_code),
|
||||
sku_code: input.skuCode,
|
||||
item_name: cand.item_name ? String(cand.item_name) : hit.item_name ? String(hit.item_name) : null,
|
||||
cover_qty: round2(batches.reduce((sum, b) => sum + (Number(b.qty) || 0), 0)),
|
||||
before_amount: sumWith(input.beforeCost),
|
||||
after_amount: sumWith(input.afterCost),
|
||||
...(cand.settled ? { skipped: 'settled' as const } : {}),
|
||||
});
|
||||
}
|
||||
const unit = await db.query<{ unit: string | null }>(
|
||||
`SELECT COALESCE(NULLIF(TRIM(unit), ''), NULL) AS unit FROM skus WHERE sku_code = $1 LIMIT 1`,
|
||||
[input.skuCode]
|
||||
);
|
||||
return {
|
||||
batch_no: input.batchNo,
|
||||
sku_code: input.skuCode,
|
||||
unit: unit.rows[0]?.unit ? String(unit.rows[0].unit) : null,
|
||||
before_cost: round2(input.beforeCost),
|
||||
after_cost: round2(input.afterCost),
|
||||
rows,
|
||||
affected_count: rows.filter((r) => r.skipped !== 'settled').length,
|
||||
skipped_count: rows.filter((r) => r.skipped === 'settled').length,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user