- 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 超长修复
1792 lines
65 KiB
TypeScript
1792 lines
65 KiB
TypeScript
/**
|
||
* 仓内加工需求单:按分公司+配送日+成品 SKU+加工方式 汇总,仓管在单内领库存原料。
|
||
* (业务前提:同一订单同一商品只会有一种加工方式,验收净重按 order_code+sku_code 归属不串单)
|
||
* 成本口径:领料只扣库存、冲减持有行(在制品),不提前费用化;
|
||
* 需求单完工时按「Σ领料成本 ÷ Σ验收净重」得出成品单位成本,
|
||
* 回填订单明细 unit_cost、成品库存批次 cost_price,并按订单分摊写成本账本。
|
||
* 见 docs/design/20260823-warehouse-processing-demand-sheet.md
|
||
*/
|
||
import type { PoolClient } from 'pg';
|
||
import { pool } from '../db';
|
||
import { requiresWarehouseProcessing } from './processingMethodUtils';
|
||
import { isProcessingWorkflowEnabled } from './processingWorkflowConfigService';
|
||
import { normalizeDateOnly } from './orderDeliveryDate';
|
||
import { fifoDeductInventory, type InventoryDeductBatch as FIFODeductBatch } from './inventoryOutboundService';
|
||
import {
|
||
reduceInventoryHoldingForMaterialPicks,
|
||
type InventoryDeductBatch,
|
||
} from './processingStandaloneCostService';
|
||
import { upsertInventoryHoldingCost } from './inventorySurplusCostService';
|
||
import { listStandaloneProcessingSkuOptions } from './processingStandaloneService';
|
||
import { notVoidedByLineReturnSql } from './inboundCoverageSql';
|
||
import { healOrphanIndependentInboundsAfterPass } from './selfPurchaseStockInboundService';
|
||
import { sumAvailableQty } from './inventoryStockCoverService';
|
||
import {
|
||
claimOwnOrderReservationForProcessingPick,
|
||
resolveProcessingPickReservationSplit,
|
||
} from './processingPickReservationService';
|
||
|
||
type Db = Pick<PoolClient, 'query'>;
|
||
|
||
const PROCESS_STATUS = { pending: 10, inProgress: 20, completed: 40, rejected: 50 } as const;
|
||
const AUTO_SKIP_REMARK = '仓内加工成品:系统自动完成自采并生成待验';
|
||
const SKIP_WAREHOUSE_REMARK = '仓内加工:改采原料独立入库,成品自采跳过';
|
||
|
||
function roundQty(n: number): number {
|
||
return Math.round(n * 1000) / 1000;
|
||
}
|
||
|
||
function roundMoney(n: number): number {
|
||
return Math.round(n * 100) / 100;
|
||
}
|
||
|
||
function roundUnitCost(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')}`;
|
||
}
|
||
|
||
function trimText(v: unknown): string {
|
||
return String(v || '').trim();
|
||
}
|
||
|
||
/** 列表 linked_order_count 与删除判定必须同一 JOIN */
|
||
export const DEMAND_SHEET_LIVE_LINK_JOIN_SQL = `processing_demand_items di
|
||
JOIN order_items oi ON oi.id = di.order_item_id AND COALESCE(oi.is_returned, false) = false
|
||
JOIN orders o ON o.order_code = di.order_code AND o.deleted_at IS NULL`;
|
||
|
||
export function demandSheetLiveLinkCountExpr(taskIdSql: string): string {
|
||
return `(SELECT COUNT(*)::int FROM ${DEMAND_SHEET_LIVE_LINK_JOIN_SQL} WHERE di.task_id = ${taskIdSql})`;
|
||
}
|
||
|
||
export async function countLiveDemandSheetOrderLinks(taskId: string, db: Db = pool): Promise<number> {
|
||
const result = await db.query(
|
||
`SELECT COUNT(*)::int AS c FROM ${DEMAND_SHEET_LIVE_LINK_JOIN_SQL} WHERE di.task_id = $1`,
|
||
[taskId]
|
||
);
|
||
return Number(result.rows[0]?.c) || 0;
|
||
}
|
||
|
||
export function assertOrphanDemandSheetDeletable(input: {
|
||
sourceType: string | null | undefined;
|
||
liveCount: number;
|
||
branchCode?: string | null;
|
||
expectedBranchCode?: string | null;
|
||
}): void {
|
||
if (String(input.sourceType || '') !== 'demand') {
|
||
throw Object.assign(new Error('仅仓内需求单可按无订单关联删除'), {
|
||
status: 400,
|
||
code: 'invalid_request',
|
||
});
|
||
}
|
||
const expected = trimText(input.expectedBranchCode);
|
||
const branch = trimText(input.branchCode);
|
||
if (expected && branch !== expected) {
|
||
throw Object.assign(new Error('无权操作其它分公司的加工需求单'), {
|
||
status: 403,
|
||
code: 'branch_mismatch',
|
||
});
|
||
}
|
||
if ((Number(input.liveCount) || 0) > 0) {
|
||
throw Object.assign(new Error('该需求单仍有订单关联,不能删除'), {
|
||
status: 409,
|
||
code: 'still_linked',
|
||
});
|
||
}
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
export function isWarehouseProcessingLine(
|
||
method: string | null | undefined,
|
||
owner: string | null | undefined
|
||
): boolean {
|
||
return requiresWarehouseProcessing(method, owner);
|
||
}
|
||
|
||
export async function orderSkuHasWarehouseDemand(
|
||
orderCode: string,
|
||
skuCode: string | null | undefined,
|
||
db: Db = pool
|
||
): Promise<boolean> {
|
||
const code = trimText(orderCode);
|
||
const sku = trimText(skuCode);
|
||
if (!code || !sku) return false;
|
||
const result = await db.query(
|
||
`SELECT 1
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt ON pt.id = di.task_id
|
||
WHERE di.order_code = $1
|
||
AND di.sku_code = $2
|
||
AND pt.source_type = 'demand'
|
||
AND pt.process_status < $3
|
||
LIMIT 1`,
|
||
[code, sku, PROCESS_STATUS.rejected]
|
||
);
|
||
return Boolean(result.rowCount);
|
||
}
|
||
|
||
/** 订单仓内加工成品验收:交货,不入可领用库存。独立入库无 order_code,不走此判定。 */
|
||
export async function isWarehouseProcessingFinishedSku(
|
||
orderCode: string | null | undefined,
|
||
skuCode: string | null | undefined,
|
||
db: Db = pool
|
||
): Promise<boolean> {
|
||
const code = trimText(orderCode);
|
||
const sku = trimText(skuCode);
|
||
if (!code || !sku) return false;
|
||
if (await orderSkuHasWarehouseDemand(code, sku, db)) return true;
|
||
const items = await db.query(
|
||
`SELECT processing_method, processing_owner
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND sku_code IS NOT DISTINCT FROM $2
|
||
AND COALESCE(is_returned, false) = false`,
|
||
[code, sku]
|
||
);
|
||
return items.rows.some((row) => isWarehouseProcessingLine(row.processing_method, row.processing_owner));
|
||
}
|
||
|
||
export async function purchaseLinkedToWarehouseDemand(
|
||
purchaseCode: string,
|
||
db: Db = pool
|
||
): Promise<boolean> {
|
||
const code = trimText(purchaseCode);
|
||
if (!code) return false;
|
||
// 阈值与 autoSkip/heal/列表标记一致:未作废(<50)即视为挂接。
|
||
// 不能用 <40:需求单完工后成品自采单若仍待采,<40 会导致跳过被拒、拦截失效、可重复采购
|
||
const result = await db.query(
|
||
`SELECT 1
|
||
FROM purchase_orders po
|
||
WHERE po.purchase_code = $1
|
||
AND EXISTS (
|
||
SELECT 1
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt ON pt.id = di.task_id AND pt.source_type = 'demand' AND pt.process_status < $2
|
||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = di.order_item_id
|
||
WHERE f.purchase_code = po.purchase_code
|
||
OR (NULLIF(TRIM(po.source_id), '') IS NOT NULL AND po.source_id = di.order_item_id::text)
|
||
)
|
||
LIMIT 1`,
|
||
[code, PROCESS_STATUS.rejected]
|
||
);
|
||
return Boolean(result.rowCount);
|
||
}
|
||
|
||
async function allocateDemandTaskCode(client: Db): Promise<string> {
|
||
const date = new Date();
|
||
const ymd = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
|
||
const result = await client.query(
|
||
`SELECT COALESCE(MAX(NULLIF(REGEXP_REPLACE(task_code, '^XQG-\\d{8}-', ''), '')), '0')::int AS seq
|
||
FROM processing_tasks
|
||
WHERE task_code LIKE 'XQG-' || $1 || '-%'`,
|
||
[ymd]
|
||
);
|
||
const seq = (Number(result.rows[0]?.seq) || 0) + 1;
|
||
return `XQG-${ymd}-${String(seq).padStart(4, '0')}`;
|
||
}
|
||
|
||
/** 与唯一索引对齐:同仓同日同 SKU 同加工方式复用未作废需求单(含已完工),已入库净重随验收行重算保留 */
|
||
async function findOrCreateDemandSheet(
|
||
client: Db,
|
||
input: {
|
||
branchCode: string;
|
||
deliveryDate: string;
|
||
sku: string;
|
||
method: string;
|
||
qty: number;
|
||
}
|
||
): Promise<string> {
|
||
const existing = await client.query(
|
||
`SELECT id FROM processing_tasks
|
||
WHERE source_type = 'demand'
|
||
AND branch_code = $1
|
||
AND demand_delivery_date = $2::date
|
||
AND sku_code = $3
|
||
AND processing_method = $4
|
||
AND process_status < $5
|
||
ORDER BY process_status ASC, created_at ASC
|
||
LIMIT 1`,
|
||
[input.branchCode, input.deliveryDate, input.sku, input.method, PROCESS_STATUS.rejected]
|
||
);
|
||
if (existing.rowCount) return String(existing.rows[0].id);
|
||
|
||
// 并发兜底必须用 SAVEPOINT:事务内普通 catch 后连接已进入 aborted 状态,任何后续查询都会报错。
|
||
// 两种 23505:同一汇单键撞唯一索引 → 复用对方建的单;task_code 撞号(同日其它 SKU 并发)→ 换号重试。
|
||
let lastErr: unknown = null;
|
||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||
const taskCode = await allocateDemandTaskCode(client);
|
||
await client.query('SAVEPOINT demand_sheet_insert');
|
||
try {
|
||
const inserted = await client.query(
|
||
`INSERT INTO processing_tasks (
|
||
order_code, inspection_id, task_code, source_type, sku_code, processing_method,
|
||
source_qty, process_status, branch_code, demand_delivery_date, created_at, updated_at
|
||
) VALUES (NULL, NULL, $1, 'demand', $2, $3, $4, $5, $6, $7::date, NOW(), NOW())
|
||
RETURNING id`,
|
||
[
|
||
taskCode,
|
||
input.sku,
|
||
input.method,
|
||
input.qty,
|
||
PROCESS_STATUS.pending,
|
||
input.branchCode,
|
||
input.deliveryDate,
|
||
]
|
||
);
|
||
await client.query('RELEASE SAVEPOINT demand_sheet_insert');
|
||
return String(inserted.rows[0].id);
|
||
} catch (err) {
|
||
await client.query('ROLLBACK TO SAVEPOINT demand_sheet_insert').catch(() => undefined);
|
||
const code = String((err as { code?: string } | null)?.code || '');
|
||
if (code !== '23505') throw err;
|
||
lastErr = err;
|
||
const raced = await client.query(
|
||
`SELECT id FROM processing_tasks
|
||
WHERE source_type = 'demand'
|
||
AND branch_code = $1
|
||
AND demand_delivery_date = $2::date
|
||
AND sku_code = $3
|
||
AND processing_method = $4
|
||
AND process_status < $5
|
||
ORDER BY process_status ASC, created_at ASC
|
||
LIMIT 1`,
|
||
[input.branchCode, input.deliveryDate, input.sku, input.method, PROCESS_STATUS.rejected]
|
||
);
|
||
if (raced.rowCount) return String(raced.rows[0].id);
|
||
// task_code 撞号:下一轮重新取号
|
||
}
|
||
}
|
||
throw lastErr;
|
||
}
|
||
|
||
export async function stampWarehouseProcessingAsSelfPurchase(
|
||
orderCode: string,
|
||
client: Db
|
||
): Promise<number> {
|
||
const result = await client.query(
|
||
`UPDATE order_items
|
||
SET supplier_code = 'INTERNAL'
|
||
WHERE order_code = $1
|
||
AND COALESCE(is_returned, false) = false
|
||
AND NULLIF(TRIM(processing_method), '') IS NOT NULL
|
||
AND TRIM(processing_method) <> '原材料'
|
||
AND LOWER(TRIM(COALESCE(processing_owner, ''))) = 'warehouse'
|
||
AND (
|
||
supplier_code IS DISTINCT FROM 'INTERNAL'
|
||
)`,
|
||
[orderCode]
|
||
);
|
||
return result.rowCount || 0;
|
||
}
|
||
|
||
/** 需求单已完工(process_status=40)的订单明细 id,保存时保留分摊 unit_cost */
|
||
export async function listCompletedWarehouseDemandItemIds(
|
||
db: Db,
|
||
itemIds: string[]
|
||
): Promise<Set<string>> {
|
||
const ids = [...new Set(itemIds.map((id) => String(id || '').trim()).filter(Boolean))];
|
||
if (!ids.length) return new Set();
|
||
const result = await db.query(
|
||
`SELECT di.order_item_id::text AS id
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt ON pt.id = di.task_id
|
||
WHERE di.order_item_id = ANY($1::uuid[])
|
||
AND pt.source_type = 'demand'
|
||
AND pt.process_status = $2`,
|
||
[ids, PROCESS_STATUS.completed]
|
||
);
|
||
return new Set(result.rows.map((r) => String(r.id)));
|
||
}
|
||
|
||
export async function syncWarehouseProcessingDemandForOrder(
|
||
orderCode: string,
|
||
client: PoolClient
|
||
): Promise<void> {
|
||
const code = trimText(orderCode);
|
||
if (!code) return;
|
||
|
||
const orderResult = await client.query(
|
||
`SELECT order_code, branch_code, delivery_date, order_status, deleted_at
|
||
FROM orders
|
||
WHERE order_code = $1
|
||
LIMIT 1`,
|
||
[code]
|
||
);
|
||
const order = orderResult.rows[0];
|
||
if (!order) return;
|
||
|
||
const branchCode = trimText(order.branch_code);
|
||
const deliveryDate = normalizeDateOnly(order.delivery_date);
|
||
const orderStatus = Number(order.order_status) || 0;
|
||
const trashed = Boolean(order.deleted_at);
|
||
const workflowOn = branchCode ? await isProcessingWorkflowEnabled(branchCode) : false;
|
||
|
||
const previous = await client.query(
|
||
`SELECT task_id FROM processing_demand_items WHERE order_code = $1`,
|
||
[code]
|
||
);
|
||
const affectedTaskIds = new Set<string>(previous.rows.map((r) => String(r.task_id)));
|
||
|
||
await client.query(`DELETE FROM processing_demand_items WHERE order_code = $1`, [code]);
|
||
|
||
const skipDemand =
|
||
!workflowOn || trashed || !deliveryDate || !branchCode || orderStatus >= 90;
|
||
if (!skipDemand) {
|
||
const items = await client.query(
|
||
`SELECT id, sku_code, quantity, processing_method, processing_owner, is_extra_dish, is_returned
|
||
FROM order_items
|
||
WHERE order_code = $1`,
|
||
[code]
|
||
);
|
||
for (const row of items.rows) {
|
||
if (Boolean(row.is_returned)) continue;
|
||
if (orderStatus >= 50 && Boolean(row.is_extra_dish)) continue;
|
||
if (!isWarehouseProcessingLine(row.processing_method, row.processing_owner)) continue;
|
||
const sku = trimText(row.sku_code);
|
||
const qty = roundQty(Number(row.quantity) || 0);
|
||
if (!sku || qty <= 0) continue;
|
||
|
||
const method = trimText(row.processing_method) || '仓内加工';
|
||
const taskId = await findOrCreateDemandSheet(client, {
|
||
branchCode,
|
||
deliveryDate,
|
||
sku,
|
||
method,
|
||
qty,
|
||
});
|
||
affectedTaskIds.add(taskId);
|
||
await client.query(
|
||
`INSERT INTO processing_demand_items (task_id, order_item_id, order_code, sku_code, qty)
|
||
VALUES ($1, $2::uuid, $3, $4, $5)
|
||
ON CONFLICT (order_item_id) DO UPDATE SET
|
||
task_id = EXCLUDED.task_id,
|
||
order_code = EXCLUDED.order_code,
|
||
sku_code = EXCLUDED.sku_code,
|
||
qty = EXCLUDED.qty,
|
||
updated_at = NOW()`,
|
||
[taskId, row.id, code, sku, qty]
|
||
);
|
||
}
|
||
}
|
||
|
||
for (const taskId of affectedTaskIds) {
|
||
await recalcDemandSheetQty(taskId, client);
|
||
await recalcDemandSheetFromInspections(taskId, client);
|
||
}
|
||
|
||
if (branchCode) {
|
||
await autoSkipOpenWarehouseDemandPurchases(code, client, branchCode);
|
||
await clearStaleWarehouseDemandPurchaseFlags(client, { orderCode: code, branchCode });
|
||
}
|
||
}
|
||
|
||
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()}`;
|
||
}
|
||
|
||
/**
|
||
* 需求单作废前退料:已领未产出的原料按领料均价退回库存(新 PRT 批次),并恢复持有行。
|
||
* 已有成品入库(net_weight > 0)时不退——货已产出,库存不能凭空回来;
|
||
* 退料同时清掉本任务的完工结算账本行(成本随退料失去依据)。
|
||
*/
|
||
async function returnDemandSheetMaterials(taskId: string, client: Db): Promise<number> {
|
||
const taskResult = await client.query(
|
||
`SELECT task_code, branch_code, COALESCE(material_qty, 0)::float AS material_qty,
|
||
COALESCE(net_weight, 0)::float AS net_weight
|
||
FROM processing_tasks
|
||
WHERE id = $1 AND source_type = 'demand'
|
||
LIMIT 1`,
|
||
[taskId]
|
||
);
|
||
const task = taskResult.rows[0];
|
||
if (!task) return 0;
|
||
const materialQty = Number(task.material_qty) || 0;
|
||
const netWeight = Number(task.net_weight) || 0;
|
||
if (materialQty <= 0 || netWeight > 0) return 0;
|
||
|
||
const branchCode = trimText(task.branch_code) || null;
|
||
const taskCode = trimText(task.task_code) || taskId;
|
||
const picks = await client.query(
|
||
`SELECT 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 ASC`,
|
||
[taskId]
|
||
);
|
||
|
||
let returnedQty = 0;
|
||
for (const pick of picks.rows) {
|
||
const skuCode = trimText(pick.sku_code);
|
||
const qty = roundQty(Number(pick.qty) || 0);
|
||
if (!skuCode || qty <= 0) continue;
|
||
const cost = roundMoney(Number(pick.material_cost) || 0);
|
||
const unitCost = roundMoney(cost / qty);
|
||
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, 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)
|
||
VALUES ($1, $2, 'processing_return', $3, 0, $3, NULL, NULL, $4)`,
|
||
[batchNo, skuCode, qty, `仓内加工需求单作废退料 ${taskCode}`]
|
||
);
|
||
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',
|
||
});
|
||
}
|
||
returnedQty = roundQty(returnedQty + qty);
|
||
}
|
||
|
||
if (returnedQty > 0) {
|
||
await client.query(`DELETE FROM processing_demand_picks WHERE task_id = $1`, [taskId]);
|
||
await client.query(
|
||
`DELETE FROM cost_details
|
||
WHERE reference_type = 'processing_task' AND reference_id = $1 AND cost_type = 'purchase'`,
|
||
[taskId]
|
||
);
|
||
await writeDemandLinkedSettledUnitCost(client, taskId, null);
|
||
await client.query(
|
||
`UPDATE processing_tasks
|
||
SET material_qty = 0, material_cost = 0, loss_qty = 0, updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[taskId]
|
||
);
|
||
}
|
||
return returnedQty;
|
||
}
|
||
|
||
/**
|
||
* 需求已归零时删除仓内加工需求单(含 CASCADE 清理 demand_items / demand_picks)。
|
||
* 返回:
|
||
* - null → 任务不存在(调用方按原「作废」语义兜底处理)
|
||
* - {started:false} → 未开工,已物理删除(含 CASCADE 清理需求行与领料行)
|
||
* - {started:true} → 已领料/已产出/已完工,保留任务与状态,调用方只把需求量归零
|
||
*/
|
||
async function loadClosedWarehouseDemandSheet(taskId: string, client: Db): Promise<{
|
||
exists: boolean;
|
||
started: boolean;
|
||
} | null> {
|
||
const taskResult = await client.query(
|
||
`SELECT COALESCE(material_qty, 0)::float AS material_qty,
|
||
COALESCE(net_weight, 0)::float AS net_weight,
|
||
pt.process_status,
|
||
(SELECT COUNT(*) FROM processing_demand_picks pp WHERE pp.task_id = pt.id) AS pick_count
|
||
FROM processing_tasks pt
|
||
WHERE pt.id = $1 AND pt.source_type = 'demand'
|
||
LIMIT 1`,
|
||
[taskId]
|
||
);
|
||
const task = taskResult.rows[0];
|
||
if (!task) return null;
|
||
const started =
|
||
Number(task.material_qty) > 0 ||
|
||
Number(task.net_weight) > 0 ||
|
||
Number(task.pick_count) > 0 ||
|
||
Number(task.process_status) >= PROCESS_STATUS.completed;
|
||
if (started) {
|
||
// 已开工/已完工:保留任务与其状态(不降级成「已作废」,否则完成页签会串味、
|
||
// 完工结算与追溯记录失去依据),调用方只把需求量归零。
|
||
return { exists: true, started: true };
|
||
}
|
||
await client.query(`DELETE FROM processing_tasks WHERE id = $1 AND source_type = 'demand'`, [
|
||
taskId,
|
||
]);
|
||
return { exists: true, started: false };
|
||
}
|
||
|
||
async function recalcDemandSheetQty(taskId: string, client: Db): Promise<void> {
|
||
const sum = await client.query(
|
||
`SELECT COALESCE(SUM(qty), 0)::float AS qty,
|
||
(ARRAY_AGG(sku_code) FILTER (WHERE sku_code IS NOT NULL))[1] AS sku_code
|
||
FROM processing_demand_items
|
||
WHERE task_id = $1`,
|
||
[taskId]
|
||
);
|
||
const qty = roundQty(Number(sum.rows[0]?.qty) || 0);
|
||
if (qty <= 0) {
|
||
// 作废前先把已领未产出的原料退回库存,避免「单没了、料也没了」
|
||
await returnDemandSheetMaterials(taskId, client);
|
||
// 规则(2026-09-13):需求全部消失后加工单本身也应消失,而不是留一张
|
||
// process_status=50 的空单——否则它会落到「已完成」页签(该页签过滤为
|
||
// completed + rejected)成为幽灵行。
|
||
// 同一加工单可能被多个订单共享:只切走/删掉其中一个订单时,其它订单的需求
|
||
// 仍在(qty>0),此时只减少需求量、保留加工单;仅当最后一个需求也消失
|
||
// (qty<=0)才删单。加工已开始(已领料/已产出)的不删,保留可追溯的作废记录。
|
||
const closed = await loadClosedWarehouseDemandSheet(taskId, client);
|
||
if (closed) {
|
||
if (closed.started) {
|
||
// 已开工/已完工:状态与领料/产出保持不变,仅需求量归零。
|
||
await client.query(
|
||
`UPDATE processing_tasks
|
||
SET source_qty = 0, updated_at = NOW()
|
||
WHERE id = $1 AND source_type = 'demand'`,
|
||
[taskId]
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
await client.query(
|
||
`UPDATE processing_tasks
|
||
SET source_qty = 0, process_status = $2, updated_at = NOW()
|
||
WHERE id = $1 AND source_type = 'demand'`,
|
||
[taskId, PROCESS_STATUS.rejected]
|
||
);
|
||
return;
|
||
}
|
||
await client.query(
|
||
`UPDATE processing_tasks
|
||
SET source_qty = $2, updated_at = NOW()
|
||
WHERE id = $1 AND source_type = 'demand'`,
|
||
[taskId, qty]
|
||
);
|
||
}
|
||
|
||
export async function skipWarehouseProcessingPurchase(input: {
|
||
purchaseCode: string;
|
||
branchCode: string;
|
||
operatorRemark?: string | null;
|
||
existingClient?: PoolClient;
|
||
}): Promise<{ purchase_code: string; status: number }> {
|
||
const { updatePurchaseOrderStatus } = await import('./purchaseOperationService');
|
||
// 无外部事务时自开事务:self_processed 标记、状态推进、待验去重必须同生共死
|
||
const client = input.existingClient || (await pool.connect());
|
||
const owns = !input.existingClient;
|
||
try {
|
||
if (owns) await client.query('BEGIN');
|
||
|
||
const linked = await purchaseLinkedToWarehouseDemand(input.purchaseCode, client);
|
||
if (!linked) {
|
||
throw Object.assign(new Error('该自采单未挂仓内加工需求,不能跳过'), {
|
||
status: 400,
|
||
code: 'not_warehouse_demand_purchase',
|
||
});
|
||
}
|
||
|
||
const po = await client.query(
|
||
`SELECT purchase_qty, actual_qty, purchase_status, order_code
|
||
FROM purchase_orders WHERE purchase_code = $1 LIMIT 1`,
|
||
[input.purchaseCode]
|
||
);
|
||
const row = po.rows[0];
|
||
if (!row) {
|
||
throw Object.assign(new Error('采购单不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
const status = Number(row.purchase_status) || 0;
|
||
if (status >= 20 && status !== 32) {
|
||
throw Object.assign(new Error('该自采单已完成或已关闭'), { status: 409, code: 'already_closed' });
|
||
}
|
||
|
||
await client.query(
|
||
`UPDATE purchase_orders SET self_processed = TRUE WHERE purchase_code = $1`,
|
||
[input.purchaseCode]
|
||
);
|
||
const qty = roundQty(Number(row.actual_qty || row.purchase_qty) || 0);
|
||
if (qty <= 0) {
|
||
throw Object.assign(new Error('采购数量须大于 0 才能跳过并生成待验'), {
|
||
status: 400,
|
||
code: 'invalid_qty',
|
||
});
|
||
}
|
||
|
||
await updatePurchaseOrderStatus(
|
||
{
|
||
purchaseCode: input.purchaseCode,
|
||
branchCode: input.branchCode,
|
||
status: 20,
|
||
actualQty: qty,
|
||
actualPrice: 0,
|
||
remark: trimText(input.operatorRemark) || SKIP_WAREHOUSE_REMARK,
|
||
},
|
||
client
|
||
);
|
||
const orderCode = String(row.order_code || '').trim();
|
||
if (orderCode) {
|
||
const { pruneDuplicateSelfPurchasePendingInspections } = await import(
|
||
'./inspectionRejectFulfillmentService'
|
||
);
|
||
await pruneDuplicateSelfPurchasePendingInspections(orderCode, client);
|
||
}
|
||
|
||
if (owns) await client.query('COMMIT');
|
||
return { purchase_code: input.purchaseCode, status: 20 };
|
||
} catch (err) {
|
||
if (owns) await client.query('ROLLBACK').catch(() => undefined);
|
||
throw err;
|
||
} finally {
|
||
if (owns) client.release();
|
||
}
|
||
}
|
||
|
||
const WAREHOUSE_DEMAND_PO_LINK_SQL = `
|
||
EXISTS (
|
||
SELECT 1
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt
|
||
ON pt.id = di.task_id AND pt.source_type = 'demand' AND pt.process_status < $STATUS
|
||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = di.order_item_id
|
||
WHERE f.purchase_code = po.purchase_code
|
||
OR (
|
||
NULLIF(TRIM(po.source_id), '') IS NOT NULL
|
||
AND po.source_id = di.order_item_id::text
|
||
)
|
||
)`;
|
||
|
||
/** 列表/自采查询:自采单是否挂仓内加工需求(别名须为 po) */
|
||
export const WAREHOUSE_DEMAND_PURCHASE_EXISTS_SQL = WAREHOUSE_DEMAND_PO_LINK_SQL.replace(
|
||
'$STATUS',
|
||
'50'
|
||
);
|
||
|
||
function isWarehouseAutoCompletedRemark(remark: string | null | undefined): boolean {
|
||
const text = String(remark || '');
|
||
return text.includes(AUTO_SKIP_REMARK) || text.includes(SKIP_WAREHOUSE_REMARK);
|
||
}
|
||
|
||
/**
|
||
* 订单已不是仓内加工时:清掉成品自采残留的 self_processed,
|
||
* 尚未成功入库的系统自动完成单重开为待采。
|
||
*/
|
||
export async function clearStaleWarehouseDemandPurchaseFlags(
|
||
db: Db,
|
||
filter: { orderCode?: string; branchCode?: string }
|
||
): Promise<number> {
|
||
const orderCode = trimText(filter.orderCode);
|
||
const branchCode = trimText(filter.branchCode);
|
||
const params: unknown[] = [PROCESS_STATUS.rejected];
|
||
const where = [
|
||
'COALESCE(po.self_processed, FALSE) = TRUE',
|
||
`NOT ${WAREHOUSE_DEMAND_PO_LINK_SQL.replace('$STATUS', '$1')}`,
|
||
];
|
||
if (orderCode) {
|
||
params.push(orderCode);
|
||
where.push(`po.order_code = $${params.length}`);
|
||
}
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
where.push(
|
||
`(NULLIF(TRIM(po.branch_code), '') = $${params.length}
|
||
OR (
|
||
NULLIF(TRIM(po.branch_code), '') IS NULL
|
||
AND EXISTS (
|
||
SELECT 1 FROM orders o
|
||
WHERE o.order_code = po.order_code AND o.branch_code = $${params.length}
|
||
)
|
||
))`
|
||
);
|
||
}
|
||
|
||
const stale = await db.query(
|
||
`SELECT po.purchase_code, po.purchase_status, po.actual_price, po.remark,
|
||
po.order_code, po.sku_code
|
||
FROM purchase_orders po
|
||
WHERE ${where.join(' AND ')}`,
|
||
params
|
||
);
|
||
if (!stale.rowCount) return 0;
|
||
|
||
const codes = stale.rows.map((row) => String(row.purchase_code));
|
||
await db.query(`UPDATE purchase_orders SET self_processed = FALSE WHERE purchase_code = ANY($1::text[])`, [
|
||
codes,
|
||
]);
|
||
|
||
for (const row of stale.rows) {
|
||
if (Number(row.purchase_status) !== 20) continue;
|
||
if ((Number(row.actual_price) || 0) > 0) continue;
|
||
const remark = String(row.remark || '').trim();
|
||
if (remark && !isWarehouseAutoCompletedRemark(row.remark)) continue;
|
||
const purchaseCode = String(row.purchase_code);
|
||
const inbound = await db.query(
|
||
`SELECT 1 FROM inspections
|
||
WHERE inspection_time IS NOT NULL
|
||
AND COALESCE(actual_qty, 0) > 0
|
||
AND (
|
||
processing_details->>'purchase_code' = $1
|
||
OR processing_details->'purchase_codes' ? $1
|
||
)
|
||
LIMIT 1`,
|
||
[purchaseCode]
|
||
);
|
||
if (inbound.rowCount) continue;
|
||
await db.query(
|
||
`DELETE FROM inspections
|
||
WHERE inspection_time IS NULL
|
||
AND COALESCE(actual_qty, 0) = 0
|
||
AND processing_details->>'purchase_code' = $1
|
||
AND COALESCE(jsonb_array_length(COALESCE(processing_details->'purchase_codes', '[]'::jsonb)), 0) <= 1`,
|
||
[purchaseCode]
|
||
);
|
||
await db.query(
|
||
`UPDATE purchase_orders
|
||
SET purchase_status = 10,
|
||
actual_qty = NULL,
|
||
actual_price = NULL,
|
||
total_amount = NULL,
|
||
remark = CASE
|
||
WHEN COALESCE(remark, '') = '' THEN '取消仓内加工,恢复待采'
|
||
ELSE remark || ';取消仓内加工,恢复待采'
|
||
END
|
||
WHERE purchase_code = $1 AND purchase_status = 20`,
|
||
[purchaseCode]
|
||
);
|
||
}
|
||
return stale.rowCount;
|
||
}
|
||
|
||
function isIgnorableAutoSkipError(err: unknown): boolean {
|
||
const code = String((err as { code?: string } | null)?.code || '');
|
||
return code === 'already_closed' || code === 'not_warehouse_demand_purchase';
|
||
}
|
||
|
||
/** 分配后:把仍待采的仓内加工成品自采单自动完成并建待验 */
|
||
export async function autoSkipOpenWarehouseDemandPurchases(
|
||
orderCode: string,
|
||
client: PoolClient,
|
||
branchCode: string
|
||
): Promise<void> {
|
||
const code = trimText(orderCode);
|
||
const branch = trimText(branchCode);
|
||
if (!code || !branch) return;
|
||
const open = await client.query(
|
||
`SELECT po.purchase_code
|
||
FROM purchase_orders po
|
||
WHERE po.order_code = $1
|
||
AND COALESCE(po.purchase_status, 10) IN (10, 32)
|
||
AND ${WAREHOUSE_DEMAND_PO_LINK_SQL.replace('$STATUS', '$2')}`,
|
||
[code, PROCESS_STATUS.rejected]
|
||
);
|
||
for (const row of open.rows) {
|
||
try {
|
||
await skipWarehouseProcessingPurchase({
|
||
purchaseCode: String(row.purchase_code),
|
||
branchCode: branch,
|
||
operatorRemark: AUTO_SKIP_REMARK,
|
||
existingClient: client,
|
||
});
|
||
} catch (err) {
|
||
if (isIgnorableAutoSkipError(err)) continue;
|
||
throw err;
|
||
}
|
||
}
|
||
}
|
||
|
||
export async function syncWarehouseProcessingDemandForOrderAfterCommit(
|
||
orderCode: string
|
||
): Promise<void> {
|
||
const code = trimText(orderCode);
|
||
if (!code) return;
|
||
const client = await pool.connect();
|
||
try {
|
||
// 需要显式事务:findOrCreateDemandSheet 的并发兜底依赖 SAVEPOINT,
|
||
// 且 autocommit 下多步删除/重建中途失败会留下半成品
|
||
await client.query('BEGIN');
|
||
await syncWarehouseProcessingDemandForOrder(code, client);
|
||
await client.query('COMMIT');
|
||
} catch (err) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw err;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/** 列表自愈:历史未自动完成的仓内加工成品自采单 */
|
||
export async function healOpenWarehouseDemandPurchases(options?: {
|
||
branchCode?: string | null;
|
||
}): Promise<number> {
|
||
const branch = trimText(options?.branchCode);
|
||
await clearStaleWarehouseDemandPurchaseFlags(pool, branch ? { branchCode: branch } : {}).catch(
|
||
(err) => console.error('[warehouse-demand] clear stale purchase flags failed', err)
|
||
);
|
||
const result = await pool.query(
|
||
`SELECT po.purchase_code,
|
||
COALESCE(NULLIF(TRIM(po.branch_code), ''), NULLIF(TRIM(o.branch_code), '')) AS branch_code
|
||
FROM purchase_orders po
|
||
LEFT JOIN orders o ON o.order_code = po.order_code
|
||
WHERE COALESCE(po.purchase_status, 10) IN (10, 32)
|
||
AND ($1 = '' OR COALESCE(NULLIF(TRIM(po.branch_code), ''), NULLIF(TRIM(o.branch_code), '')) = $1)
|
||
AND ${WAREHOUSE_DEMAND_PO_LINK_SQL.replace('$STATUS', '$2')}
|
||
LIMIT 200`,
|
||
[branch, PROCESS_STATUS.rejected]
|
||
);
|
||
let n = 0;
|
||
for (const row of result.rows) {
|
||
const poBranch = trimText(row.branch_code);
|
||
if (!poBranch) continue;
|
||
try {
|
||
await skipWarehouseProcessingPurchase({
|
||
purchaseCode: String(row.purchase_code),
|
||
branchCode: poBranch,
|
||
operatorRemark: AUTO_SKIP_REMARK,
|
||
});
|
||
n += 1;
|
||
} catch (err) {
|
||
if (isIgnorableAutoSkipError(err)) continue;
|
||
console.error('[warehouse-demand] auto-skip failed', row.purchase_code, err);
|
||
}
|
||
}
|
||
return n;
|
||
}
|
||
|
||
/**
|
||
* 列表自愈:仓内加工(self_processed 或挂需求单)自采单成本价/金额一律清 0。
|
||
* 见 docs/design/20260829-warehouse-purchase-list-force-zero.md
|
||
*/
|
||
export async function healWarehousePurchaseZeroCosts(options?: {
|
||
branchCode?: string | null;
|
||
}): Promise<number> {
|
||
const branch = trimText(options?.branchCode);
|
||
// ⚠️ 性能红线(2026-09-24,勿回退成在 UPDATE 的 WHERE 里逐行 EXISTS):
|
||
// 旧写法把 WAREHOUSE_DEMAND_PO_LINK_SQL 直接嵌进 WHERE,其中 `po.source_id = di.order_item_id::text`
|
||
// 非 sargable → 对每行采购单重跑一次(本地实测 3533 行 × order_item_fulfillments 6067 行
|
||
// ≈ 2100 万次行扫描;该 UPDATE 单次 943ms 且 0 行被更新,占采购列表接口总耗时 95%)。
|
||
// 现改为「先把需求关联的采购单号算成小集合,再按 IN 做查找」,与 inboundCoverageSql.ts:73
|
||
// 的先例同一手法(本地实测 2222ms → 2.9ms);谓词与旧写法逐行等价
|
||
// (守卫全开后 EXCEPT ALL 双向 0 差,BR002/BR003/不分分公司三组均验证)。
|
||
const result = await pool.query(
|
||
`WITH demand_codes AS (
|
||
SELECT DISTINCT f.purchase_code AS pc
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt
|
||
ON pt.id = di.task_id
|
||
AND pt.source_type = 'demand'
|
||
AND pt.process_status < $2
|
||
JOIN order_item_fulfillments f ON f.order_item_id = di.order_item_id
|
||
WHERE f.purchase_code IS NOT NULL
|
||
UNION
|
||
SELECT po2.purchase_code
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt
|
||
ON pt.id = di.task_id
|
||
AND pt.source_type = 'demand'
|
||
AND pt.process_status < $2
|
||
JOIN purchase_orders po2 ON po2.source_id = di.order_item_id::text
|
||
)
|
||
UPDATE purchase_orders po
|
||
SET actual_price = 0,
|
||
purchase_price = 0,
|
||
total_amount = 0,
|
||
updated_at = NOW()
|
||
WHERE (
|
||
COALESCE(po.self_processed, FALSE) = TRUE
|
||
OR po.purchase_code IN (SELECT pc FROM demand_codes)
|
||
)
|
||
AND (
|
||
COALESCE(po.actual_price, 0) <> 0
|
||
OR COALESCE(po.purchase_price, 0) <> 0
|
||
OR COALESCE(po.total_amount, 0) <> 0
|
||
)
|
||
AND (
|
||
$1 = ''
|
||
OR NULLIF(TRIM(po.branch_code), '') = $1
|
||
OR (
|
||
NULLIF(TRIM(po.branch_code), '') IS NULL
|
||
AND EXISTS (
|
||
SELECT 1 FROM orders o
|
||
WHERE o.order_code = po.order_code AND o.branch_code = $1
|
||
)
|
||
)
|
||
)
|
||
RETURNING po.purchase_code`,
|
||
[branch, PROCESS_STATUS.rejected]
|
||
);
|
||
const codes = result.rows
|
||
.map((r) => String(r.purchase_code || '').trim())
|
||
.filter(Boolean);
|
||
if (!codes.length) return 0;
|
||
|
||
// 挂需求单:未完工成品行 unit_cost、未入库待验 purchase_price 对齐改实采置 0
|
||
await pool.query(
|
||
`UPDATE order_items oi
|
||
SET unit_cost = 0
|
||
WHERE oi.id IN (
|
||
SELECT di.order_item_id
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt
|
||
ON pt.id = di.task_id AND pt.source_type = 'demand' AND pt.process_status < 40
|
||
LEFT JOIN order_item_fulfillments f ON f.order_item_id = di.order_item_id
|
||
JOIN purchase_orders po ON (
|
||
f.purchase_code = po.purchase_code
|
||
OR (
|
||
NULLIF(TRIM(po.source_id), '') IS NOT NULL
|
||
AND po.source_id = di.order_item_id::text
|
||
)
|
||
)
|
||
WHERE po.purchase_code = ANY($1::text[])
|
||
)
|
||
AND oi.unit_cost IS DISTINCT FROM 0`,
|
||
[codes]
|
||
);
|
||
await pool.query(
|
||
`UPDATE inspections
|
||
SET purchase_price = 0
|
||
WHERE (
|
||
processing_details->>'purchase_code' = ANY($1::text[])
|
||
OR COALESCE(processing_details->'purchase_codes', '[]'::jsonb) ?| $1::text[]
|
||
)
|
||
AND COALESCE(actual_qty, 0) = 0
|
||
AND COALESCE(purchase_price, 0) <> 0`,
|
||
[codes]
|
||
);
|
||
return codes.length;
|
||
}
|
||
|
||
export async function assertWarehouseDemandPurchaseNotFinishedAsProduct(
|
||
purchaseCode: string,
|
||
actualPrice: number | null | undefined,
|
||
db: Db = pool
|
||
): Promise<void> {
|
||
const linked = await purchaseLinkedToWarehouseDemand(purchaseCode, db);
|
||
if (!linked) return;
|
||
if (actualPrice == null || Number(actualPrice) > 0) {
|
||
throw Object.assign(
|
||
new Error('仓内加工成品自采请点「跳过」,勿按成品称重完成(请用新增自采入库原料)'),
|
||
{ status: 409, code: 'warehouse_demand_use_skip' }
|
||
);
|
||
}
|
||
}
|
||
|
||
export async function pickDemandSheetMaterial(input: {
|
||
taskId: string;
|
||
skuCode: string;
|
||
qty: number;
|
||
/** 加工单价:可选,仅记录不入账 */
|
||
processUnitPrice?: number | null;
|
||
operatorId?: string | null;
|
||
remark?: string | null;
|
||
/** 操作者当前分公司:传入时校验任务归属,禁止跨分公司领料 */
|
||
expectedBranchCode?: string | null;
|
||
/** 幂等键:表单会话生成,重试/双击不产生重复领料 */
|
||
requestId?: string | null;
|
||
}): Promise<{ pick_id: string; material_cost: number }> {
|
||
const taskId = trimText(input.taskId);
|
||
const skuCode = trimText(input.skuCode);
|
||
const qty = roundQty(Number(input.qty));
|
||
const requestId = trimText(input.requestId) || null;
|
||
if (!taskId) throw Object.assign(new Error('缺少加工需求单'), { status: 400 });
|
||
if (!skuCode) throw Object.assign(new Error('请选择库存商品'), { status: 400 });
|
||
if (!Number.isFinite(qty) || qty <= 0) {
|
||
throw Object.assign(new Error('领料数量须大于 0'), { status: 400 });
|
||
}
|
||
|
||
try {
|
||
await healOrphanIndependentInboundsAfterPass(input.expectedBranchCode);
|
||
} catch (healErr) {
|
||
console.warn('[warehouse-demand] independent inbound heal skipped:', (healErr as Error)?.message);
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const task = await client.query(
|
||
`SELECT id, task_code, branch_code, process_status, source_type,
|
||
COALESCE(material_qty, 0)::float AS material_qty
|
||
FROM processing_tasks WHERE id = $1 LIMIT 1`,
|
||
[taskId]
|
||
);
|
||
// 幂等重放:同一表单会话的重试/双击直接返回首次领料结果
|
||
if (requestId) {
|
||
const replay = await client.query(
|
||
`SELECT id, material_cost::float AS material_cost
|
||
FROM processing_demand_picks
|
||
WHERE task_id = $1 AND request_id = $2
|
||
LIMIT 1`,
|
||
[taskId, requestId]
|
||
);
|
||
if (replay.rowCount) {
|
||
await client.query('COMMIT');
|
||
try {
|
||
await recalcDemandSheetFromInspections(taskId);
|
||
} catch (err) {
|
||
console.error('[warehouse-demand] 领料幂等重放后重算失败', taskId, err);
|
||
}
|
||
return {
|
||
pick_id: String(replay.rows[0].id),
|
||
material_cost: roundMoney(Number(replay.rows[0].material_cost) || 0),
|
||
};
|
||
}
|
||
}
|
||
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_STATUS.rejected) {
|
||
throw Object.assign(new Error('需求单已关闭'), { status: 409 });
|
||
}
|
||
// 误标完工且尚未领料:先重算降回待加工,再允许补领(已完工且已有料仍拒追加)
|
||
if (Number(row.process_status) >= PROCESS_STATUS.completed) {
|
||
if ((Number(row.material_qty) || 0) > 0) {
|
||
throw Object.assign(new Error('需求单已关闭'), { status: 409 });
|
||
}
|
||
await recalcDemandSheetFromInspections(taskId, client);
|
||
}
|
||
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 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 开发者批准):
|
||
* 需求单的成品就是本单已被预留的那批货 ⇒ 领料时**本单自己的预留不该挡住自己**。
|
||
* 口径:可领 = 毛可用 − **他单**预留;领料后把本单预留按量消费掉(成对,见下方 claim)。
|
||
* 独立加工领料(无订单)保持原口径不变。
|
||
* 见 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 <> ''`,
|
||
[taskId]
|
||
)
|
||
).rows.map((r) => String(r.order_code));
|
||
|
||
// 可领量 = 毛可用 − 他单预留(本单自己的预留可被本单领料消耗)
|
||
// 他单预留一次成型 = 全部在用预留 − 本单自己的在用预留(逐单号循环会算 N 倍,见测试 ①)
|
||
const grossAvailable = await sumAvailableQty(client, skuCode, branchCode);
|
||
const reservationSplit = await resolveProcessingPickReservationSplit(client, {
|
||
orderCodes: ownOrderCodes,
|
||
skuCode,
|
||
branchCode,
|
||
});
|
||
const claimableQty = Math.max(0, grossAvailable - reservationSplit.otherReserved);
|
||
if (claimableQty + 1e-9 < qty) {
|
||
throw Object.assign(
|
||
new Error(`库存不足:本分公司可用 ${claimableQty},需要 ${qty}`),
|
||
{ status: 400, code: 'insufficient_stock' }
|
||
);
|
||
}
|
||
// 领料前的本单活跃预留(供"只领了一部分"时精确降额;复用切分结果,不多查一次)
|
||
const plannedOwnReservation = reservationSplit.ownReserved;
|
||
|
||
const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = [];
|
||
await fifoDeductInventory(
|
||
client,
|
||
{
|
||
skuCode,
|
||
qty,
|
||
branchCode,
|
||
// 传本单订单号 ⇒ 内部 `getClaimableStockQty` 按「毛可用 − 他单预留」校验/扣减(与上面同口径)
|
||
orderCode: ownOrderCodes[0] || null,
|
||
// 内部预留守卫一次豁免全部本单订单号(只免第一个会把他单自己的另几张单当"他单"挡住)
|
||
reservationExemptOrderCodes: ownOrderCodes,
|
||
pickCode: String(row.task_code || taskId),
|
||
operatorId: input.operatorId || null,
|
||
itemName: skuName,
|
||
operationType: 'processing_out',
|
||
remark: `仓内加工需求领料 ${row.task_code || taskId}`,
|
||
},
|
||
(batch, deductedQty) => {
|
||
deductedBatches.push({ ...batch, deductedQty });
|
||
}
|
||
);
|
||
|
||
/**
|
||
* ⚠️ **必须成对**:领料已扣库 ⇒ 本单那部分预留要同步消费。否则「库存已扣为 0、预留仍 status=10」
|
||
* ⇒ 发车扣不到(短送)+ 加工成品又产出一份 ⇒ **同一批货算两次**。
|
||
* 只动本单自己的预留;他单预留一律不碰。
|
||
*/
|
||
await claimOwnOrderReservationForProcessingPick(client, {
|
||
orderCodes: ownOrderCodes,
|
||
skuCode,
|
||
branchCode,
|
||
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,
|
||
}));
|
||
// 需求单领料不提前费用化:仅冲减库存持有行(材料 → 在制品),
|
||
// 材料成本在需求单完工时按净重分摊到各订单(见 settleDemandSheetCostOnCompletion)
|
||
await reduceInventoryHoldingForMaterialPicks(client, {
|
||
skuCode,
|
||
branchCode,
|
||
materialCost,
|
||
deductedBatches: costBatches,
|
||
});
|
||
const inserted = 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, $4, $5, $6::uuid, $7, $8)
|
||
RETURNING id`,
|
||
[
|
||
taskId,
|
||
skuCode,
|
||
qty,
|
||
input.processUnitPrice == null ? null : roundMoney(Number(input.processUnitPrice)),
|
||
materialCost,
|
||
asUuidOrNull(input.operatorId),
|
||
trimText(input.remark) || null,
|
||
requestId,
|
||
]
|
||
);
|
||
// 领料后至少进入加工中;若已全部入库,随后 recalc 会完工
|
||
const newStatus = PROCESS_STATUS.inProgress;
|
||
await client.query(
|
||
`UPDATE processing_tasks
|
||
SET material_qty = COALESCE(material_qty, 0) + $2,
|
||
material_cost = COALESCE(material_cost, 0) + $3,
|
||
process_status = $4,
|
||
updated_at = NOW()
|
||
WHERE id = $1`,
|
||
[taskId, qty, materialCost, newStatus]
|
||
);
|
||
// 先入后领:领完再按「已领料且全部入库」判定完工
|
||
await recalcDemandSheetFromInspections(taskId, client);
|
||
await client.query('COMMIT');
|
||
return { pick_id: String(inserted.rows[0].id), material_cost: materialCost };
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
// 并发撞幂等键(两个请求同时领同一表单):回滚后返回已存在的那笔
|
||
if (requestId && String((error as { code?: string } | null)?.code || '') === '23505') {
|
||
const replay = await client.query(
|
||
`SELECT id, material_cost::float AS material_cost
|
||
FROM processing_demand_picks
|
||
WHERE task_id = $1 AND request_id = $2
|
||
LIMIT 1`,
|
||
[taskId, requestId]
|
||
);
|
||
if (replay.rowCount) {
|
||
try {
|
||
await recalcDemandSheetFromInspections(taskId);
|
||
} catch (err) {
|
||
console.error('[warehouse-demand] 领料撞键重放后重算失败', taskId, err);
|
||
}
|
||
return {
|
||
pick_id: String(replay.rows[0].id),
|
||
material_cost: roundMoney(Number(replay.rows[0].material_cost) || 0),
|
||
};
|
||
}
|
||
}
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 入库后回调:汇总该需求单下所有已入库订单行的实收净重。
|
||
* 完工须「已领料且全部入库」;只入库不领料保持待加工,不结算成本。
|
||
*/
|
||
export async function recalcDemandSheetFromInspections(
|
||
taskId: string,
|
||
client?: Db
|
||
): Promise<{ net_weight: number; completed: boolean; loss_qty: number }> {
|
||
const db = client || pool;
|
||
const taskIdTrimmed = trimText(taskId);
|
||
if (!taskIdTrimmed) return { net_weight: 0, completed: false, loss_qty: 0 };
|
||
|
||
const items = await db.query(
|
||
`SELECT di.order_item_id, di.order_code, di.sku_code, di.qty,
|
||
oi.is_returned, oi.quantity,
|
||
COALESCE(oi.stock_cover_qty, 0)::float AS stock_cover_qty,
|
||
COALESCE((
|
||
SELECT MAX(f.inventory_cover_qty)
|
||
FROM order_item_fulfillments f
|
||
WHERE f.order_item_id = oi.id
|
||
), 0)::float AS inventory_cover_qty
|
||
FROM processing_demand_items di
|
||
JOIN order_items oi ON oi.id = di.order_item_id
|
||
WHERE di.task_id = $1`,
|
||
[taskIdTrimmed]
|
||
);
|
||
if (!items.rows.length) return { net_weight: 0, completed: false, loss_qty: 0 };
|
||
|
||
let allFulfilled = true;
|
||
let totalNetWeight = 0;
|
||
|
||
for (const item of items.rows) {
|
||
if (Boolean(item.is_returned)) continue;
|
||
const inspection = await db.query(
|
||
`SELECT COALESCE(SUM(COALESCE(i.actual_qty, 0)), 0)::float AS total_actual_qty
|
||
FROM inspections i
|
||
WHERE i.order_code = $1
|
||
AND i.sku_code = $2
|
||
AND i.actual_qty > 0
|
||
AND i.inspection_time IS NOT NULL
|
||
AND COALESCE(i.compliance_status, 0) <> 30
|
||
AND ${notVoidedByLineReturnSql('i')}`,
|
||
[item.order_code, item.sku_code]
|
||
);
|
||
const actualQty = Number(inspection.rows[0]?.total_actual_qty) || 0;
|
||
totalNetWeight += actualQty;
|
||
if (actualQty > 0) continue;
|
||
|
||
const pending = await db.query(
|
||
`SELECT 1 FROM inspections
|
||
WHERE order_code = $1 AND sku_code = $2 AND inspection_time IS NULL
|
||
LIMIT 1`,
|
||
[item.order_code, item.sku_code]
|
||
);
|
||
if (pending.rowCount) {
|
||
allFulfilled = false;
|
||
continue;
|
||
}
|
||
|
||
/**
|
||
* 全损耗(开发者 2026-10-15 裁决 A):该行已有「**已完工但实收为 0**」的验收
|
||
* (`inspection_time` 非空、未作废、非退回)⇒ 视为**已交付(净重 0)**。
|
||
*
|
||
* 修前:只认「有 actual_qty>0 的验收 / 还有待验行 / 已被库存抵扣全覆盖」三种情况,
|
||
* 全损耗时三条都不成立 ⇒ `process_status` 永久停在 20(加工中)、`settleDemandSheetCostOnCompletion`
|
||
* 从不被调用 ⇒ 材料成本悬空在制品、订单行 `processing_settled_unit_cost` 恒 NULL。
|
||
*/
|
||
const zeroLossDone = await db.query(
|
||
`SELECT 1 FROM inspections i
|
||
WHERE i.order_code = $1
|
||
AND i.sku_code = $2
|
||
AND i.inspection_time IS NOT NULL
|
||
AND COALESCE(i.compliance_status, 0) <> 30
|
||
AND COALESCE(i.actual_qty, 0) = 0
|
||
AND ${notVoidedByLineReturnSql('i')}
|
||
LIMIT 1`,
|
||
[item.order_code, item.sku_code]
|
||
);
|
||
if (zeroLossDone.rowCount) continue;
|
||
|
||
const orderedQty = Number(item.quantity) || Number(item.qty) || 0;
|
||
const coveredQty = Math.max(
|
||
Number(item.inventory_cover_qty) || 0,
|
||
Number(item.stock_cover_qty) || 0
|
||
);
|
||
if (orderedQty > 0 && coveredQty >= orderedQty - 1e-9) {
|
||
continue;
|
||
}
|
||
allFulfilled = false;
|
||
}
|
||
|
||
const netWeight = roundQty(totalNetWeight);
|
||
const taskRow = await db.query(
|
||
`SELECT COALESCE(material_qty, 0)::float AS material_qty
|
||
FROM processing_tasks WHERE id = $1 LIMIT 1`,
|
||
[taskIdTrimmed]
|
||
);
|
||
const materialQty = Number(taskRow.rows[0]?.material_qty) || 0;
|
||
const hasPick = materialQty > 0;
|
||
const lossQty = roundQty(Math.max(0, materialQty - netWeight));
|
||
const completed = allFulfilled && hasPick;
|
||
if (completed) {
|
||
await db.query(
|
||
`UPDATE processing_tasks
|
||
SET net_weight = $2, loss_qty = $3, process_status = $4, updated_at = NOW()
|
||
WHERE id = $1 AND source_type = 'demand'`,
|
||
[taskIdTrimmed, netWeight, lossQty, PROCESS_STATUS.completed]
|
||
);
|
||
// 完工结算:材料成本按净重分摊回订单/库存批次/成本账本。
|
||
// 分摊失败不阻断验收与完工(下次重算/验收会幂等重试)
|
||
try {
|
||
await settleDemandSheetCostOnCompletion(taskIdTrimmed, db);
|
||
} catch (err) {
|
||
console.error('[warehouse-demand] 完工成本分摊失败', taskIdTrimmed, err);
|
||
}
|
||
} else {
|
||
await db.query(
|
||
`UPDATE processing_tasks
|
||
SET net_weight = $2,
|
||
loss_qty = $3,
|
||
process_status = CASE
|
||
WHEN COALESCE(material_qty, 0) <= 0 THEN $4::int
|
||
WHEN process_status >= $5::int THEN $6::int
|
||
ELSE process_status
|
||
END,
|
||
updated_at = NOW()
|
||
WHERE id = $1 AND source_type = 'demand'`,
|
||
[
|
||
taskIdTrimmed,
|
||
netWeight,
|
||
lossQty,
|
||
PROCESS_STATUS.pending,
|
||
PROCESS_STATUS.completed,
|
||
PROCESS_STATUS.inProgress,
|
||
]
|
||
);
|
||
}
|
||
|
||
return { net_weight: netWeight, completed, loss_qty: lossQty };
|
||
}
|
||
|
||
/**
|
||
* 需求单挂接行的完工单价快照。null=作废清除;数字=完工/全损耗写入。
|
||
* 不改 unit_cost(由 settle 另一句写,或保存订单独立清零)。
|
||
*/
|
||
async function writeDemandLinkedSettledUnitCost(
|
||
db: Db,
|
||
taskId: string,
|
||
unitCost: number | null
|
||
): Promise<void> {
|
||
await db.query(
|
||
`UPDATE order_items
|
||
SET processing_settled_unit_cost = $2::numeric
|
||
WHERE id IN (SELECT order_item_id FROM processing_demand_items WHERE task_id = $1)
|
||
AND processing_settled_unit_cost IS DISTINCT FROM $2::numeric`,
|
||
[taskId, unitCost]
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 从领料出库流水追溯原料批次供应商:无供应商码 → 自采;有 → 供应。
|
||
* 溯源合计与任务 material_cost 对不齐时,差额归自采(设计默认)。
|
||
*/
|
||
export async function resolveDemandMaterialCostBySource(
|
||
db: Db,
|
||
input: { taskId: string; taskCode: string; materialCost: number }
|
||
): Promise<{ selfCost: number; supplierCost: number }> {
|
||
const materialCost = roundMoney(Number(input.materialCost) || 0);
|
||
const taskCode = trimText(input.taskCode);
|
||
const taskId = trimText(input.taskId);
|
||
const remarks = [
|
||
`仓内加工需求领料 ${taskCode}`,
|
||
taskId && taskId !== taskCode ? `仓内加工需求领料 ${taskId}` : null,
|
||
].filter(Boolean) as string[];
|
||
|
||
if (!remarks.length || materialCost <= 0) {
|
||
return { selfCost: materialCost, supplierCost: 0 };
|
||
}
|
||
|
||
const traced = await db.query(
|
||
`SELECT
|
||
CASE
|
||
WHEN COALESCE(NULLIF(TRIM(inv.supplier_code), ''), '') = '' THEN 'self'
|
||
ELSE 'supplier'
|
||
END AS src,
|
||
COALESCE(SUM(ABS(il.quantity) * COALESCE(inv.cost_price, 0)), 0)::float AS amt
|
||
FROM inventory_logs il
|
||
LEFT JOIN LATERAL (
|
||
SELECT supplier_code, cost_price
|
||
FROM inventory
|
||
WHERE batch_no = il.batch_no
|
||
AND sku_code IS NOT DISTINCT FROM il.sku_code
|
||
ORDER BY created_at DESC NULLS LAST
|
||
LIMIT 1
|
||
) inv ON TRUE
|
||
WHERE il.operation_type = 'processing_out'
|
||
AND il.remark = ANY($1::text[])
|
||
GROUP BY 1`,
|
||
[remarks]
|
||
);
|
||
|
||
let selfCost = 0;
|
||
let supplierCost = 0;
|
||
for (const row of traced.rows) {
|
||
const amt = roundMoney(Number(row.amt) || 0);
|
||
if (String(row.src) === 'supplier') supplierCost = roundMoney(supplierCost + amt);
|
||
else selfCost = roundMoney(selfCost + amt);
|
||
}
|
||
|
||
const tracedTotal = roundMoney(selfCost + supplierCost);
|
||
if (tracedTotal <= 0) {
|
||
return { selfCost: materialCost, supplierCost: 0 };
|
||
}
|
||
// 与任务累计材料成本对齐:差额归自采
|
||
const delta = roundMoney(materialCost - tracedTotal);
|
||
if (Math.abs(delta) >= 0.01) {
|
||
selfCost = roundMoney(Math.max(0, selfCost + delta));
|
||
}
|
||
// 若自采被调成负,挤到供应侧守恒
|
||
if (selfCost < 0) {
|
||
supplierCost = roundMoney(Math.max(0, supplierCost + selfCost));
|
||
selfCost = 0;
|
||
}
|
||
const fix = roundMoney(materialCost - selfCost - supplierCost);
|
||
if (Math.abs(fix) >= 0.01) selfCost = roundMoney(selfCost + fix);
|
||
return { selfCost, supplierCost };
|
||
}
|
||
|
||
type ProcessingLedgerRow = {
|
||
orderCode: string;
|
||
subtype: string;
|
||
costSource: 'processing_self' | 'processing_supplier';
|
||
amount: number;
|
||
remark: string;
|
||
};
|
||
|
||
/** 按材料来源拆账本行;orderShareAmount/total 用于按订单分摊时的比例 */
|
||
function buildProcessingSourceLedgerRows(input: {
|
||
orderCode: string;
|
||
subtype: string;
|
||
sourceSplit: { selfCost: number; supplierCost: number };
|
||
orderShareAmount?: number;
|
||
totalMaterialCost?: number;
|
||
remarkSelf: string;
|
||
remarkSupplier: string;
|
||
}): ProcessingLedgerRow[] {
|
||
const selfCost = roundMoney(input.sourceSplit.selfCost);
|
||
const supplierCost = roundMoney(input.sourceSplit.supplierCost);
|
||
const total = roundMoney(selfCost + supplierCost);
|
||
const rows: ProcessingLedgerRow[] = [];
|
||
|
||
const scale =
|
||
input.orderShareAmount != null && total > 0
|
||
? Number(input.orderShareAmount) / total
|
||
: 1;
|
||
|
||
const push = (costSource: 'processing_self' | 'processing_supplier', raw: number, remark: string) => {
|
||
const amount =
|
||
input.orderShareAmount != null && total > 0
|
||
? roundMoney(raw * scale)
|
||
: roundMoney(raw);
|
||
if (amount <= 0) return;
|
||
rows.push({
|
||
orderCode: input.orderCode,
|
||
subtype: input.subtype,
|
||
costSource,
|
||
amount,
|
||
remark,
|
||
});
|
||
};
|
||
|
||
push('processing_self', selfCost, input.remarkSelf);
|
||
push('processing_supplier', supplierCost, input.remarkSupplier);
|
||
|
||
// 按比例拆完后用尾差对齐该订单份额
|
||
if (input.orderShareAmount != null && rows.length) {
|
||
const sum = roundMoney(rows.reduce((s, r) => s + r.amount, 0));
|
||
const gap = roundMoney(Number(input.orderShareAmount) - sum);
|
||
if (Math.abs(gap) >= 0.01) {
|
||
rows[rows.length - 1].amount = roundMoney(rows[rows.length - 1].amount + gap);
|
||
}
|
||
}
|
||
return rows.filter((r) => r.amount > 0);
|
||
}
|
||
|
||
/**
|
||
* 纯函数:把材料成本按各订单验收净重占比分摊。
|
||
* 单位成本 = 材料成本 ÷ 总净重(损耗自动摊入);单位成本与金额均为两位小数,末单吃尾差,保证合计=材料成本。
|
||
*/
|
||
export function allocateProcessingCostByWeight(
|
||
materialCost: number,
|
||
orderQtys: Array<{ orderCode: string; inspectedQty: number }>
|
||
): { unitCost: number; allocations: Array<{ orderCode: string; amount: number }> } {
|
||
const cost = roundMoney(Number(materialCost) || 0);
|
||
const positive = orderQtys
|
||
.map((r) => ({ orderCode: r.orderCode, qty: roundQty(Number(r.inspectedQty) || 0) }))
|
||
.filter((r) => r.orderCode && r.qty > 0);
|
||
const totalQty = roundQty(positive.reduce((s, r) => s + r.qty, 0));
|
||
if (cost <= 0 || totalQty <= 0 || !positive.length) {
|
||
return { unitCost: 0, allocations: [] };
|
||
}
|
||
const unitCost = roundUnitCost(cost / totalQty);
|
||
const allocations: Array<{ orderCode: string; amount: number }> = [];
|
||
let allocated = 0;
|
||
positive.forEach((row, index) => {
|
||
const isLast = index === positive.length - 1;
|
||
const amount = isLast
|
||
? Math.max(0, roundMoney(cost - allocated))
|
||
: roundMoney(row.qty * unitCost);
|
||
allocated = roundMoney(allocated + amount);
|
||
allocations.push({ orderCode: row.orderCode, amount });
|
||
});
|
||
return { unitCost, allocations };
|
||
}
|
||
|
||
/**
|
||
* 需求单完工结算:Σ领料成本 ÷ Σ验收净重 = 成品单位成本。
|
||
* 落价:订单明细 unit_cost、成品库存批次 cost_price。加工材料分摊不写 cost_details(见 20260831-processing-not-on-ledger)。
|
||
* 重算时删除本任务旧加工采购行;净重为 0 时仍回写单价 0 并清账。
|
||
*/
|
||
export async function settleDemandSheetCostOnCompletion(
|
||
taskId: string,
|
||
db: Db = pool,
|
||
options?: { overwriteInboundCostPrice?: boolean }
|
||
): Promise<{ unit_cost: number; allocated_amount: number }> {
|
||
const id = trimText(taskId);
|
||
if (!id) return { unit_cost: 0, allocated_amount: 0 };
|
||
|
||
// FOR UPDATE:事务内调用时串行化并发完工结算(autocommit 下退化为单语句锁,无副作用)
|
||
const taskResult = await db.query(
|
||
`SELECT sku_code, branch_code, task_code, COALESCE(material_cost, 0)::float AS material_cost
|
||
FROM processing_tasks
|
||
WHERE id = $1 AND source_type = 'demand'
|
||
LIMIT 1
|
||
FOR UPDATE`,
|
||
[id]
|
||
);
|
||
const task = taskResult.rows[0];
|
||
if (!task) return { unit_cost: 0, allocated_amount: 0 };
|
||
|
||
const materialCost = roundMoney(Number(task.material_cost) || 0);
|
||
const skuCode = trimText(task.sku_code);
|
||
if (materialCost <= 0 || !skuCode) return { unit_cost: 0, allocated_amount: 0 };
|
||
|
||
const clearProcessingLedger = () =>
|
||
db.query(
|
||
`DELETE FROM cost_details
|
||
WHERE reference_type = 'processing_task' AND reference_id = $1 AND cost_type = 'purchase'`,
|
||
[id]
|
||
);
|
||
|
||
// 按订单汇总验收净重(已称重入库的实收,含不合格标记)
|
||
const perOrder = await db.query(
|
||
`SELECT di.order_code,
|
||
COALESCE((
|
||
SELECT SUM(COALESCE(i.actual_qty, 0))
|
||
FROM inspections i
|
||
WHERE i.order_code = di.order_code
|
||
AND i.sku_code = $2
|
||
AND i.actual_qty > 0
|
||
AND i.inspection_time IS NOT NULL
|
||
AND COALESCE(i.compliance_status, 0) <> 30
|
||
), 0)::float AS inspected_qty
|
||
FROM processing_demand_items di
|
||
JOIN order_items oi ON oi.id = di.order_item_id
|
||
WHERE di.task_id = $1
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
GROUP BY di.order_code
|
||
ORDER BY di.order_code`,
|
||
[id, skuCode]
|
||
);
|
||
|
||
const totalInspected = roundQty(
|
||
perOrder.rows.reduce((s, r) => s + (Number(r.inspected_qty) || 0), 0)
|
||
);
|
||
|
||
if (totalInspected <= 0) {
|
||
await writeDemandLinkedSettledUnitCost(db, id, 0);
|
||
await clearProcessingLedger();
|
||
return { unit_cost: 0, allocated_amount: 0 };
|
||
}
|
||
|
||
const { unitCost, allocations } = allocateProcessingCostByWeight(
|
||
materialCost,
|
||
perOrder.rows.map((r) => ({
|
||
orderCode: String(r.order_code),
|
||
inspectedQty: Number(r.inspected_qty) || 0,
|
||
}))
|
||
);
|
||
|
||
// 只回本张需求单挂的仓内加工明细行,避免误伤同订单同 SKU 的其它行;值相同则不产生写放大
|
||
for (const orderCode of [...new Set(allocations.map((a) => a.orderCode))]) {
|
||
await db.query(
|
||
`UPDATE order_items
|
||
SET unit_cost = $3::numeric,
|
||
processing_settled_unit_cost = $3::numeric
|
||
WHERE order_code = $2
|
||
AND id IN (SELECT order_item_id FROM processing_demand_items WHERE task_id = $1)
|
||
AND (
|
||
unit_cost IS DISTINCT FROM $3::numeric
|
||
OR processing_settled_unit_cost IS DISTINCT FROM $3::numeric
|
||
)`,
|
||
[id, orderCode, unitCost]
|
||
);
|
||
}
|
||
|
||
await clearProcessingLedger();
|
||
|
||
// 成品批次成本价:默认只补 0/NULL;管理员改领料可覆盖本需求单关联入库批次
|
||
if (unitCost > 0) {
|
||
await db.query(
|
||
`UPDATE inventory SET cost_price = $2
|
||
WHERE sku_code = $3
|
||
AND (
|
||
$4::boolean
|
||
OR cost_price IS NULL
|
||
OR cost_price = 0
|
||
)
|
||
AND batch_no IN (
|
||
SELECT DISTINCT i.inbound_batch_no
|
||
FROM inspections i
|
||
WHERE i.sku_code = $3
|
||
AND i.inbound_batch_no IS NOT NULL
|
||
AND i.actual_qty > 0
|
||
AND i.inspection_time IS NOT NULL
|
||
AND COALESCE(i.compliance_status, 0) <> 30
|
||
AND i.order_code IN (
|
||
SELECT order_code FROM processing_demand_items WHERE task_id = $1
|
||
)
|
||
)`,
|
||
[id, unitCost, skuCode, Boolean(options?.overwriteInboundCostPrice)]
|
||
);
|
||
}
|
||
|
||
return { unit_cost: unitCost, allocated_amount: 0 };
|
||
}
|
||
|
||
/**
|
||
* 根据订单号查找所有关联的需求单并逐一重算净重/完工状态。
|
||
* 在智能入库完成后调用。
|
||
*/
|
||
export async function recalcDemandSheetsForOrder(
|
||
orderCode: string,
|
||
client?: Db
|
||
): Promise<Array<{ task_id: string; net_weight: number; completed: boolean; loss_qty: number }>> {
|
||
const db = client || pool;
|
||
const code = trimText(orderCode);
|
||
if (!code) return [];
|
||
|
||
const result = await db.query(
|
||
`SELECT DISTINCT di.task_id
|
||
FROM processing_demand_items di
|
||
WHERE di.order_code = $1`,
|
||
[code]
|
||
);
|
||
const results: Array<{ task_id: string; net_weight: number; completed: boolean; loss_qty: number }> = [];
|
||
for (const row of result.rows) {
|
||
const taskId = String(row.task_id);
|
||
const r = await recalcDemandSheetFromInspections(taskId, db);
|
||
results.push({ task_id: taskId, ...r });
|
||
}
|
||
return results;
|
||
}
|
||
|
||
export async function deleteOrphanDemandSheet(input: {
|
||
taskId: string;
|
||
expectedBranchCode?: string | null;
|
||
}): Promise<{ id: string; task_code: string; returned_material: boolean }> {
|
||
const taskId = trimText(input.taskId);
|
||
if (!taskId) {
|
||
throw Object.assign(new Error('缺少任务 ID'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const task = await client.query(
|
||
`SELECT id, task_code, source_type, branch_code,
|
||
COALESCE(net_weight, 0)::float AS net_weight
|
||
FROM processing_tasks
|
||
WHERE id = $1
|
||
FOR UPDATE`,
|
||
[taskId]
|
||
);
|
||
if (!task.rowCount) {
|
||
throw Object.assign(new Error('加工需求单不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
const row = task.rows[0];
|
||
const liveCount = await countLiveDemandSheetOrderLinks(taskId, client);
|
||
assertOrphanDemandSheetDeletable({
|
||
sourceType: row.source_type,
|
||
liveCount,
|
||
branchCode: row.branch_code,
|
||
expectedBranchCode: input.expectedBranchCode,
|
||
});
|
||
|
||
let returnedMaterial = false;
|
||
if ((Number(row.net_weight) || 0) <= 0) {
|
||
returnedMaterial = (await returnDemandSheetMaterials(taskId, client)) > 0;
|
||
}
|
||
|
||
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 {
|
||
id: String(row.id),
|
||
task_code: String(row.task_code || ''),
|
||
returned_material: returnedMaterial,
|
||
};
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
export async function listDemandSheetPicks(
|
||
taskId: string,
|
||
expectedBranchCode?: string | null
|
||
): Promise<
|
||
Array<{
|
||
id: string;
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
qty: number;
|
||
net_weight: number | null;
|
||
loss_qty: number | null;
|
||
process_unit_price: number | null;
|
||
material_cost: number;
|
||
created_at: string;
|
||
}>
|
||
> {
|
||
const expectedBranch = trimText(expectedBranchCode);
|
||
if (expectedBranch) {
|
||
const owner = await pool.query(
|
||
`SELECT 1 FROM processing_tasks
|
||
WHERE id = $1 AND source_type = 'demand' AND branch_code = $2
|
||
LIMIT 1`,
|
||
[taskId, expectedBranch]
|
||
);
|
||
if (!owner.rowCount) {
|
||
throw Object.assign(new Error('无权查看其它分公司的加工需求单'), {
|
||
status: 403,
|
||
code: 'branch_mismatch',
|
||
});
|
||
}
|
||
}
|
||
const result = await pool.query(
|
||
`SELECT p.id, p.sku_code, s.sku_name, p.qty, p.net_weight, p.loss_qty,
|
||
p.process_unit_price, p.material_cost, p.created_at
|
||
FROM processing_demand_picks p
|
||
LEFT JOIN skus s ON s.sku_code = p.sku_code
|
||
WHERE p.task_id = $1
|
||
ORDER BY p.created_at DESC`,
|
||
[taskId]
|
||
);
|
||
return result.rows.map((r) => ({
|
||
id: String(r.id),
|
||
sku_code: String(r.sku_code),
|
||
sku_name: r.sku_name ? String(r.sku_name) : null,
|
||
qty: Number(r.qty) || 0,
|
||
net_weight: r.net_weight == null ? null : Number(r.net_weight),
|
||
loss_qty: r.loss_qty == null ? null : Number(r.loss_qty),
|
||
process_unit_price: r.process_unit_price == null ? null : Number(r.process_unit_price),
|
||
material_cost: Number(r.material_cost) || 0,
|
||
created_at: r.created_at,
|
||
}));
|
||
}
|
||
|
||
export { listStandaloneProcessingSkuOptions };
|
||
|
||
/**
|
||
* 某需求单**自己**的源订单号(供「需求单领料」把本单预留排除出"占用")。
|
||
* 需求单不带 `processing_tasks.order_code`(领料单跨订单聚合),源单只能从需求明细取。
|
||
* 领料弹窗用它调 `listStandaloneProcessingSkuOptions({ ownOrderCodes })`。
|
||
* 见 docs/design/20261014-加工领料可用本单预留.md
|
||
*/
|
||
export async function listDemandSheetOwnOrderCodes(
|
||
taskId: string,
|
||
db: Db = pool
|
||
): Promise<string[]> {
|
||
const id = String(taskId || '').trim();
|
||
if (!id) return [];
|
||
const r = await db.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 <> ''`,
|
||
[id]
|
||
);
|
||
return r.rows.map((row) => String(row.order_code));
|
||
}
|