Files
SupplierSystem/server/src/services/processingStandaloneOutputService.ts
T
Ubuntu dd0e9a8889
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(独立加工成本): 均分总价值守恒——前端只在人工改价时提交单价,后端把舍入残差补到最后一行(损耗越多单价越高、但Σ金额=原料成本)
2026-10-23 17:36:20 +08:00

653 lines
27 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.
/**
* 独立加工单**完工**:申报成品(多行)→ 成品新批次回仓 → 损耗留痕 → 可选继承原料报告。
*
* 2026-10-23 开发者裁决(本轮已确认):
* · 原料多行、成品多行(一个原料可产出多个成品);
* · 损耗 = 原料投入合计 − 成品产出合计,**允许人工覆盖**(留痕),**不允许产出 > 投入**;
* · 成品**新批次**入库,入库成本**默认按原料成本按产出数量均分**,允许人工按行设置;
* · 损耗成本**只留痕、不进账本**(沿用 2026-10-15 裁决);
* · 报告继承**可选**:库存批次报告 / 检验报告 各自勾选;原料没有报告就继承不到(不造空报告)。
*
* 见 docs/design/20261023-独立加工多产出与成品回仓.md
*/
import type { PoolClient } from 'pg';
import { pool } from '../db';
import { upsertInventoryHoldingCost } from './inventorySurplusCostService';
const PROCESS_STATUS_COMPLETED = 40;
function trimText(v: unknown): string {
return String(v || '').trim();
}
function roundQty(n: number): number {
return Math.round(n * 1000) / 1000;
}
function roundMoney(n: number): number {
return Math.round(n * 100) / 100;
}
function currentCycleCode(): string {
const d = new Date();
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}`;
}
export interface StandaloneOutputInput {
skuCode: string;
qty: number;
/** 人工设置的单位成本;空 ⇒ 按原料成本均分 */
unitCost?: number | null;
/** 继承库存批次报告 */
inheritBatchReport?: boolean;
/** 继承检验报告(原料批次有检验记录时) */
inheritInspectionReport?: boolean;
}
export interface CompleteStandaloneProcessingInput {
taskId: string;
branchCode: string;
outputs: StandaloneOutputInput[];
/** 人工覆盖损耗;不填 ⇒ 自动差额 */
lossQty?: number | null;
operatorId?: string | null;
}
export interface CompleteStandaloneProcessingResult {
task_id: string;
task_code: string;
material_qty: number;
material_cost: number;
output_qty: number;
loss_qty: number;
/** 损耗是否人工覆盖 */
loss_manual: boolean;
outputs: Array<{
id: string;
sku_code: string;
sku_name: string | null;
qty: number;
unit: string | null;
unit_cost: number;
cost_amount: number;
batch_no: string;
inherit_batch_report: boolean;
inherit_inspection_report: boolean;
}>;
}
function businessError(message: string, code: string, status = 400) {
return Object.assign(new Error(message), { status, code });
}
export async function completeStandaloneProcessingTask(
input: CompleteStandaloneProcessingInput
): Promise<CompleteStandaloneProcessingResult> {
const taskId = trimText(input.taskId);
const branchCode = trimText(input.branchCode);
if (!taskId) throw businessError('缺少加工单 id', 'invalid_request');
if (!branchCode) throw businessError('请选择当前操作分公司', 'branch_required');
const rawOutputs = Array.isArray(input.outputs) ? input.outputs : [];
if (!rawOutputs.length) throw businessError('请至少添加一行成品', 'invalid_request');
const outputs = rawOutputs.map((row, idx) => {
const skuCode = trimText(row?.skuCode);
const qty = roundQty(Number(row?.qty));
const unitCost =
row?.unitCost == null || String(row.unitCost).trim() === '' ? null : Number(row.unitCost);
if (!skuCode) throw businessError(`第 ${idx + 1} 行成品未选择商品`, 'invalid_request');
if (!Number.isFinite(qty) || qty <= 0) throw businessError(`第 ${idx + 1} 行成品数量须大于 0`, 'invalid_request');
if (unitCost != null && (!Number.isFinite(unitCost) || unitCost < 0)) {
throw businessError(`第 ${idx + 1} 行成品成本价无效`, 'invalid_request');
}
return {
skuCode,
qty,
unitCost: unitCost == null ? null : Math.round(unitCost * 10000) / 10000,
inheritBatchReport: row?.inheritBatchReport === true,
inheritInspectionReport: row?.inheritInspectionReport === true,
};
});
const client = await pool.connect();
try {
await client.query('BEGIN');
const taskRes = await client.query<{
id: string;
task_code: string;
source_type: string | null;
process_status: number;
branch_code: string | null;
}>(
`SELECT id, task_code, source_type, process_status, branch_code
FROM processing_tasks WHERE id = $1 FOR UPDATE`,
[taskId]
);
const task = taskRes.rows[0];
if (!task) throw businessError('加工单不存在', 'not_found', 404);
if (String(task.source_type || '') !== 'standalone') {
throw businessError('只有独立加工单可以在这里申报成品', 'invalid_source');
}
if (String(task.branch_code || '') !== branchCode) {
throw businessError('加工单不属于当前分公司', 'branch_mismatch', 403);
}
if (Number(task.process_status) >= PROCESS_STATUS_COMPLETED) {
throw businessError('该加工单已完成,不能重复申报成品', 'already_completed');
}
const taskCode = String(task.task_code || '');
const materialRes = await client.query<{
sku_code: string;
sku_name: string | null;
qty: string;
material_cost: string;
deducted_batches: unknown;
}>(
`SELECT sku_code, sku_name, qty, material_cost, deducted_batches
FROM processing_task_materials WHERE task_id = $1 ORDER BY created_at ASC`,
[taskId]
);
if (!materialRes.rowCount) {
// 老单(改造前只存单据头,没有原料行)⇒ 用单据头兜底
const header = await client.query<{ sku_code: string; source_qty: string; material_cost: string }>(
`SELECT sku_code, COALESCE(material_qty, source_qty, 0) AS source_qty,
COALESCE(material_cost, 0) AS material_cost
FROM processing_tasks WHERE id = $1`,
[taskId]
);
const h = header.rows[0];
materialRes.rows.push({
sku_code: String(h?.sku_code || ''),
sku_name: null,
qty: String(h?.source_qty || 0),
material_cost: String(h?.material_cost || 0),
deducted_batches: [],
} as never);
}
const materialQty = roundQty(
materialRes.rows.reduce((sum, row) => sum + (Number(row.qty) || 0), 0)
);
const materialCost = roundMoney(
materialRes.rows.reduce((sum, row) => sum + (Number(row.material_cost) || 0), 0)
);
const outputQty = roundQty(outputs.reduce((sum, row) => sum + row.qty, 0));
if (outputQty > materialQty + 1e-6) {
throw businessError(
`产出合计(${outputQty})不能大于原料投入合计(${materialQty})`,
'output_exceeds_input'
);
}
const autoLoss = roundQty(materialQty - outputQty);
const lossManual = input.lossQty != null && String(input.lossQty).trim() !== '';
const lossQty = lossManual ? roundQty(Number(input.lossQty)) : autoLoss;
if (!Number.isFinite(lossQty) || lossQty < -1e-6) {
throw businessError('损耗数量不能为负数', 'invalid_loss');
}
if (outputQty + lossQty > materialQty + 1e-6) {
throw businessError(
`产出 + 损耗(${roundQty(outputQty + lossQty)})不能大于原料投入(${materialQty})`,
'loss_over_input'
);
}
/**
* 成本计划(2026-10-23 开发者:「加工 50 斤 × 6 元 = 300 总价值,产出 49 斤均分后总价值仍应是 300」):
* · 未人工改价 ⇒ 单价 = 原料成本 ÷ 产出合计(4 位小数),**金额按行四舍五入到分**;
* · 舍入残差(如 49 × 6.1224 = 299.888 → 299.89)**补到最后一行**,保证 Σ金额 == 原料成本(总价值守恒);
* · 有人工改价 ⇒ 尊重人工值,不做残差补差(否则会把人工价悄悄改掉)。
*/
const allAutoCost = outputs.every((row) => row.unitCost == null);
const costPlans = outputs.map((row) => {
const unitCost = row.unitCost == null ? Math.round((materialCost / outputQty) * 10000) / 10000 : row.unitCost;
return { unitCost, amount: roundMoney(row.qty * unitCost) };
});
if (allAutoCost && costPlans.length) {
const sumAmount = roundMoney(costPlans.reduce((sum, plan) => sum + plan.amount, 0));
const residue = roundMoney(materialCost - sumAmount);
if (Math.abs(residue) >= 0.01) {
const last = costPlans[costPlans.length - 1];
last.amount = roundMoney(last.amount + residue);
const lastQty = Number(outputs[outputs.length - 1].qty) || 0;
if (lastQty > 0) last.unitCost = Math.round((last.amount / lastQty) * 10000) / 10000;
}
}
const inserted: CompleteStandaloneProcessingResult['outputs'] = [];
const materialBatchNos = [
...new Set(
materialRes.rows.flatMap((row) => {
const list = Array.isArray(row.deducted_batches) ? (row.deducted_batches as unknown[]) : [];
return list
.map((x) => trimText((x as { batch_no?: unknown })?.batch_no))
.filter(Boolean);
})
),
];
const materialSkuCodes = [...new Set(materialRes.rows.map((r) => trimText(r.sku_code)).filter(Boolean))];
/**
* 成品默认继承原料批次的「生产日期 / 保质期 / 产地」(开发者 2026-10-23 要求)。
* 规则:以**最早到期**的原料批次为主批(各字段取自同一批,保证日期/产地口径一致);
* 主批某字段为空时,回退到其它原料批次的第一个非空值;没有原料批次信息则保持 NULL。
* 注意:只写批次级的 `inventory.production_date/expiry_date/shelf_life/origin`,不回写商品档案。
*
* ⚠️ 必须连 `shelf_life`(保质期**原文**)一起继承:库存管理「修改」弹窗改生产日期时,
* 服务端会用「生产日期 + 保质期」重算有效期(推不出则**清空**)。只继承算好的
* `expiry_date` 而不继承 `shelf_life`,操作员一改生产日期就会把有效期弄丢。
*/
const materialBatchRows = materialBatchNos.length
? (
await client.query<{
batch_no: string;
production_date: string | null;
expiry_date: string | null;
shelf_life: string | null;
origin: string | null;
}>(
`SELECT batch_no, production_date, expiry_date, shelf_life, origin
FROM inventory
WHERE batch_no = ANY($1::text[])
AND sku_code = ANY($2::text[])`,
[materialBatchNos, materialSkuCodes]
)
).rows
: [];
const batchTime = (value: string | null) => {
if (!value) return Number.POSITIVE_INFINITY;
const t = new Date(value).getTime();
return Number.isNaN(t) ? Number.POSITIVE_INFINITY : t;
};
const primaryMaterialBatch = [...materialBatchRows].sort(
(a, b) => batchTime(a.expiry_date) - batchTime(b.expiry_date)
)[0];
const pickBatchField = <K extends 'production_date' | 'expiry_date' | 'shelf_life' | 'origin'>(key: K) =>
primaryMaterialBatch?.[key] ??
materialBatchRows.find((row) => row[key] != null && row[key] !== '')?.[key] ??
null;
const inheritedProductionDate = pickBatchField('production_date');
const inheritedExpiryDate = pickBatchField('expiry_date');
const inheritedShelfLife = pickBatchField('shelf_life');
const inheritedOrigin = pickBatchField('origin');
for (const [idx, output] of outputs.entries()) {
const skuRes = await client.query<{ sku_code: string; sku_name: string | null; unit: string | null; spec: string | null }>(
`SELECT sku_code, sku_name, unit, spec FROM skus WHERE sku_code = $1 LIMIT 1`,
[output.skuCode]
);
if (!skuRes.rowCount) throw businessError(`第 ${idx + 1} 行成品商品不存在`, 'not_found', 404);
const sku = skuRes.rows[0];
const plan = costPlans[idx];
const unitCost = plan.unitCost;
const costAmount = plan.amount;
/**
* 新批次号:`PG-<任务 uuid 前 8 位>-<行号>`。
* ⚠️ **不能用 task_code**(2026-10-23 核查发现):删除加工单会删掉单据行,取号走"当日 MAX+1"
* 就会**重复使用**同一个 task_code,而批次号由 task_code 派生 ⇒ 撞 `inventory_sku_code_batch_no_key`。
* uuid 永不复用,天然唯一;撞号仍加随机后缀兜底。
*/
const taskKey = taskId.replace(/-/g, '').slice(0, 8);
let batchNo = `PG-${taskKey}-${idx + 1}`;
for (let attempt = 0; attempt < 5; attempt += 1) {
const exists = await client.query(`SELECT 1 FROM inventory WHERE batch_no = $1 LIMIT 1`, [batchNo]);
if (!exists.rowCount) break;
batchNo = `PG-${taskKey}-${idx + 1}-${Math.random().toString(36).slice(2, 6)}`;
}
const invRes = await client.query<{ id: string }>(
`INSERT INTO inventory (
batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status,
branch_code, production_date, expiry_date, shelf_life, origin, spec
) VALUES ($1, $2, $3, $3, NULL, $4, 10, $5, $6, $7, $8, $9, NULLIF(TRIM($10), ''))
RETURNING id`,
[
batchNo,
output.skuCode,
output.qty,
unitCost,
branchCode,
inheritedProductionDate,
inheritedExpiryDate,
inheritedShelfLife,
inheritedOrigin,
String(sku.spec || ''),
]
);
const inventoryId = String(invRes.rows[0]?.id || '');
await client.query(
`INSERT INTO inventory_logs (
batch_no, sku_code, operation_type, quantity, before_qty, after_qty,
related_order_code, operator_id, remark, branch_code
) VALUES ($1, $2, 'processing_in', $3, 0, $3, NULL, $4, $5, $6)`,
[batchNo, output.skuCode, output.qty, input.operatorId || null, `独立加工产出 ${taskCode}`, branchCode]
);
// 库存持有成本(有货就得有值;与独立入库同一桶)
await upsertInventoryHoldingCost(client, {
cycleCode: currentCycleCode(),
branchCode,
skuCode: output.skuCode,
amount: costAmount,
referenceId: inventoryId,
operatorId: input.operatorId || null,
unitPrice: unitCost,
surplusQty: output.qty,
costSource: 'processing_output',
referenceType: 'processing_output',
costSubtype: 'processing_output',
remarkPrefix: `独立加工产出 ${taskCode}`,
});
/** 报告继承(可选):只复制**关联**,不复制报告本体 */
let inheritedBatchReports = 0;
let inheritedInspectionReports = 0;
if (output.inheritBatchReport && materialBatchNos.length) {
const reports = await client.query<{ report_id: string }>(
`SELECT DISTINCT report_id FROM inventory_batch_report_matches
WHERE batch_no = ANY($1::text[]) AND sku_code = ANY($2::text[])`,
[materialBatchNos, materialSkuCodes]
);
for (const row of reports.rows) {
await client.query(
`INSERT INTO inventory_batch_report_matches
(report_id, inventory_id, sku_code, product_name, batch_no, production_date, match_source, confirmed_at)
VALUES ($1, $2, $3, $4, $5, NULL, 'inherit', NOW())
ON CONFLICT DO NOTHING`,
[row.report_id, inventoryId, output.skuCode, sku.sku_name || null, batchNo]
);
inheritedBatchReports += 1;
}
}
if (output.inheritInspectionReport && materialBatchNos.length) {
const photos = await client.query<{ photos: unknown }>(
`SELECT inspection_photos AS photos FROM inspections
WHERE inbound_batch_no = ANY($1::text[])
AND COALESCE(array_length(inspection_photos, 1), 0) > 0`,
[materialBatchNos]
);
const files = [
...new Set(
photos.rows.flatMap((r) => (Array.isArray(r.photos) ? r.photos.map((x) => String(x)) : []))
),
].filter(Boolean);
if (files.length) {
const reportRes = await client.query<{ id: string }>(
`INSERT INTO inventory_batch_reports
(branch_code, report_no, report_type, file_paths, product_names, status, uploaded_by, uploaded_at)
VALUES ($1, $2, 'inspection_inherit', $3::text[], $4::text[], 20, $5, NOW())
RETURNING id`,
[branchCode, `INH-${taskCode}-${idx + 1}`, files, [String(sku.sku_name || '')], input.operatorId || null]
);
await client.query(
`INSERT INTO inventory_batch_report_matches
(report_id, inventory_id, sku_code, product_name, batch_no, production_date, match_source, confirmed_at)
VALUES ($1, $2, $3, $4, $5, NULL, 'inherit', NOW())
ON CONFLICT DO NOTHING`,
[reportRes.rows[0]?.id, inventoryId, output.skuCode, sku.sku_name || null, batchNo]
);
inheritedInspectionReports += 1;
}
}
const outRes = await client.query<{ id: string }>(
`INSERT INTO processing_task_outputs
(task_id, sku_code, sku_name, spec, unit, qty, unit_cost, cost_amount, batch_no, inventory_id,
inherit_batch_report, inherit_inspection_report)
VALUES ($1, $2, $3, NULLIF(TRIM($4), ''), NULLIF(TRIM($5), ''), $6, $7, $8, $9, $10, $11, $12)
RETURNING id`,
[
taskId,
output.skuCode,
sku.sku_name || null,
String(sku.spec || ''),
String(sku.unit || ''),
output.qty,
unitCost,
costAmount,
batchNo,
inventoryId,
output.inheritBatchReport,
output.inheritInspectionReport,
]
);
inserted.push({
id: String(outRes.rows[0]?.id || ''),
sku_code: output.skuCode,
sku_name: sku.sku_name || null,
qty: output.qty,
unit: sku.unit || null,
unit_cost: unitCost,
cost_amount: costAmount,
batch_no: batchNo,
inherit_batch_report: output.inheritBatchReport && inheritedBatchReports > 0,
inherit_inspection_report: output.inheritInspectionReport && inheritedInspectionReports > 0,
});
}
await client.query(
`UPDATE processing_tasks
SET process_status = $2,
loss_qty = $3,
gross_weight = $4,
net_weight = $5,
completed_at = NOW(),
updated_at = NOW()
WHERE id = $1`,
[taskId, PROCESS_STATUS_COMPLETED, lossQty, materialQty, outputQty]
);
await client.query('COMMIT');
return {
task_id: taskId,
task_code: taskCode,
material_qty: materialQty,
material_cost: materialCost,
output_qty: outputQty,
loss_qty: lossQty,
loss_manual: lossManual,
outputs: inserted,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/** 读侧:单据的原料行与成品行(详情/列表渲染用) */
export async function listStandaloneMaterialsAndOutputs(taskId: string): Promise<{
materials: Array<{ sku_code: string; sku_name: string | null; qty: number; material_cost: number }>;
outputs: Array<{
sku_code: string;
sku_name: string | null;
qty: number;
unit: string | null;
unit_cost: number;
cost_amount: number;
batch_no: string | null;
inherit_batch_report: boolean;
inherit_inspection_report: boolean;
}>;
}> {
const id = trimText(taskId);
if (!id) return { materials: [], outputs: [] };
const [m, o] = await Promise.all([
pool.query(
`SELECT sku_code, sku_name, qty, material_cost FROM processing_task_materials
WHERE task_id = $1 ORDER BY created_at ASC`,
[id]
),
pool.query(
`SELECT sku_code, sku_name, qty, unit, unit_cost, cost_amount, batch_no,
inherit_batch_report, inherit_inspection_report
FROM processing_task_outputs WHERE task_id = $1 ORDER BY created_at ASC`,
[id]
),
]);
return {
materials: m.rows.map((r) => ({
sku_code: String(r.sku_code),
sku_name: r.sku_name ? String(r.sku_name) : null,
qty: Number(r.qty) || 0,
material_cost: Number(r.material_cost) || 0,
})),
outputs: o.rows.map((r) => ({
sku_code: String(r.sku_code),
sku_name: r.sku_name ? String(r.sku_name) : null,
qty: Number(r.qty) || 0,
unit: r.unit ? String(r.unit) : null,
unit_cost: Number(r.unit_cost) || 0,
cost_amount: Number(r.cost_amount) || 0,
batch_no: r.batch_no ? String(r.batch_no) : null,
inherit_batch_report: r.inherit_batch_report === true,
inherit_inspection_report: r.inherit_inspection_report === true,
})),
};
}
/**
* 独立加工单**删除/作废**(2026-10-23 开发者:「提交完工的单子可以点击删除」)。
*
* 安全口径(不能凭空造货/毁货):
* · 成品批次**未被领用/出库**(在库量 = 产出量、状态 10、无出库流水)才允许删;
* 任一成品已被领用 ⇒ 拒绝并说明(否则删单会凭空多出原料、凭空少掉成品)。
* · 原料按**领料行成本**退回库存(新 `PRT` 批次 + `processing_return` 流水 + 恢复持有成本);
* · 成品批次、报告关联、持有成本、行数据与单据一并删除(单据硬删,流水留痕)。
* 权限:路由层限管理员(与需求单删除同口径)。
*/
export async function deleteStandaloneProcessingTask(input: {
taskId: string;
branchCode: string;
operatorId?: string | null;
}): Promise<{ task_code: string; returned_materials: number; removed_outputs: number }> {
const taskId = trimText(input.taskId);
const branchCode = trimText(input.branchCode);
if (!taskId) throw businessError('缺少加工单 id', 'invalid_request');
const client = await pool.connect();
try {
await client.query('BEGIN');
const taskRes = await client.query<{ id: string; task_code: string; source_type: string | null; branch_code: string | null }>(
`SELECT id, task_code, source_type, branch_code FROM processing_tasks WHERE id = $1 FOR UPDATE`,
[taskId]
);
const task = taskRes.rows[0];
if (!task) throw businessError('加工单不存在', 'not_found', 404);
if (String(task.source_type || '') !== 'standalone') {
throw businessError('只有独立加工单可以在这里删除', 'invalid_source');
}
if (String(task.branch_code || '') !== branchCode) {
throw businessError('加工单不属于当前分公司', 'branch_mismatch', 403);
}
const taskCode = String(task.task_code || '');
const outputs = await client.query<{ inventory_id: string | null; batch_no: string | null; sku_code: string; qty: string }>(
`SELECT inventory_id, batch_no, sku_code, qty FROM processing_task_outputs WHERE task_id = $1`,
[taskId]
);
for (const row of outputs.rows) {
const inventoryId = trimText(row.inventory_id);
const batchNo = trimText(row.batch_no);
if (!inventoryId && !batchNo) continue;
const inv = await client.query<{ quantity: string; available_qty: string }>(
`SELECT quantity, COALESCE(available_qty, 0) AS available_qty FROM inventory WHERE id = $1`,
[inventoryId || null]
);
const live = inv.rows[0];
if (live && Math.abs(Number(live.available_qty) - Number(live.quantity)) > 1e-6) {
throw businessError(
`成品批次 ${batchNo} 已被领用/出库(可用 ${live.available_qty} / 入库 ${live.quantity}),不能删除此加工单`,
'output_in_use'
);
}
const outbound = await client.query(
`SELECT 1 FROM inventory_logs
WHERE batch_no = $1 AND quantity > 0
AND operation_type IN ('picking_out', 'delivery_loading_out', 'processing_out', 'retail_out')
LIMIT 1`,
[batchNo]
);
if (outbound.rowCount) {
throw businessError(`成品批次 ${batchNo} 已有出库记录,不能删除此加工单`, 'output_in_use');
}
}
// ① 退回原料(按领料行成本建新批次;与需求单作废退料同口径)
const materials = await client.query<{
sku_code: string;
sku_name: string | null;
qty: string;
material_cost: string;
}>(`SELECT sku_code, sku_name, qty, material_cost FROM processing_task_materials WHERE task_id = $1`, [taskId]);
let returnedMaterials = 0;
for (const row of materials.rows) {
const skuCode = trimText(row.sku_code);
const qty = roundQty(Number(row.qty) || 0);
const cost = roundMoney(Number(row.material_cost) || 0);
if (!skuCode || qty <= 0) continue;
const unitCost = qty > 0 ? Math.round((cost / qty) * 10000) / 10000 : 0;
const taskKey = taskId.replace(/-/g, '').slice(0, 8);
let batchNo = `PRT-${taskKey}-${returnedMaterials + 1}`;
for (let attempt = 0; attempt < 5; attempt += 1) {
const exists = await client.query(`SELECT 1 FROM inventory WHERE batch_no = $1 LIMIT 1`, [batchNo]);
if (!exists.rowCount) break;
batchNo = `PRT-${taskKey}-${returnedMaterials + 1}-${Math.random().toString(36).slice(2, 6)}`;
}
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, skuCode, qty, unitCost, 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, branch_code)
VALUES ($1, $2, 'processing_return', $3, 0, $3, NULL, $4, $5, $6)`,
[batchNo, skuCode, qty, input.operatorId || null, `独立加工单删除退料 ${taskCode}`, branchCode]
);
if (cost > 0) {
await upsertInventoryHoldingCost(client, {
cycleCode: currentCycleCode(),
branchCode,
skuCode,
amount: cost,
referenceId: batchNo,
referenceType: 'stock_in',
costSubtype: 'processing_return',
costSource: 'processing_return',
remarkPrefix: 'processing_return',
});
}
returnedMaterials += 1;
}
// ② 删除成品批次(含报告关联与持有成本)
for (const row of outputs.rows) {
const inventoryId = trimText(row.inventory_id);
if (inventoryId) {
await client.query(`DELETE FROM inventory_batch_report_matches WHERE inventory_id = $1`, [inventoryId]);
await client.query(
`DELETE FROM cost_details WHERE cost_type = 'inventory_holding' AND reference_type = 'processing_output' AND reference_id = $1`,
[inventoryId]
);
await client.query(`DELETE FROM inventory WHERE id = $1`, [inventoryId]);
}
}
await client.query(`DELETE FROM processing_task_outputs WHERE task_id = $1`, [taskId]);
await client.query(`DELETE FROM processing_task_materials WHERE task_id = $1`, [taskId]);
await client.query(`DELETE FROM cost_details WHERE reference_type = 'processing_task' AND reference_id = $1`, [taskId]);
await client.query(`DELETE FROM processing_tasks WHERE id = $1`, [taskId]);
await client.query('COMMIT');
return { task_code: taskCode, returned_materials: returnedMaterials, removed_outputs: outputs.rowCount || 0 };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}