Files
SupplierSystem/server/src/services/processingDemandPickAmendService.ts
T
Ubuntu 5fa2bbfd55
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
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

415 lines
14 KiB
TypeScript
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.
/**
* 管理员改已完成仓内需求单领料。禁止调用 pickDemandSheetMaterial / returnDemandSheetMaterials。
* 见 docs/design/20260904-processing-demand-pick-amend.md
*/
import type { PoolClient } from 'pg';
import { pool } from '../db';
import { fifoDeductInventory, type InventoryDeductBatch as FIFODeductBatch } from './inventoryOutboundService';
import { upsertInventoryHoldingCost } from './inventorySurplusCostService';
import { reduceInventoryHoldingForMaterialPicks, type InventoryDeductBatch } from './processingStandaloneCostService';
import { settleDemandSheetCostOnCompletion } from './processingDemandSheetService';
import {
claimOwnOrderReservationForProcessingPick,
resolveProcessingPickReservationSplit,
} from './processingPickReservationService';
import { sumAvailableQty } from './inventoryStockCoverService';
const PROCESS_COMPLETED = 40;
const PROCESS_REJECTED = 50;
function roundQty(n: number): number {
return Math.round(n * 1000) / 1000;
}
function roundMoney(n: number): number {
return Math.round(n * 100) / 100;
}
function trimText(v: unknown): string {
return String(v || '').trim();
}
function asUuidOrNull(v?: string | null): string | null {
const s = trimText(v);
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s) ? s : null;
}
function currentCycleCode(): string {
const d = new Date();
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}`;
}
function newReturnBatchNo(): string {
const d = new Date();
const ymd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
return `PRT${ymd}${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
}
export function assertAmendDemandMaterialQty(input: {
newQty: number;
currentQty: number;
netWeight: number;
}): { newQty: number; delta: number } {
const newQty = roundQty(Number(input.newQty));
const currentQty = roundQty(Number(input.currentQty));
const netWeight = roundQty(Number(input.netWeight));
if (!Number.isFinite(newQty) || newQty <= 0) {
throw Object.assign(new Error('领料数量须大于 0'), { status: 400, code: 'invalid_qty' });
}
if (newQty + 1e-9 < netWeight) {
throw Object.assign(new Error(`领料不能小于已入库净重 ${netWeight}`), {
status: 400,
code: 'qty_below_net_weight',
});
}
return { newQty, delta: roundQty(newQty - currentQty) };
}
export type DemandPickLine = {
id: string;
sku_code: string;
qty: number;
material_cost: number;
};
export type LifoReturnSlice = {
id: string;
sku_code: string;
qty: number;
cost: number;
remainingQty: number;
remainingCost: number;
};
/** picks 须已按 created_at DESC(新→旧) */
export function planLifoPickReturns(picks: DemandPickLine[], returnQty: number): LifoReturnSlice[] {
let left = roundQty(Number(returnQty) || 0);
const slices: LifoReturnSlice[] = [];
if (left <= 0) return slices;
for (const pick of picks) {
if (left <= 0) break;
const qty = roundQty(Number(pick.qty) || 0);
const cost = roundMoney(Number(pick.material_cost) || 0);
if (qty <= 0) continue;
const take = roundQty(Math.min(qty, left));
const takeCost = take + 1e-9 >= qty ? cost : roundMoney((cost * take) / qty);
slices.push({
id: pick.id,
sku_code: pick.sku_code,
qty: take,
cost: takeCost,
remainingQty: roundQty(qty - take),
remainingCost: roundMoney(cost - takeCost),
});
left = roundQty(left - take);
}
if (left > 1e-9) {
throw Object.assign(new Error('退料数量超过已领料'), { status: 400, code: 'return_exceeds_pick' });
}
return slices;
}
export async function amendDemandSheetMaterialQty(input: {
taskId: string;
qty: number;
skuCode?: string | null;
operatorId?: string | null;
remark?: string | null;
expectedBranchCode?: string | null;
requestId?: string | null;
}): Promise<{
material_qty: number;
material_cost: number;
loss_qty: number;
unit_cost: number;
process_status: number;
}> {
const taskId = trimText(input.taskId);
if (!taskId) throw Object.assign(new Error('缺少加工需求单'), { status: 400 });
const client = await pool.connect();
try {
await client.query('BEGIN');
const task = await client.query(
`SELECT id, task_code, sku_code, branch_code, process_status, source_type,
COALESCE(material_qty, 0)::float AS material_qty,
COALESCE(material_cost, 0)::float AS material_cost,
COALESCE(net_weight, 0)::float AS net_weight
FROM processing_tasks
WHERE id = $1
FOR UPDATE`,
[taskId]
);
const row = task.rows[0];
if (!row || String(row.source_type) !== 'demand') {
throw Object.assign(new Error('加工需求单不存在'), { status: 404 });
}
if (Number(row.process_status) >= PROCESS_REJECTED) {
throw Object.assign(new Error('需求单已关闭'), { status: 409 });
}
if (Number(row.process_status) !== PROCESS_COMPLETED) {
throw Object.assign(new Error('仅已完成的需求单可在此改领料,未完成请用领料加工'), {
status: 409,
code: 'not_completed',
});
}
const branchCode = trimText(row.branch_code);
const expectedBranch = trimText(input.expectedBranchCode);
if (expectedBranch && branchCode !== expectedBranch) {
throw Object.assign(new Error('无权操作其它分公司的加工需求单'), {
status: 403,
code: 'branch_mismatch',
});
}
const currentQty = roundQty(Number(row.material_qty) || 0);
const netWeight = roundQty(Number(row.net_weight) || 0);
const { delta } = assertAmendDemandMaterialQty({
newQty: input.qty,
currentQty,
netWeight,
});
if (Math.abs(delta) < 1e-9) {
await client.query('COMMIT');
return {
material_qty: currentQty,
material_cost: roundMoney(Number(row.material_cost) || 0),
loss_qty: roundQty(Math.max(0, currentQty - netWeight)),
unit_cost: 0,
process_status: PROCESS_COMPLETED,
};
}
if (delta > 0) {
await addCompletedDemandPick(client, {
taskId,
taskCode: String(row.task_code || taskId),
branchCode,
skuCode: trimText(input.skuCode) || trimText(row.sku_code),
qty: delta,
operatorId: input.operatorId,
remark: input.remark,
requestId: trimText(input.requestId) || null,
});
} else {
await returnCompletedDemandPickDelta(client, {
taskId,
taskCode: String(row.task_code || taskId),
branchCode,
returnQty: roundQty(-delta),
});
}
const summed = await client.query(
`SELECT COALESCE(SUM(qty), 0)::float AS qty, COALESCE(SUM(material_cost), 0)::float AS cost
FROM processing_demand_picks WHERE task_id = $1`,
[taskId]
);
const materialQty = roundQty(Number(summed.rows[0]?.qty) || 0);
const materialCost = roundMoney(Number(summed.rows[0]?.cost) || 0);
const lossQty = roundQty(Math.max(0, materialQty - netWeight));
await client.query(
`UPDATE processing_tasks
SET material_qty = $2,
material_cost = $3,
loss_qty = $4,
process_status = $5,
updated_at = NOW()
WHERE id = $1 AND source_type = 'demand'`,
[taskId, materialQty, materialCost, lossQty, PROCESS_COMPLETED]
);
const settled = await settleDemandSheetCostOnCompletion(taskId, client, {
overwriteInboundCostPrice: true,
});
await client.query('COMMIT');
return {
material_qty: materialQty,
material_cost: materialCost,
loss_qty: lossQty,
unit_cost: settled.unit_cost,
process_status: PROCESS_COMPLETED,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
async function addCompletedDemandPick(
client: PoolClient,
input: {
taskId: string;
taskCode: string;
branchCode: string;
skuCode: string;
qty: number;
operatorId?: string | null;
remark?: string | null;
requestId: string | null;
}
) {
const skuCode = trimText(input.skuCode);
if (!skuCode) throw Object.assign(new Error('请选择库存商品'), { status: 400 });
if (input.requestId) {
const replay = await client.query(
`SELECT 1 FROM processing_demand_picks WHERE task_id = $1 AND request_id = $2 LIMIT 1`,
[input.taskId, input.requestId]
);
if (replay.rowCount) return;
}
const skuRow = await client.query(`SELECT sku_name FROM skus WHERE sku_code = $1 LIMIT 1`, [skuCode]);
const skuName = String(skuRow.rows[0]?.sku_name || skuCode);
/**
* 与「需求单领料」同口径(2026-10-14):可领 = 毛可用 − **他单**预留。
* 需求单的成品就是本单已预留的那批货 ⇒ 本单自己的预留不该挡住本单领料;
* 扣库后必须成对消费本单预留(否则"库存已扣、预留仍在"⇒ 短送 + 同一批算两次)。
* 见 docs/design/20261014-加工领料可用本单预留.md
*/
const ownOrderCodes = (
await client.query<{ order_code: string }>(
`SELECT DISTINCT order_code FROM processing_demand_items
WHERE task_id = $1::uuid AND order_code IS NOT NULL AND order_code <> ''`,
[input.taskId]
)
).rows.map((r) => String(r.order_code));
const grossAvailable = await sumAvailableQty(client, skuCode, input.branchCode);
// 他单预留一次成型 = 全部在用预留 − 本单自己的在用预留(逐单号循环会算 N 倍)
const reservationSplit = await resolveProcessingPickReservationSplit(client, {
orderCodes: ownOrderCodes,
skuCode,
branchCode: input.branchCode,
});
const availableQty = Math.max(0, grossAvailable - reservationSplit.otherReserved);
if (availableQty + 1e-9 < input.qty) {
throw Object.assign(new Error(`库存不足:本分公司可用 ${availableQty},需要 ${input.qty}`), {
status: 400,
code: 'insufficient_stock',
});
}
const plannedOwnReservation = reservationSplit.ownReserved;
const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = [];
await fifoDeductInventory(
client,
{
skuCode,
qty: input.qty,
branchCode: input.branchCode,
// 传本单订单号 ⇒ 内部按「毛可用 − 他单预留」校验/扣减(与上面同口径)
orderCode: ownOrderCodes[0] || null,
// 内部预留守卫一次豁免全部本单订单号
reservationExemptOrderCodes: ownOrderCodes,
pickCode: input.taskCode,
operatorId: input.operatorId || null,
itemName: skuName,
operationType: 'processing_out',
remark: `管理员改领料补扣 ${input.taskCode}`,
},
(batch, deductedQty) => {
deductedBatches.push({ ...batch, deductedQty });
}
);
/**
* ⚠️ **必须成对**:领料已扣库 ⇒ 本单那部分预留要同步消费,否则
* 「库存已扣为 0、预留仍 status=10」⇒ 发车扣不到(短送)+ 加工成品又产出一份 ⇒ 同一批算两次。
*/
await claimOwnOrderReservationForProcessingPick(client, {
orderCodes: ownOrderCodes,
skuCode,
branchCode: input.branchCode,
qty: input.qty,
planned: plannedOwnReservation,
});
const materialCost = roundMoney(
deductedBatches.reduce((sum, b) => sum + b.deductedQty * b.costPrice, 0)
);
const costBatches: InventoryDeductBatch[] = deductedBatches.map((b) => ({
batchNo: b.batchNo,
deductedQty: b.deductedQty,
costPrice: b.costPrice,
}));
await reduceInventoryHoldingForMaterialPicks(client, {
skuCode,
branchCode: input.branchCode,
materialCost,
deductedBatches: costBatches,
});
await client.query(
`INSERT INTO processing_demand_picks (
task_id, sku_code, qty, net_weight, loss_qty, process_unit_price, material_cost, operator_id, remark, request_id
) VALUES ($1, $2, $3, NULL, NULL, NULL, $4, $5::uuid, $6, $7)`,
[
input.taskId,
skuCode,
input.qty,
materialCost,
asUuidOrNull(input.operatorId),
trimText(input.remark) || '管理员改领料补扣',
input.requestId,
]
);
}
async function returnCompletedDemandPickDelta(
client: PoolClient,
input: { taskId: string; taskCode: string; branchCode: string; returnQty: number }
) {
const picks = await client.query(
`SELECT id, sku_code, qty::float AS qty, COALESCE(material_cost, 0)::float AS material_cost
FROM processing_demand_picks
WHERE task_id = $1
ORDER BY created_at DESC, id DESC`,
[input.taskId]
);
const slices = planLifoPickReturns(
picks.rows.map((r) => ({
id: String(r.id),
sku_code: String(r.sku_code),
qty: Number(r.qty) || 0,
material_cost: Number(r.material_cost) || 0,
})),
input.returnQty
);
for (const slice of slices) {
const unitCost = slice.qty > 0 ? roundMoney(slice.cost / slice.qty) : 0;
const batchNo = newReturnBatchNo();
await client.query(
`INSERT INTO inventory (
batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status, branch_code,
production_date
) VALUES ($1, $2, $3, $3, NULL, $4, 10, $5, (NOW() AT TIME ZONE 'Asia/Shanghai')::date)`,
[batchNo, slice.sku_code, slice.qty, unitCost, input.branchCode]
);
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, 'processing_return', $3, 0, $3, NULL, NULL, $4)`,
[batchNo, slice.sku_code, slice.qty, `管理员改领料退料 ${input.taskCode}`]
);
if (slice.cost > 0) {
await upsertInventoryHoldingCost(client, {
cycleCode: currentCycleCode(),
branchCode: input.branchCode,
skuCode: slice.sku_code,
amount: slice.cost,
referenceId: batchNo,
referenceType: 'stock_in',
costSubtype: 'processing_return',
costSource: 'processing_return',
remarkPrefix: 'processing_return',
});
}
if (slice.remainingQty <= 1e-9) {
await client.query(`DELETE FROM processing_demand_picks WHERE id = $1`, [slice.id]);
} else {
await client.query(
`UPDATE processing_demand_picks SET qty = $2, material_cost = $3 WHERE id = $1`,
[slice.id, slice.remainingQty, slice.remainingCost]
);
}
}
}