Files
SupplierSystem/server/src/services/purchaseAmendService.ts
T
Ubuntu b56293f9bf
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-11-03 13:17:55 +08:00

575 lines
23 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.
import type { PoolClient } from 'pg';
import { pool } from '../db';
import { orderReceivedQtyDb, writeOrderItemReceivedQtyWithStockCover } from './orderItemReceivedQtyService';
import { assertPurchaseOrderInBranch } from './purchaserBranchScope';
import { writeAuditLog } from './auditService';
import { syncOrderItemsFromSupplyCompletion } from './orderItemSupplyUnitSync';
import { syncSkuCostFromPreparation } from './preparationCostService';
import { reconcileOrderPurchaseFromLatestInspections } from './inspectionComplianceService';
import { applyInboundBatchQtyDelta } from './inventoryAdjustService';
import { assertSupplyCostPrice, clearPlanPriceForZeroCost } from './supplyCostPrice';
import { isZeroSupplyCostAllowed } from './zeroSupplyCostConfigService';
export type AmendPurchaseActualInput = {
purchaseCode: string;
branchCode: string;
actualQty?: number | null;
actualPrice?: number | null;
unit?: string | null;
remark?: string | null;
operatorId?: string | null;
operatorName?: string | null;
operatorRole?: string | null;
/** 上游订单已先完成数量/单位/售价同步时,避免反向按采购单位再次改订单行 */
skipOrderItemSync?: boolean;
/** 保留改单写入的订单成本与报价成本,不用既有实采价反向覆盖 */
preserveOrderEnteredCost?: boolean;
/**
* 方案 C(docs/design/20260920-self-purchase-actual-qty-single-writer.md):
* 自采 UI 入口置 true —— 本接口不改实收数量,只改价格/单位/备注。
* 服务端可信调用方(订单明细编辑等)不传,行为与改动前一致。
*/
preserveActualQty?: boolean;
/**
* 口径(2026-10-10 裁决,见 docs/design/20261014-self-purchase-completed-scope.md):
* 自采 UI 入口置 true —— **未入库(< 30)** 的行允许改「交数」实收;
* **已入库(30) 行的实收只由管理员改**(订单详情「管理员改实收」,会同步调批次库存)⇒ 忽略传入值。
*/
preserveActualQtyWhenInbound?: boolean;
};
export type AmendPurchaseActualResult = {
success: true;
purchase_code: string;
needs_customer_price: boolean;
needs_customer_price_item_ids: string[];
reconciled: boolean;
cost_updated: boolean;
inventory_adjusted?: boolean;
inventory_batch_no?: string | null;
/** 有批次号但未改库存(过手无台账 / 合单从单) */
inventory_skipped?: boolean;
inventory_skip_reason?: 'no_inventory_row' | 'merge_guest' | null;
};
/**
* 自采待仓验(20)/已完成(30) 改实采数量、单价、单位:写审计日志并同步验收/成本。
*/
export async function amendPurchaseActual(
input: AmendPurchaseActualInput,
existingClient?: PoolClient
): Promise<AmendPurchaseActualResult> {
const client = existingClient || (await pool.connect());
const ownsClient = !existingClient;
try {
if (ownsClient) await client.query('BEGIN');
const purchaseCode = String(input.purchaseCode || '').trim();
if (!purchaseCode) {
throw Object.assign(new Error('缺少采购单号'), { status: 400, code: 'invalid_request' });
}
await assertPurchaseOrderInBranch(client, purchaseCode, input.branchCode);
const { purchaseLinkedToWarehouseDemand } = await import('./processingDemandSheetService');
const warehouseDemand = await purchaseLinkedToWarehouseDemand(purchaseCode, client);
const poResult = await client.query(
`SELECT purchase_code, purchase_status, branch_code, sku_code, order_code, supplier_code,
source_id, purchase_qty, purchase_price, actual_qty, actual_price, remark, self_processed
FROM purchase_orders
WHERE purchase_code = $1
LIMIT 1`,
[purchaseCode]
);
const row = poResult.rows[0];
if (!row) {
throw Object.assign(new Error('采购单不存在或无权操作'), { status: 404, code: 'not_found' });
}
const status = Number(row.purchase_status) || 0;
if (![20, 30].includes(status)) {
throw Object.assign(new Error('仅待仓验或已完成的自采单可改实采信息'), {
status: 409,
code: 'invalid_status',
});
}
/**
* 方案 C:preserveActualQty=true(自采 UI 入口)时本接口不改实收数量,也不再回退
* 到计划量 —— 否则待验收的行会被预填,触发验收守卫,单据永久停在 20。
* 订单明细编辑等服务端调用方不传该标记,行为与改动前完全一致。
*
* 2026-10-10 起自采 UI 走 `preserveActualQtyWhenInbound`:未入库(< 30)允许写交数,
* 已入库(30)仍旧不写(D3:已入库实收只归管理员)。
*/
const preserveActualQty =
input.preserveActualQty === true ||
(input.preserveActualQtyWhenInbound === true &&
Number(row.purchase_status) >= 30);
const beforeQty =
row.actual_qty != null
? Number(row.actual_qty)
: preserveActualQty
? 0
: Number(row.purchase_qty) || 0;
const beforePrice =
row.actual_price != null ? Number(row.actual_price) : Number(row.purchase_price) || 0;
const unitRow = await client.query(
`SELECT COALESCE(
NULLIF(TRIM(oi.unit), ''),
NULLIF(TRIM(s.unit), ''),
'个'
) AS unit
FROM purchase_orders po
LEFT JOIN order_item_fulfillments f ON f.purchase_code = po.purchase_code
LEFT JOIN order_items oi ON oi.id = f.order_item_id
LEFT JOIN order_items oi2 ON oi2.id::text = po.source_id
LEFT JOIN skus s ON s.sku_code = po.sku_code
WHERE po.purchase_code = $1
ORDER BY oi.id NULLS LAST
LIMIT 1`,
[purchaseCode]
);
const beforeUnit = String(unitRow.rows[0]?.unit || '个');
const beforeRemark = row.remark != null ? String(row.remark) : null;
/** preserveActualQty 时忽略传入的实收数量:本接口只改价格/单位/备注 */
const nextQty = preserveActualQty
? beforeQty
: input.actualQty === undefined || input.actualQty === null
? beforeQty
: Number(input.actualQty);
const nextPrice =
input.actualPrice === undefined || input.actualPrice === null
? beforePrice
: Number(input.actualPrice);
const nextUnit =
input.unit !== undefined && input.unit !== null && String(input.unit).trim()
? String(input.unit).trim().slice(0, 20)
: beforeUnit;
const nextRemark =
input.remark === undefined ? beforeRemark : input.remark == null ? null : String(input.remark).trim() || null;
if (!preserveActualQty && (!Number.isFinite(nextQty) || nextQty <= 0)) {
throw Object.assign(new Error('实采数量无效'), { status: 400, code: 'invalid_request' });
}
if (warehouseDemand) {
if (!Number.isFinite(nextPrice) || nextPrice < 0) {
throw Object.assign(new Error('实采单价无效'), { status: 400, code: 'invalid_request' });
}
if (nextPrice > 0) {
throw Object.assign(new Error('仓内加工成品成本须为 0,请另采原料入库'), {
status: 409,
code: 'warehouse_demand_readonly',
});
}
if (Math.abs(nextQty - beforeQty) > 1e-9 || nextUnit !== beforeUnit) {
throw Object.assign(new Error('仓内加工成品自采数量/单位只读,请另采原料入库'), {
status: 409,
code: 'warehouse_demand_readonly',
});
}
const priceAlreadyZero = Math.abs(beforePrice) < 1e-9;
const remarkSame = nextRemark === beforeRemark;
if (priceAlreadyZero && remarkSame) {
if (ownsClient) await client.query('COMMIT');
return {
success: true,
purchase_code: purchaseCode,
needs_customer_price: false,
needs_customer_price_item_ids: [],
reconciled: false,
cost_updated: false,
inventory_adjusted: false,
inventory_skipped: false,
inventory_skip_reason: null,
};
}
await client.query(
`UPDATE purchase_orders
SET actual_price = 0,
purchase_price = 0,
total_amount = 0,
remark = COALESCE($2::text, remark)
WHERE purchase_code = $1`,
[purchaseCode, nextRemark]
);
// 按明细 id 清零,完工分摊行(process_status=40)保留;不走 ByOrderSku、不写报价
await client.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
WHERE f.purchase_code = $1
OR EXISTS (
SELECT 1 FROM purchase_orders po
WHERE po.purchase_code = $1
AND NULLIF(TRIM(po.source_id), '') IS NOT NULL
AND po.source_id = di.order_item_id::text
)
)
AND oi.unit_cost IS DISTINCT FROM 0`,
[purchaseCode]
);
await client.query(
`UPDATE inspections
SET purchase_price = 0
WHERE (
processing_details->>'purchase_code' = $1
OR COALESCE(processing_details->'purchase_codes', '[]'::jsonb) ? $1
)
AND COALESCE(actual_qty, 0) = 0`,
[purchaseCode]
);
await writeAuditLog({
operatorId: input.operatorId,
operatorName: input.operatorName,
operatorRole: input.operatorRole,
operationType: 'purchase_amend_actual',
targetTable: 'purchase_orders',
targetId: purchaseCode,
oldValue: { actual_price: beforePrice, purchase_status: status },
newValue: { actual_price: 0, warehouse_demand_zero_cost: true },
branchCode: input.branchCode,
actionCategory: 'purchase',
});
if (ownsClient) await client.query('COMMIT');
return {
success: true,
purchase_code: purchaseCode,
needs_customer_price: false,
needs_customer_price_item_ids: [],
reconciled: false,
cost_updated: true,
inventory_adjusted: false,
inventory_skipped: false,
inventory_skip_reason: null,
};
}
// 仓内加工自采单:成本价必须为 0(既有反向规则);其余默认必须 >0,
// 「允许成本价为 0」开关开启后可按 0 保存(负数/NaN 仍拒)。
if (!row.self_processed && nextPrice === 0) {
const allowZero = await isZeroSupplyCostAllowed(
String(input.branchCode || row.branch_code || '').trim() || null
);
assertSupplyCostPrice(nextPrice, '实采单价', { allowZero });
} else if (!Number.isFinite(nextPrice) || nextPrice < 0 || (!row.self_processed && nextPrice <= 0)) {
throw Object.assign(new Error('实采单价必须大于 0'), { status: 400, code: 'invalid_request' });
}
const changed =
Math.abs(nextQty - beforeQty) > 1e-9 ||
Math.abs(nextPrice - beforePrice) > 1e-9 ||
nextUnit !== beforeUnit ||
nextRemark !== beforeRemark;
if (!changed) {
if (ownsClient) await client.query('COMMIT');
return {
success: true,
purchase_code: purchaseCode,
needs_customer_price: false,
needs_customer_price_item_ids: [],
reconciled: false,
cost_updated: false,
inventory_adjusted: false,
inventory_skipped: false,
inventory_skip_reason: null,
};
}
await client.query(
`UPDATE purchase_orders
SET actual_qty = CASE WHEN $2::numeric > 0 THEN $2::numeric ELSE actual_qty END,
actual_price = $3,
purchase_price = CASE
WHEN COALESCE(purchase_price, 0) = 0 THEN $3
ELSE purchase_price
END,
total_amount = CASE
WHEN $2::numeric > 0 THEN ROUND($2::numeric * $3::numeric, 2)
ELSE total_amount
END,
remark = COALESCE($4::text, remark)
WHERE purchase_code = $1`,
[purchaseCode, nextQty, nextPrice, nextRemark]
);
// 实采价改成 0:把「下单采购价」与金额一并清零,避免读取点
// `COALESCE(NULLIF(actual_price,0), purchase_price)` 把 0 回退成下单价。
if (Number(nextPrice) === 0) {
await clearPlanPriceForZeroCost(client, purchaseCode);
}
let needsCustomerPrice = false;
const needsCustomerPriceItemIds: string[] = [];
// 方案 C:尚未验收(无实收)时不同步订单行**数量/履约**——实收由验收产生后再同步
if (beforeQty > 0 && row.order_code && row.sku_code && !input.skipOrderItemSync) {
const syncResult = await syncOrderItemsFromSupplyCompletion(client, {
orderCode: String(row.order_code),
skuCode: String(row.sku_code),
settlementQty: nextQty,
settlementUnit: nextUnit,
link: { type: 'purchase', purchaseCode },
supplierCode: row.supplier_code ? String(row.supplier_code) : null,
});
needsCustomerPrice = syncResult.needsCustomerPrice;
needsCustomerPriceItemIds.push(...syncResult.itemIds);
} else if (!input.skipOrderItemSync && nextUnit !== beforeUnit && row.source_id) {
await client.query(`UPDATE order_items SET unit = $2 WHERE id = $1::uuid`, [
String(row.source_id),
nextUnit,
]);
}
/**
* 实采价 → **订单行成本回写**(订单管理 / 采购成本账本 / 采购备货风险提示同一口径)。
*
* ⚠️ 2026-10-14 开发者批准「方案 A:改价本来就要回写给订单行」——本段**与「有无实收」解耦**。
* 改前它在 `beforeQty > 0` 的分支里;自采 UI 路由恒传 `preserveActualQty: true`(方案 C),
* 未验收(`actual_qty IS NULL`)时 `beforeQty` 退化成 0 ⇒ **改价不回写订单行**,
* 于是「采购备货风险提示」按 `GREATEST(自采价, 订单行成本)` 判定时长期卡在订单行旧值上
* (改了价、风险消不掉)。现改为:**价格确实变了就回写**;「有实收」(beforeQty>0)路径行为不变。
*
* ⚠️ 0 是合法成本价(「允许成本价为 0」开关开启时):0 也必须回写,否则
* 采购侧已 0、订单行还留着上一次的正数,两边长期不一致。
*/
if (
row.order_code &&
row.sku_code &&
!input.skipOrderItemSync &&
!input.preserveOrderEnteredCost &&
(beforeQty > 0 || Math.abs(nextPrice - beforePrice) > 1e-9)
) {
const allowZeroWriteback =
nextPrice > 0 ||
(nextPrice === 0 &&
(await isZeroSupplyCostAllowed(
String(input.branchCode || row.branch_code || '').trim() || null
)));
if (allowZeroWriteback) {
const { setOrderItemUnitCostByOrderSku } = await import('./orderItemUnitCostService');
await setOrderItemUnitCostByOrderSku(
client,
String(row.order_code),
String(row.sku_code),
nextPrice
);
}
}
// 同步自采验收价量单位(含误标 supplier 但挂了本 purchase_code 的单据)
// preserveActualQty=true(自采 UI / 订单明细成本回写)时不动 prepare_qty——方案 C
// 「本接口只改价格/单位/备注」;否则保持原行为(prepare_qty = nextQty)。
// 见 docs/design/20260929-amend-actual-preserve-prepare-qty.md
if (row.order_code && row.sku_code) {
await client.query(
`UPDATE inspections
SET prepare_qty = CASE WHEN $7::boolean THEN prepare_qty ELSE $2 END,
purchase_price = $3,
unit = COALESCE($4::varchar, unit),
actual_qty = CASE
WHEN COALESCE(actual_qty, 0) > 0 THEN $2
ELSE actual_qty
END
WHERE order_code = $1
AND sku_code IS NOT DISTINCT FROM $5
AND (
processing_details->>'purchase_code' = $6
OR COALESCE(processing_details->'purchase_codes', '[]'::jsonb) ? $6
OR (
COALESCE(NULLIF(TRIM(source_type), ''), 'purchase') = 'purchase'
AND COALESCE(TRIM(supplier_code), '') = ''
)
)`,
[row.order_code, nextQty, nextPrice, nextUnit, row.sku_code, purchaseCode, preserveActualQty]
);
}
let reconciled = false;
let costUpdated = false;
let inventoryAdjusted = false;
let inventoryBatchNo: string | null = null;
let inventorySkipped = false;
let inventorySkipReason: 'no_inventory_row' | 'merge_guest' | null = null;
if (row.sku_code && !input.preserveOrderEnteredCost) {
await syncSkuCostFromPreparation(String(row.sku_code), nextPrice, client, input.branchCode, {
syncQuoteSheet: true,
}).catch(() => undefined);
}
if (row.order_code && row.sku_code) {
const inbound = await client.query(
`SELECT inbound_batch_no
FROM inspections
WHERE order_code = $1 AND sku_code IS NOT DISTINCT FROM $2
AND COALESCE(actual_qty, 0) > 0
AND (
processing_details->>'purchase_code' = $3
OR COALESCE(processing_details->'purchase_codes', '[]'::jsonb) ? $3
OR (
COALESCE(NULLIF(TRIM(source_type), ''), 'purchase') = 'purchase'
AND COALESCE(TRIM(supplier_code), '') = ''
)
)
ORDER BY
CASE WHEN NULLIF(TRIM(inbound_batch_no), '') IS NOT NULL THEN 0 ELSE 1 END,
inspection_time DESC NULLS LAST,
created_at DESC
LIMIT 1`,
[row.order_code, row.sku_code, purchaseCode]
);
if (inbound.rowCount) {
await reconcileOrderPurchaseFromLatestInspections(client, String(row.order_code), {
branchCode: input.branchCode,
operatorId: input.operatorId,
});
reconciled = true;
costUpdated = true;
const batchNo = String(inbound.rows[0]?.inbound_batch_no || '').trim();
const qtyDelta = nextQty - beforeQty;
const priceChanged = Math.abs(nextPrice - beforePrice) > 1e-9;
if (batchNo && (Math.abs(qtyDelta) > 1e-9 || priceChanged)) {
// 合单从单:履约挂在别单采购上(含已完成),共享宿主批次,不对本单差额改库存
const guest = await client.query(
`SELECT 1
FROM order_items oi
JOIN order_item_fulfillments f ON f.order_item_id = oi.id
JOIN purchase_orders po ON po.purchase_code = f.purchase_code
WHERE oi.order_code = $1
AND oi.sku_code IS NOT DISTINCT FROM $2
AND f.purchase_code IS NOT NULL
AND NULLIF(TRIM(po.order_code), '') IS NOT NULL
AND po.order_code IS DISTINCT FROM oi.order_code
AND po.purchase_status <> 40
LIMIT 1`,
[row.order_code, row.sku_code]
);
if (guest.rowCount) {
inventoryBatchNo = batchNo;
inventorySkipped = true;
inventorySkipReason = 'merge_guest';
} else {
const invExists = await client.query(
`SELECT 1 FROM inventory
WHERE batch_no = $1 AND branch_code = $2
LIMIT 1`,
[batchNo, input.branchCode]
);
if (!invExists.rowCount) {
// 过手履约等:验收写了批次号但未建库存台账 → 跳过差额,避免 404 回滚实采
inventoryBatchNo = batchNo;
inventorySkipped = true;
inventorySkipReason = 'no_inventory_row';
} else {
const inv = await applyInboundBatchQtyDelta(client, {
batchNo,
branchCode: input.branchCode,
deltaQty: qtyDelta,
costPrice: priceChanged ? nextPrice : null,
orderCode: String(row.order_code),
operatorId: input.operatorId,
remark: `purchase_amend ${purchaseCode}`,
// 自采补录实收:允许在已装车未出库时抬高入库,避免「改不了→扣不了」死锁
allowIncreaseWhileLoadedPendingOutbound: true,
});
inventoryAdjusted = inv.adjusted;
inventoryBatchNo = inv.batch_no;
}
}
}
} else if (nextPrice > 0 && nextQty > 0) {
const amount = Math.round(nextQty * nextPrice * 100) / 100;
const existing = await client.query(
`SELECT id, cost_subtype FROM cost_details
WHERE order_code = $1 AND sku_code = $2 AND cost_type = 'purchase'
ORDER BY created_at DESC NULLS LAST
LIMIT 1`,
[row.order_code, row.sku_code]
);
const subtype = existing.rows[0] ? String(existing.rows[0].cost_subtype || '') : '';
if (existing.rows[0]?.id && subtype !== 'inspection_inbound') {
await client.query(
`UPDATE cost_details
SET amount = $2,
allocated_amount = COALESCE(allocated_amount, $2),
cost_subtype = COALESCE(NULLIF(TRIM(cost_subtype), ''), 'self_purchase'),
status = 20
WHERE id = $1`,
[existing.rows[0].id, amount]
);
costUpdated = true;
}
}
}
await writeAuditLog({
operatorId: input.operatorId,
operatorName: input.operatorName,
operatorRole: input.operatorRole,
operationType: 'purchase_amend_actual',
targetTable: 'purchase_orders',
targetId: purchaseCode,
oldValue: {
actual_qty: beforeQty > 0 ? beforeQty : null,
actual_price: beforePrice,
unit: beforeUnit,
remark: beforeRemark,
purchase_status: status,
},
newValue: {
actual_qty: nextQty > 0 ? nextQty : null,
actual_price: nextPrice,
unit: nextUnit,
remark: nextRemark,
purchase_status: status,
inventory_adjusted: inventoryAdjusted,
inventory_batch_no: inventoryBatchNo,
inventory_skipped: inventorySkipped,
inventory_skip_reason: inventorySkipReason,
},
branchCode: input.branchCode,
actionCategory: 'purchase',
});
if (nextQty > 0 && row.order_code && row.sku_code) {
await writeOrderItemReceivedQtyWithStockCover(orderReceivedQtyDb(ownsClient ? null : client), {
orderCode: String(row.order_code),
skuCode: String(row.sku_code),
qty: nextQty,
unit: nextUnit,
stage: 10,
}).catch((error) => console.error('[purchase-amend] 写订单行实收失败', error));
}
if (ownsClient) await client.query('COMMIT');
return {
success: true,
purchase_code: purchaseCode,
needs_customer_price: needsCustomerPrice,
needs_customer_price_item_ids: needsCustomerPriceItemIds,
reconciled,
cost_updated: costUpdated,
inventory_adjusted: inventoryAdjusted,
inventory_batch_no: inventoryBatchNo,
inventory_skipped: inventorySkipped,
inventory_skip_reason: inventorySkipReason,
};
} catch (error) {
if (ownsClient) await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
if (ownsClient) client.release();
}
}