来源:audit-20261014(4 路只读审核 + Lead 复验)D1/D3;开发者批准"可以直接修改"。 D1(P0,重复计账) · 现象:订单详情"实收"是派生值 = 入库实收 + 库存抵扣量;保存时前端提交的正是这个显示值 (OrderManagementPage.tsx:2524-2531),服务端原样写进**缺口槽** (purchase_orders.actual_qty / inspections.actual_qty)且不扣 stock_cover_qty ⇒ 下次渲染再加一遍抵扣。 · 真库演算(BR002 ORD_API_20261014_BR002_0001 苹果行:计划 40 / 抵扣 30 / 缺口 10): 改前:管理员改成 42 保存 ⇒ 槽写 42 ⇒ 再显示 72(重复 30); 改后:槽写 12 ⇒ 再显示 42 ✓。 · 改法:新增口径唯一入口 server/src/services/receivedQtySlot.ts 的 resolveGapSlotQty (缺口量 = max(0, 显示值 − 抵扣量)),三处槽写入点改用它: adminOrderReceivedQtyService(直送/采购/验收/新建验收)+ pendingBackfillQtyService (手工路径 + 确认入账自动路径 = min(拣货整行, 未覆盖))。 · 明确保留整行量语义(不得缺口化):fillPickingForOrder 的 qtyByItemId/qtyBySku、 免入库 updateSkipInboundLoadedQty(核货量)。抵扣覆盖整行时直接跳过写槽。 D3(P1,取不到验收实收) · 现象:map 构造用验收行 supplier_code(BR002 实测 15/17 条为空)、取用却在订单行 supplier_code(自采是 INTERNAL)⇒ 键 sku|_none ≠ sku|INTERNAL ⇒ 取不到验收实收, 实收被"采购实收"档兜底(本单两档同值,暂未显错)。 · 改法:新增纯函数 normalizeReceivedQtySupplierKey(空/INTERNAL/UNASSIGNED ⇒ _self), 构造与取用两侧统一走它。 测试:server/tests/receivedQtySlotCaliber.test.ts(9 项)、 src/pages/orders/orderManagement/orderManagementHelpers.receivedKey.test.ts(4 项)。 回归:相关 server 测试 121 passed(3 项失败均在基线失败集内且不引用本次改动文件); 前后端 tsc 0 错误。设计:docs/design/20261014-审核整改(实收写回·验收取键·第7面成本·应收应付与看板).md §1-2。
377 lines
13 KiB
TypeScript
377 lines
13 KiB
TypeScript
import { pool } from '../db';
|
||
import type { TenantContext } from './tenantScope';
|
||
import { writeAuditLog } from './auditService';
|
||
import { ensureSupplierStatementAfterInbound } from './financeReconciliationService';
|
||
import { resyncPostedPurchaseCostAmounts } from './orderCostPostingService';
|
||
import { freezeOrderSettlementQtyOnComplete } from './orderItemSupplyUnitSync';
|
||
import { loadDirectDeliverySkuSetForOrder } from './skuDirectDelivery';
|
||
import { isSupplierSkipInbound } from './supplierSkipInbound';
|
||
import { adjustInboundInspectionQty } from './inspectionInboundQtyAdjust';
|
||
import { resolveGapSlotQty } from './receivedQtySlot';
|
||
import {
|
||
closeOrCreateInspectionForSku,
|
||
fillPickingForOrder,
|
||
type BackfillReceivedLine,
|
||
} from './pendingBackfillQtyService';
|
||
|
||
function trimText(v: unknown): string {
|
||
return String(v || '').trim();
|
||
}
|
||
|
||
function businessError(message: string, status = 400, code = 'invalid_request'): Error {
|
||
return Object.assign(new Error(message), { status, code });
|
||
}
|
||
|
||
function isAdminCtx(ctx?: TenantContext | null): boolean {
|
||
if (!ctx) return false;
|
||
return ctx.isSuperAdmin || ctx.roles.includes('admin');
|
||
}
|
||
|
||
async function assertAdminReceivedQtyOrder(orderCode: string): Promise<{
|
||
orderStatus: number;
|
||
branchCode: string | null;
|
||
supplierCodeBySku: Map<string, string>;
|
||
itemIdBySku: Map<string, string>;
|
||
/** 库存抵扣量(缺口槽换算用,2026-10-14 审核整改 D1) */
|
||
coverQtyByItemId: Map<string, number>;
|
||
coverQtyBySku: Map<string, number>;
|
||
}> {
|
||
const order = await pool.query(
|
||
`SELECT order_status, branch_code
|
||
FROM orders
|
||
WHERE order_code = $1 AND deleted_at IS NULL
|
||
LIMIT 1`,
|
||
[orderCode]
|
||
);
|
||
if (!order.rowCount) throw businessError('订单不存在', 404, 'not_found');
|
||
const orderStatus = Number(order.rows[0].order_status) || 0;
|
||
if (orderStatus < 40) {
|
||
throw businessError('待验收之前不可改实收', 409, 'order_status_too_early');
|
||
}
|
||
const items = await pool.query(
|
||
`SELECT id, sku_code, supplier_code, COALESCE(stock_cover_qty, 0)::float AS stock_cover_qty
|
||
FROM order_items
|
||
WHERE order_code = $1 AND COALESCE(is_returned, false) = false`,
|
||
[orderCode]
|
||
);
|
||
const supplierCodeBySku = new Map<string, string>();
|
||
const itemIdBySku = new Map<string, string>();
|
||
const coverQtyByItemId = new Map<string, number>();
|
||
const coverQtyBySku = new Map<string, number>();
|
||
for (const row of items.rows) {
|
||
const sku = trimText(row.sku_code);
|
||
const cover = Math.max(0, Number(row.stock_cover_qty) || 0);
|
||
coverQtyByItemId.set(String(row.id), cover);
|
||
if (!sku) continue;
|
||
supplierCodeBySku.set(sku, trimText(row.supplier_code));
|
||
if (!itemIdBySku.has(sku)) itemIdBySku.set(sku, String(row.id));
|
||
// 同 SKU 多行时取最大(与"槽只装缺口量"的保守口径一致:宁可少写,不多写)
|
||
coverQtyBySku.set(sku, Math.max(coverQtyBySku.get(sku) || 0, cover));
|
||
}
|
||
return {
|
||
orderStatus,
|
||
branchCode: order.rows[0].branch_code ? String(order.rows[0].branch_code) : null,
|
||
supplierCodeBySku,
|
||
itemIdBySku,
|
||
coverQtyByItemId,
|
||
coverQtyBySku,
|
||
};
|
||
}
|
||
|
||
async function hasUnresolvedFailedInspection(orderCode: string, skuCode: string): Promise<boolean> {
|
||
const result = await pool.query(
|
||
`SELECT 1
|
||
FROM inspections i
|
||
WHERE i.order_code = $1
|
||
AND i.sku_code IS NOT DISTINCT FROM $2
|
||
AND COALESCE(i.quality_rating, '') IN ('D', '不合格')
|
||
AND (
|
||
NULLIF(TRIM(i.inbound_batch_no), '') IS NULL
|
||
OR COALESCE(i.actual_qty, 0) <= 0
|
||
)
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM inspections p
|
||
WHERE p.order_code = i.order_code
|
||
AND p.sku_code IS NOT DISTINCT FROM i.sku_code
|
||
AND COALESCE(p.actual_qty, 0) > 0
|
||
AND NULLIF(TRIM(p.inbound_batch_no), '') IS NOT NULL
|
||
AND p.inspection_time IS NOT NULL
|
||
AND (i.inspection_time IS NULL OR p.inspection_time >= i.inspection_time)
|
||
)
|
||
LIMIT 1`,
|
||
[orderCode, skuCode]
|
||
);
|
||
return Boolean(result.rowCount);
|
||
}
|
||
|
||
async function updatePurchaseActualQty(orderCode: string, skuCode: string, qty: number): Promise<string | null> {
|
||
const found = await pool.query(
|
||
`SELECT purchase_code, actual_qty, actual_price, purchase_price
|
||
FROM purchase_orders
|
||
WHERE order_code = $1
|
||
AND sku_code IS NOT DISTINCT FROM $2
|
||
AND COALESCE(purchase_status, 10) >= 20
|
||
AND COALESCE(purchase_status, 10) NOT IN (32, 40)
|
||
ORDER BY created_at DESC
|
||
LIMIT 1`,
|
||
[orderCode, skuCode]
|
||
);
|
||
const row = found.rows[0];
|
||
if (!row) return null;
|
||
const unit = Number(row.actual_price) > 0 ? Number(row.actual_price) : Number(row.purchase_price) || 0;
|
||
const amount = Math.round(qty * unit * 100) / 100;
|
||
await pool.query(
|
||
`UPDATE purchase_orders
|
||
SET actual_qty = $2,
|
||
total_amount = CASE WHEN $3::numeric > 0 THEN $3 ELSE total_amount END
|
||
WHERE purchase_code = $1`,
|
||
[row.purchase_code, qty, amount]
|
||
);
|
||
return String(row.purchase_code);
|
||
}
|
||
|
||
async function supplierStatementConfirmed(supplierCode: string, orderCode: string): Promise<boolean> {
|
||
const code = trimText(supplierCode);
|
||
if (!code) return false;
|
||
const result = await pool.query(
|
||
`SELECT 1
|
||
FROM supplier_statements ss
|
||
INNER JOIN statement_lines sl
|
||
ON sl.statement_no = ss.statement_no AND sl.statement_type = 'supplier'
|
||
WHERE ss.supplier_code = $1
|
||
AND sl.order_code = $2
|
||
AND COALESCE(ss.statement_status, 0) >= 20
|
||
LIMIT 1`,
|
||
[code, orderCode]
|
||
);
|
||
return Boolean(result.rowCount);
|
||
}
|
||
|
||
async function updateSkipInboundLoadedQty(input: {
|
||
orderCode: string;
|
||
skuCode: string;
|
||
orderItemId: string | null;
|
||
qty: number;
|
||
}): Promise<boolean> {
|
||
const result = await pool.query(
|
||
`UPDATE picking_items pi
|
||
SET loaded_qty = $3::numeric
|
||
FROM picking_tasks pt
|
||
WHERE pt.pick_code = pi.pick_code
|
||
AND pi.order_code = $1
|
||
AND (
|
||
($4::text IS NOT NULL AND pi.order_item_id::text = $4)
|
||
OR pi.sku_code IS NOT DISTINCT FROM $2
|
||
)`,
|
||
[input.orderCode, input.skuCode, input.qty, input.orderItemId]
|
||
);
|
||
return (result.rowCount || 0) > 0;
|
||
}
|
||
|
||
async function auditLine(input: {
|
||
ctx?: TenantContext | null;
|
||
orderCode: string;
|
||
skuCode: string;
|
||
path: string;
|
||
oldQty?: number | null;
|
||
newQty: number;
|
||
targetTable: string;
|
||
targetId: string;
|
||
branchCode: string | null;
|
||
}): Promise<void> {
|
||
await writeAuditLog({
|
||
operatorId: input.ctx?.userId || null,
|
||
operatorRole: input.ctx?.roles?.join(',') || null,
|
||
operationType: 'order_received_qty_adjust',
|
||
targetTable: input.targetTable,
|
||
targetId: input.targetId,
|
||
oldValue: { order_code: input.orderCode, sku_code: input.skuCode, path: input.path, qty: input.oldQty ?? null },
|
||
newValue: { order_code: input.orderCode, sku_code: input.skuCode, path: input.path, qty: input.newQty },
|
||
branchCode: input.branchCode,
|
||
actionCategory: 'admin_correct',
|
||
});
|
||
}
|
||
|
||
export async function saveAdminOrderReceivedQty(input: {
|
||
orderCode: string;
|
||
items: BackfillReceivedLine[];
|
||
ctx?: TenantContext | null;
|
||
}): Promise<{
|
||
orderCode: string;
|
||
closedInspections: number;
|
||
warnings: string[];
|
||
}> {
|
||
const orderCode = trimText(input.orderCode);
|
||
if (!orderCode) throw businessError('缺少订单号');
|
||
if (!isAdminCtx(input.ctx)) {
|
||
throw businessError('仅管理员可改订单实收', 403, 'admin_required');
|
||
}
|
||
const meta = await assertAdminReceivedQtyOrder(orderCode);
|
||
|
||
const qtyByItemId = new Map<string, number>();
|
||
const qtyBySku = new Map<string, number>();
|
||
for (const line of input.items || []) {
|
||
const qty = Number(line.actual_qty);
|
||
if (!Number.isFinite(qty) || qty <= 0) continue;
|
||
const itemId = trimText(line.order_item_id);
|
||
const sku = trimText(line.sku_code);
|
||
if (itemId) qtyByItemId.set(itemId, qty);
|
||
if (sku) qtyBySku.set(sku, qty);
|
||
}
|
||
if (!qtyBySku.size && qtyByItemId.size) {
|
||
const ids = [...qtyByItemId.keys()];
|
||
const mapped = await pool.query(
|
||
`SELECT id, sku_code FROM order_items WHERE order_code = $1 AND id::text = ANY($2::text[])`,
|
||
[orderCode, ids]
|
||
);
|
||
for (const row of mapped.rows) {
|
||
const sku = trimText(row.sku_code);
|
||
const qty = qtyByItemId.get(String(row.id));
|
||
if (sku && qty) qtyBySku.set(sku, qty);
|
||
}
|
||
}
|
||
if (!qtyBySku.size) throw businessError('请至少填写一条大于 0 的实收数量');
|
||
|
||
const directSet = await loadDirectDeliverySkuSetForOrder(orderCode, [...qtyBySku.keys()]);
|
||
const warnings: string[] = [];
|
||
let closedInspections = 0;
|
||
|
||
for (const [skuCode, actualQty] of qtyBySku) {
|
||
if (await hasUnresolvedFailedInspection(orderCode, skuCode)) {
|
||
warnings.push(`${skuCode} 仍有未化解不合格,未改实收`);
|
||
continue;
|
||
}
|
||
|
||
const matchedItemId = meta.itemIdBySku.get(skuCode) || null;
|
||
|
||
/**
|
||
* **缺口槽换算**(2026-10-14 审核整改 D1):`actualQty` 是**显示实收**(= 入库实收 + 库存抵扣),
|
||
* 而下面写的是**缺口槽**(`purchase_orders.actual_qty` / `inspections.actual_qty`)。
|
||
* 不减掉抵扣 ⇒ 下次渲染会再加一遍(真库演算:42 → 72)。
|
||
* 唯一例外:`skip_inbound`(免入库)分支写的是**核货量 = 整行量**,用原值。
|
||
*/
|
||
const coverQty =
|
||
(matchedItemId ? meta.coverQtyByItemId.get(matchedItemId) : undefined) ??
|
||
meta.coverQtyBySku.get(skuCode) ??
|
||
0;
|
||
const gapQty = resolveGapSlotQty({ displayedQty: actualQty, stockCoverQty: coverQty });
|
||
|
||
if (directSet.has(skuCode)) {
|
||
if (gapQty <= 0) continue;
|
||
const po = await updatePurchaseActualQty(orderCode, skuCode, gapQty);
|
||
if (!po) {
|
||
warnings.push(`${skuCode} 直送无已完成自采,未改实收`);
|
||
continue;
|
||
}
|
||
await auditLine({
|
||
ctx: input.ctx,
|
||
orderCode,
|
||
skuCode,
|
||
path: 'direct_delivery_purchase',
|
||
newQty: gapQty,
|
||
targetTable: 'purchase_orders',
|
||
targetId: po,
|
||
branchCode: meta.branchCode,
|
||
});
|
||
continue;
|
||
}
|
||
|
||
const supplierCode = meta.supplierCodeBySku.get(skuCode) || '';
|
||
const skipInbound = supplierCode ? await isSupplierSkipInbound(supplierCode) : false;
|
||
if (skipInbound) {
|
||
const updated = await updateSkipInboundLoadedQty({
|
||
orderCode,
|
||
skuCode,
|
||
orderItemId: matchedItemId,
|
||
qty: actualQty,
|
||
});
|
||
if (!updated) {
|
||
warnings.push(`${skuCode} 不入仓尚无核货行,未改实收`);
|
||
continue;
|
||
}
|
||
await auditLine({
|
||
ctx: input.ctx,
|
||
orderCode,
|
||
skuCode,
|
||
path: 'skip_inbound_loaded',
|
||
newQty: actualQty,
|
||
targetTable: 'picking_items',
|
||
targetId: skuCode,
|
||
branchCode: meta.branchCode,
|
||
}); continue;
|
||
}
|
||
|
||
// 缺口已在上文按(本行抵扣量)换算为 gapQty;抵扣覆盖整行时无需写槽
|
||
if (gapQty <= 0) continue;
|
||
|
||
await updatePurchaseActualQty(orderCode, skuCode, gapQty);
|
||
|
||
const inbound = await pool.query(
|
||
`SELECT id FROM inspections
|
||
WHERE order_code = $1
|
||
AND sku_code IS NOT DISTINCT FROM $2
|
||
AND actual_qty IS NOT NULL
|
||
AND inbound_batch_no IS NOT NULL
|
||
LIMIT 1`,
|
||
[orderCode, skuCode]
|
||
);
|
||
if (inbound.rowCount) {
|
||
await adjustInboundInspectionQty({
|
||
orderCode,
|
||
skuCode,
|
||
qty: gapQty,
|
||
branchCode: meta.branchCode,
|
||
operatorId: input.ctx?.userId || null,
|
||
remark: `管理员改订单实收 ${orderCode} ${skuCode}`,
|
||
});
|
||
await ensureSupplierStatementAfterInbound({
|
||
orderCode,
|
||
skuCode,
|
||
supplierCode: supplierCode || null,
|
||
});
|
||
if (await supplierStatementConfirmed(supplierCode, orderCode)) {
|
||
warnings.push(`${skuCode} 实收已改,供应商结算单已确认未改,请财务手工调`);
|
||
}
|
||
await auditLine({
|
||
ctx: input.ctx,
|
||
orderCode,
|
||
skuCode,
|
||
path: 'inbound_inspection',
|
||
newQty: gapQty,
|
||
targetTable: 'inspections',
|
||
targetId: String(inbound.rows[0].id),
|
||
branchCode: meta.branchCode,
|
||
});
|
||
continue;
|
||
}
|
||
|
||
const closed = await closeOrCreateInspectionForSku({
|
||
orderCode,
|
||
skuCode,
|
||
actualQty: gapQty,
|
||
ctx: input.ctx,
|
||
});
|
||
if (closed) closedInspections += 1;
|
||
await auditLine({
|
||
ctx: input.ctx,
|
||
orderCode,
|
||
skuCode,
|
||
path: 'close_or_create_inspection',
|
||
newQty: gapQty,
|
||
targetTable: 'inspections',
|
||
targetId: skuCode,
|
||
branchCode: meta.branchCode,
|
||
});
|
||
}
|
||
|
||
await fillPickingForOrder({ orderCode, qtyByItemId, qtyBySku, ctx: input.ctx });
|
||
if (meta.orderStatus >= 90) {
|
||
// 已完成单:改实收会改动 picking_items.loaded_qty(结算量取值来源),
|
||
// 必须强制重算结算量,否则客户账单仍按旧量开票。
|
||
// 见 docs/design/20260915-remove-pending-backfill-state.md 第⑤步
|
||
await freezeOrderSettlementQtyOnComplete(pool, orderCode, { force: true });
|
||
await resyncPostedPurchaseCostAmounts(orderCode);
|
||
}
|
||
return { orderCode, closedInspections, warnings };
|
||
}
|