/** * 管理员改已完成仓内需求单领料。禁止调用 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 { getClaimableStockQty } 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); // 与需求单领料同口径:只能领「毛可用 − 全部在用预留」 // 见 docs/design/20260922-processing-pick-respect-reservations.md const availableQty = await getClaimableStockQty(client, skuCode, input.branchCode, null); if (availableQty + 1e-9 < input.qty) { throw Object.assign(new Error(`库存不足:本分公司可用 ${availableQty},需要 ${input.qty}`), { status: 400, code: 'insufficient_stock', }); } const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = []; await fifoDeductInventory( client, { skuCode, qty: input.qty, branchCode: input.branchCode, orderCode: null, pickCode: input.taskCode, operatorId: input.operatorId || null, itemName: skuName, operationType: 'processing_out', remark: `管理员改领料补扣 ${input.taskCode}`, }, (batch, deductedQty) => { deductedBatches.push({ ...batch, deductedQty }); } ); 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] ); } } }