事故(真跑 P0):自采界面「新增自采」(= 独立入库)返回 200 与 batch_no,但 self_purchase_stock_inbounds 与 inspections 各 0 行 —— 货与待验单静默消失。 根因三层(缺一层都不会丢数): ① createSelfPurchaseStockInbound 引用**不存在的列** inspections.order_item_id(该表实测 30 列,无此列); ② 该语句在事务内报错被 catch 吞掉(只 console.warn,不抛、不回滚到 SAVEPOINT); ③ PG 语义:事务 aborted 后末尾 COMMIT 等价 ROLLBACK,而返回值已由 RETURNING 取到 ⇒ 照常返回成功。 开发者裁决(2026-10-15):「独立入库本来就不与订单关联」,它是给需要加工的产品采购原材料的入口 (createIndependentInboundInspection 恒写 order_code=NULL,输入接口也没有订单号字段) ⇒ 整块删掉订单实收回写,而不是去补一个"合法关联"。 改前 → 改后(同一脚本、同一 SKU SKU97144738818): · self_purchase_stock_inbounds 0 行 → 1 行;inspections 0 行 → 1 行; · stderr 报 column "order_item_id" does not exist → 无该告警; · 链路端到端:创建 1 行 + 真实验收(actual_qty=3 合格)后 inventory / inventory_logs / cost_details 各 1 行。 测试: · 删除 selfPurchaseActualQtyWriteback.test.ts —— 它把缺陷当契约钉住(断言了那条不存在的列 SQL 与吞异常日志文案); · 新增 selfPurchaseStockInboundTxnSafety.test.ts(9 例):不得引用该列 + BEGIN…COMMIT 之间不得出现 「只记日志」的 catch + 注入旧码必须 FAIL 的反向验证(已实测:注回旧码 5 例转红)。 验证:server tsc 0 error;vitest 32 failed / 2993 passed —— 失败数与本轮基线 32 例相同、失败文件集是基线子集(无新增); 设计门禁 8 通过 / 1 红(check-ai-cost,已知不许调绿) / 1 未执行(verify-facts,本地库连接探测),与改动前同基线。 设计:docs/design/20261015-独立入库不与订单关联(删掉订单实收回写与吞异常).md 同族风险:另有 6 处「事务内吞异常」站点(下单 / 明细保存等,属 finance/order 冻结面)已在设计文 §8 逐条列出, 本次**只报告未修**,等开发者裁决。
1337 lines
47 KiB
TypeScript
1337 lines
47 KiB
TypeScript
/**
|
||
* 独立自采商品入库:默认只建待验单(走验收流程,称重后以实称入库);
|
||
* 分公司关闭「独立入库验收」后提交即 inboundFromWeigh 直收并回填 inventory_id。
|
||
* 见 docs/design/20260823-independent-self-purchase-with-stock-inbound.md
|
||
* docs/design/20260827-independent-inbound-flow-switch.md
|
||
*/
|
||
import type { PoolClient } from 'pg';
|
||
import { isZeroSupplyCostAllowed } from './zeroSupplyCostConfigService';
|
||
import { pool } from '../db';
|
||
import { createIndependentInboundInspection } from './independentInboundService';
|
||
import { createCatalogSkuForInbound } from './skuProvisioningService';
|
||
import { inboundFromWeigh } from './stockInboundService';
|
||
import { getIndependentInboundFlowConfig } from './independentInboundFlowConfigService';
|
||
import {
|
||
reduceInventoryHoldingForReference,
|
||
upsertInventoryHoldingCost,
|
||
} from './inventorySurplusCostService';
|
||
import { writeAuditLog } from './auditService';
|
||
import { healNeedsNewInventoryRow } from './independentInboundHeal';
|
||
import { insertAfterSaleForSpiVoid } from './afterSaleLifecycleService';
|
||
|
||
function round2(n: number): number {
|
||
return Math.round(n * 100) / 100;
|
||
}
|
||
|
||
const QTY_EPS = 1e-9;
|
||
const OUTBOUND_LOG_TYPES = ['processing_out', 'picking_out', 'delivery_loading_out'] as const;
|
||
|
||
/**
|
||
* 已入库独立入库仅当整批仍在仓且无出库/领料流水才可作废。
|
||
* 批次不存在、可用≈0、可用≠数量、或有出库流水 → 不可删(盘点补量也不行)。
|
||
*/
|
||
export function canVoidIndependentInboundWhenInventoryHidden(
|
||
batchExists: boolean,
|
||
quantity: number,
|
||
availableQty: number,
|
||
hasOutboundLog = false
|
||
): boolean {
|
||
if (hasOutboundLog) return false;
|
||
if (!batchExists) return false;
|
||
const available = Number(availableQty) || 0;
|
||
const qty = Number(quantity) || 0;
|
||
if (available <= QTY_EPS || qty <= QTY_EPS) return false;
|
||
return Math.abs(available - qty) <= QTY_EPS;
|
||
}
|
||
|
||
/** 待验独立入库点退回:清 SPI.inspection_id 后删未提交待验单,不作废。 */
|
||
export async function bounceIndependentInboundPendingInspection(
|
||
client: Pick<PoolClient, 'query'>,
|
||
inspectionId: string
|
||
): Promise<void> {
|
||
const id = String(inspectionId || '').trim();
|
||
if (!id) {
|
||
throw Object.assign(new Error('验收单不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
|
||
const spiResult = await client.query(
|
||
`SELECT id::text AS id, inventory_id::text AS inventory_id
|
||
FROM self_purchase_stock_inbounds
|
||
WHERE inspection_id = $1::uuid AND voided_at IS NULL
|
||
FOR UPDATE`,
|
||
[id]
|
||
);
|
||
const spi = spiResult.rows[0];
|
||
if (spi?.inventory_id) {
|
||
throw Object.assign(new Error('该独立入库已确认入库,不能退回'), {
|
||
status: 409,
|
||
code: 'already_inspected',
|
||
});
|
||
}
|
||
if (spi) {
|
||
await client.query(
|
||
`UPDATE self_purchase_stock_inbounds
|
||
SET inspection_id = NULL
|
||
WHERE id = $1::uuid`,
|
||
[spi.id]
|
||
);
|
||
}
|
||
const deleted = await client.query(
|
||
`DELETE FROM inspections
|
||
WHERE id = $1::uuid AND inspection_time IS NULL`,
|
||
[id]
|
||
);
|
||
if (!deleted.rowCount) {
|
||
throw Object.assign(new Error('该验收单已提交,不能退回'), {
|
||
status: 409,
|
||
code: 'already_inspected',
|
||
});
|
||
}
|
||
}
|
||
|
||
function roundQty(n: number): number {
|
||
return Math.round(n * 1000) / 1000;
|
||
}
|
||
|
||
type InboundAuditChange = { field: string; label: string; before: unknown; after: unknown };
|
||
|
||
function buildStockInboundAdjustChanges(
|
||
spi: { qty?: unknown; unit_cost?: unknown; remark?: unknown },
|
||
next: { qty: number; unitCost: number; remark: string }
|
||
): InboundAuditChange[] {
|
||
const changes: InboundAuditChange[] = [];
|
||
if (Math.abs(roundQty(Number(spi.qty)) - next.qty) > QTY_EPS) {
|
||
changes.push({ field: 'qty', label: '数量', before: Number(spi.qty), after: next.qty });
|
||
}
|
||
if (round2(Number(spi.unit_cost)) !== next.unitCost) {
|
||
changes.push({
|
||
field: 'unit_cost',
|
||
label: '单价',
|
||
before: round2(Number(spi.unit_cost)),
|
||
after: next.unitCost,
|
||
});
|
||
}
|
||
const oldRemark = String(spi.remark || '').trim();
|
||
if (oldRemark !== next.remark) {
|
||
changes.push({ field: 'remark', label: '备注', before: oldRemark || null, after: next.remark });
|
||
}
|
||
return changes;
|
||
}
|
||
|
||
function currentCycleCode(): string {
|
||
const d = new Date();
|
||
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||
}
|
||
|
||
export interface CreateSelfPurchaseStockInboundInput {
|
||
skuCode?: string;
|
||
skuName?: string;
|
||
categoryCode?: string;
|
||
unit?: string;
|
||
qty: number;
|
||
unitCost: number;
|
||
branchCode: string;
|
||
remark?: string | null;
|
||
operatorId?: string | null;
|
||
/** 幂等键:客户端每次表单会话生成,重试/双击不重复入库 */
|
||
requestId?: string | null;
|
||
}
|
||
|
||
export interface CreateSelfPurchaseStockInboundResult {
|
||
id: string;
|
||
branch_code: string;
|
||
sku_code: string;
|
||
sku_name: string | null;
|
||
qty: number;
|
||
unit_cost: number;
|
||
total_amount: number;
|
||
batch_no: string;
|
||
inventory_id: string;
|
||
remark: string | null;
|
||
created_at: string;
|
||
/** 是否建了待验单;false 表示按开关直接入库 */
|
||
pending?: boolean;
|
||
}
|
||
|
||
export interface SelfPurchaseInboundHistoryRow {
|
||
purchase_code: string;
|
||
order_code: null;
|
||
sku_code: string;
|
||
purchase_qty: number;
|
||
actual_qty: number;
|
||
actual_price: number;
|
||
purchase_price: number;
|
||
total_amount: number;
|
||
purchase_status: number;
|
||
created_at: string;
|
||
remark: string | null;
|
||
purchaser_code: null;
|
||
purchaser_name: null;
|
||
item_name: string;
|
||
unit: string;
|
||
category_code: string | null;
|
||
category_name: string | null;
|
||
customer_name: string;
|
||
history_day: string;
|
||
source_type: 'self_purchase_inbound';
|
||
}
|
||
|
||
/**
|
||
* 修改独立自采入库:允许批次已消耗,但新数量不得低于已领用数量。
|
||
* 按新值同步库存批次数量/可用量/成本价与持有行,写调整流水与审计。
|
||
*/
|
||
export async function updateSelfPurchaseStockInbound(input: {
|
||
id: string;
|
||
branchCode: string;
|
||
qty: number;
|
||
unitCost: number;
|
||
remark?: string | null;
|
||
operatorId?: string | null;
|
||
}): Promise<{ id: string; qty: number; unit_cost: number; total_amount: number; consumed_qty?: number }> {
|
||
const id = String(input.id || '').trim();
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const qty = roundQty(Number(input.qty));
|
||
const unitCost = round2(Number(input.unitCost));
|
||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
|
||
throw Object.assign(new Error('入库记录不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
if (!branchCode) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
if (!Number.isFinite(qty) || qty <= 0) {
|
||
throw Object.assign(new Error('入库数量须大于 0'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
// 「允许成本价为 0」开关(分公司级,默认关闭):开启后 0 合法,负数/NaN 仍拒
|
||
const allowZeroInboundCost = await isZeroSupplyCostAllowed(branchCode);
|
||
if (allowZeroInboundCost) {
|
||
if (!Number.isFinite(unitCost) || unitCost < 0) {
|
||
throw Object.assign(new Error('成本价无效'), { status: 400, code: 'invalid_cost' });
|
||
}
|
||
} else if (!Number.isFinite(unitCost) || unitCost <= 0) {
|
||
throw Object.assign(new Error('成本价须大于 0'), { status: 400, code: 'invalid_cost' });
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
|
||
const spiResult = await client.query(
|
||
`SELECT id, branch_code, sku_code, sku_name, qty::float AS qty,
|
||
unit_cost::float AS unit_cost, remark, batch_no, inventory_id::text AS inventory_id,
|
||
inspection_id::text AS inspection_id, voided_at
|
||
FROM self_purchase_stock_inbounds
|
||
WHERE id = $1::uuid
|
||
LIMIT 1
|
||
FOR UPDATE`,
|
||
[id]
|
||
);
|
||
const spi = spiResult.rows[0];
|
||
if (!spi) {
|
||
throw Object.assign(new Error('入库记录不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
if (String(spi.branch_code || '') !== branchCode) {
|
||
throw Object.assign(new Error('无权修改其它分公司的入库记录'), {
|
||
status: 403,
|
||
code: 'branch_mismatch',
|
||
});
|
||
}
|
||
if (spi.voided_at) {
|
||
throw Object.assign(new Error('该记录已删除,不能再修改'), { status: 409, code: 'already_voided' });
|
||
}
|
||
|
||
// 待入库(未验收):直接改申报数量/成本价,同步待验单,无库存批次约束
|
||
if (!spi.inventory_id) {
|
||
if (spi.inspection_id) {
|
||
const updInspection = await client.query(
|
||
`UPDATE inspections
|
||
SET prepare_qty = $2, purchase_price = $3
|
||
WHERE id = $1::uuid AND inspection_time IS NULL`,
|
||
[spi.inspection_id, qty, unitCost]
|
||
);
|
||
if (!updInspection.rowCount) {
|
||
throw Object.assign(new Error('该记录已验收或待验单不存在,不能修改'), {
|
||
status: 409,
|
||
code: 'already_inspected',
|
||
});
|
||
}
|
||
}
|
||
const pendingTotal = round2(qty * unitCost);
|
||
const pendingRemark = String(input.remark || '').trim() || '独立自采入库';
|
||
await client.query(
|
||
`UPDATE self_purchase_stock_inbounds
|
||
SET qty = $2, unit_cost = $3, total_amount = $4, remark = $5
|
||
WHERE id = $1::uuid`,
|
||
[id, qty, unitCost, pendingTotal, pendingRemark]
|
||
);
|
||
await client.query('COMMIT');
|
||
const pendingChanges = buildStockInboundAdjustChanges(spi, {
|
||
qty,
|
||
unitCost,
|
||
remark: pendingRemark,
|
||
});
|
||
await writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'stock_inbound_adjust',
|
||
actionCategory: 'purchase',
|
||
targetTable: 'self_purchase_stock_inbounds',
|
||
targetId: id,
|
||
oldValue: {
|
||
sku_code: spi.sku_code,
|
||
sku_name: spi.sku_name,
|
||
qty: spi.qty,
|
||
unit_cost: spi.unit_cost,
|
||
remark: spi.remark || null,
|
||
},
|
||
newValue: {
|
||
sku_code: spi.sku_code,
|
||
sku_name: spi.sku_name,
|
||
pending: true,
|
||
qty,
|
||
unit_cost: unitCost,
|
||
remark: pendingRemark,
|
||
changes: pendingChanges,
|
||
},
|
||
branchCode,
|
||
});
|
||
return { id, qty, unit_cost: unitCost, total_amount: pendingTotal };
|
||
}
|
||
|
||
const invResult = await client.query(
|
||
`SELECT id, quantity::float AS quantity, available_qty::float AS available_qty
|
||
FROM inventory
|
||
WHERE id = $1::uuid
|
||
LIMIT 1
|
||
FOR UPDATE`,
|
||
[spi.inventory_id]
|
||
);
|
||
const inv = invResult.rows[0];
|
||
if (!inv) {
|
||
throw Object.assign(new Error('关联库存批次不存在,无法修改'), { status: 409, code: 'batch_missing' });
|
||
}
|
||
const oldQty = Number(inv.quantity) || 0;
|
||
const availableQty = Number(inv.available_qty) || 0;
|
||
// Consumed quantity is immutable, but the purchase record may still be
|
||
// corrected. Keep consumed = quantity - available and recalculate the
|
||
// remaining available quantity from the corrected inbound quantity.
|
||
const consumedQty = Math.max(0, oldQty - availableQty);
|
||
if (qty + 1e-9 < consumedQty) {
|
||
throw Object.assign(
|
||
new Error(`新数量不能小于已领用数量 ${consumedQty}`),
|
||
{ status: 409, code: 'qty_below_consumed' }
|
||
);
|
||
}
|
||
const nextAvailableQty = Math.max(0, qty - consumedQty);
|
||
|
||
const batchNo = String(spi.batch_no || '').trim();
|
||
const totalAmount = round2(qty * unitCost);
|
||
const remark = String(input.remark || '').trim() || '独立自采入库';
|
||
|
||
// Preserve consumed quantity while correcting the total batch quantity/cost.
|
||
await client.query(
|
||
`UPDATE inventory SET quantity = $2, available_qty = $3, cost_price = $4 WHERE id = $1::uuid`,
|
||
[inv.id, qty, nextAvailableQty, unitCost]
|
||
);
|
||
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, 'stock_in_adjust', $3, $4, $5, NULL, $6, $7)`,
|
||
[
|
||
batchNo,
|
||
String(spi.sku_code || ''),
|
||
qty - oldQty,
|
||
oldQty,
|
||
qty,
|
||
input.operatorId || null,
|
||
`独立自采入库修改 ${id}:${oldQty}×${spi.unit_cost} → ${qty}×${unitCost}`,
|
||
]
|
||
);
|
||
|
||
// 持有行按 reference 绝对值覆盖(金额差自动找平)
|
||
await upsertInventoryHoldingCost(client, {
|
||
cycleCode: currentCycleCode(),
|
||
branchCode,
|
||
skuCode: String(spi.sku_code || ''),
|
||
amount: totalAmount,
|
||
referenceId: batchNo,
|
||
operatorId: input.operatorId,
|
||
unitPrice: unitCost,
|
||
surplusQty: nextAvailableQty,
|
||
costSource: 'stock_inbound',
|
||
referenceType: 'stock_in',
|
||
costSubtype: 'stock_inbound',
|
||
remarkPrefix: 'stock_inbound',
|
||
});
|
||
|
||
await client.query(
|
||
`UPDATE self_purchase_stock_inbounds
|
||
SET qty = $2, unit_cost = $3, total_amount = $4, remark = $5
|
||
WHERE id = $1::uuid`,
|
||
[id, qty, unitCost, totalAmount, remark]
|
||
);
|
||
|
||
await client.query('COMMIT');
|
||
|
||
const stockedChanges = buildStockInboundAdjustChanges(spi, { qty, unitCost, remark });
|
||
await writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'stock_inbound_adjust',
|
||
actionCategory: 'purchase',
|
||
targetTable: 'self_purchase_stock_inbounds',
|
||
targetId: id,
|
||
oldValue: {
|
||
sku_code: spi.sku_code,
|
||
sku_name: spi.sku_name,
|
||
qty: spi.qty,
|
||
unit_cost: spi.unit_cost,
|
||
remark: spi.remark || null,
|
||
},
|
||
newValue: {
|
||
sku_code: spi.sku_code,
|
||
sku_name: spi.sku_name,
|
||
qty,
|
||
unit_cost: unitCost,
|
||
remark,
|
||
batch_no: batchNo,
|
||
changes: stockedChanges,
|
||
},
|
||
branchCode,
|
||
});
|
||
|
||
return { id, qty, unit_cost: unitCost, total_amount: totalAmount, consumed_qty: consumedQty };
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 作废独立自采入库:待验删除不作售后;已入库仅未领用可删并写售后核查单。
|
||
*/
|
||
export async function voidSelfPurchaseStockInbound(input: {
|
||
id: string;
|
||
branchCode: string;
|
||
operatorId?: string | null;
|
||
reason?: string | null;
|
||
}): Promise<{ id: string; voided: true }> {
|
||
const id = String(input.id || '').trim();
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
|
||
throw Object.assign(new Error('入库记录不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
if (!branchCode) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
|
||
const spiResult = await client.query(
|
||
`SELECT id, branch_code, sku_code, sku_name, qty::float AS qty,
|
||
unit_cost::float AS unit_cost, total_amount::float AS total_amount,
|
||
batch_no, inventory_id::text AS inventory_id,
|
||
inspection_id::text AS inspection_id, voided_at
|
||
FROM self_purchase_stock_inbounds
|
||
WHERE id = $1::uuid
|
||
LIMIT 1
|
||
FOR UPDATE`,
|
||
[id]
|
||
);
|
||
const spi = spiResult.rows[0];
|
||
if (!spi) {
|
||
throw Object.assign(new Error('入库记录不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
if (String(spi.branch_code || '') !== branchCode) {
|
||
throw Object.assign(new Error('无权作废其它分公司的入库记录'), {
|
||
status: 403,
|
||
code: 'branch_mismatch',
|
||
});
|
||
}
|
||
if (spi.voided_at) {
|
||
throw Object.assign(new Error('该记录已作废'), { status: 409, code: 'already_voided' });
|
||
}
|
||
|
||
// 待入库(未验收):撤销待验单 + 作废记录,无库存批次约束
|
||
if (!spi.inventory_id) {
|
||
if (spi.inspection_id) {
|
||
const delInspection = await client.query(
|
||
`DELETE FROM inspections
|
||
WHERE id = $1::uuid AND inspection_time IS NULL`,
|
||
[spi.inspection_id]
|
||
);
|
||
if (!delInspection.rowCount) {
|
||
throw Object.assign(new Error('该记录已验收或待验单不存在,不能作废'), {
|
||
status: 409,
|
||
code: 'already_inspected',
|
||
});
|
||
}
|
||
}
|
||
await client.query(
|
||
`UPDATE self_purchase_stock_inbounds
|
||
SET voided_at = NOW(), voided_by = $2::uuid, void_reason = $3
|
||
WHERE id = $1::uuid`,
|
||
[id, input.operatorId || null, String(input.reason || '').trim() || '待入库撤销']
|
||
);
|
||
await client.query('COMMIT');
|
||
await writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'stock_inbound_void',
|
||
targetTable: 'self_purchase_stock_inbounds',
|
||
targetId: id,
|
||
newValue: {
|
||
sku_code: spi.sku_code,
|
||
sku_name: spi.sku_name,
|
||
pending: true,
|
||
qty: spi.qty,
|
||
unit_cost: spi.unit_cost,
|
||
reason: String(input.reason || '').trim() || null,
|
||
},
|
||
branchCode,
|
||
});
|
||
return { id, voided: true };
|
||
}
|
||
|
||
const batchNo = String(spi.batch_no || '').trim();
|
||
const invResult = await client.query(
|
||
`SELECT id, quantity::float AS quantity, available_qty::float AS available_qty
|
||
FROM inventory
|
||
WHERE id = $1::uuid
|
||
LIMIT 1
|
||
FOR UPDATE`,
|
||
[spi.inventory_id]
|
||
);
|
||
const inv = invResult.rows[0];
|
||
const quantity = Number(inv?.quantity) || 0;
|
||
const availableQty = Number(inv?.available_qty) || 0;
|
||
const outbound = batchNo
|
||
? await client.query(
|
||
`SELECT 1
|
||
FROM inventory_logs
|
||
WHERE batch_no = $1
|
||
AND sku_code IS NOT DISTINCT FROM $2
|
||
AND operation_type = ANY($3::text[])
|
||
LIMIT 1`,
|
||
[batchNo, String(spi.sku_code || ''), [...OUTBOUND_LOG_TYPES]]
|
||
)
|
||
: { rowCount: 0 };
|
||
const hasOutboundLog = Boolean(outbound.rowCount);
|
||
if (!canVoidIndependentInboundWhenInventoryHidden(Boolean(inv), quantity, availableQty, hasOutboundLog)) {
|
||
throw Object.assign(
|
||
new Error('已领用或出库,不能删除(盘点补量也不行)'),
|
||
{ status: 409, code: 'batch_consumed' }
|
||
);
|
||
}
|
||
|
||
if (inv) {
|
||
await client.query(`UPDATE inventory SET available_qty = 0 WHERE id = $1::uuid`, [inv.id]);
|
||
await client.query(
|
||
`INSERT INTO inventory_logs (batch_no, sku_code, operation_type, quantity, before_qty, after_qty, related_order_code, operator_id, remark)
|
||
VALUES ($1, $2, 'stock_in_void', $3, $3, 0, NULL, $4, $5)`,
|
||
[
|
||
batchNo,
|
||
String(spi.sku_code || ''),
|
||
availableQty,
|
||
input.operatorId || null,
|
||
`独立自采入库作废 ${id}${input.reason ? `:${String(input.reason).trim()}` : ''}`,
|
||
]
|
||
);
|
||
}
|
||
|
||
const totalAmount = Number(spi.total_amount) || 0;
|
||
if (totalAmount > 0 && batchNo) {
|
||
await reduceInventoryHoldingForReference(client, {
|
||
referenceType: 'stock_in',
|
||
referenceId: batchNo,
|
||
reduceAmount: totalAmount,
|
||
});
|
||
}
|
||
|
||
await client.query(
|
||
`UPDATE self_purchase_stock_inbounds
|
||
SET voided_at = NOW(), voided_by = $2::uuid, void_reason = $3
|
||
WHERE id = $1::uuid`,
|
||
[id, input.operatorId || null, String(input.reason || '').trim() || null]
|
||
);
|
||
|
||
await insertAfterSaleForSpiVoid(client, {
|
||
spiId: id,
|
||
branchCode,
|
||
skuCode: spi.sku_code,
|
||
skuName: spi.sku_name,
|
||
qty: Number(spi.qty) || 0,
|
||
amount: totalAmount,
|
||
});
|
||
|
||
await client.query('COMMIT');
|
||
|
||
await writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'stock_inbound_void',
|
||
targetTable: 'self_purchase_stock_inbounds',
|
||
targetId: id,
|
||
newValue: {
|
||
sku_code: spi.sku_code,
|
||
sku_name: spi.sku_name,
|
||
qty: spi.qty,
|
||
unit_cost: spi.unit_cost,
|
||
total_amount: spi.total_amount,
|
||
batch_no: batchNo,
|
||
reason: String(input.reason || '').trim() || null,
|
||
},
|
||
branchCode,
|
||
});
|
||
|
||
return { id, voided: true };
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/** 自采待入库且无有效待验单:复用 SPI 批次号重建待验或关开关直收。 */
|
||
export async function resubmitSelfPurchaseStockInbound(input: {
|
||
id: string;
|
||
branchCode: string;
|
||
operatorId?: string | null;
|
||
}): Promise<CreateSelfPurchaseStockInboundResult> {
|
||
const id = String(input.id || '').trim();
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) {
|
||
throw Object.assign(new Error('入库记录不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
if (!branchCode) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const spiResult = await client.query(
|
||
`SELECT id, branch_code, sku_code, sku_name, qty::float AS qty,
|
||
unit_cost::float AS unit_cost, total_amount::float AS total_amount,
|
||
batch_no, inventory_id::text AS inventory_id,
|
||
inspection_id::text AS inspection_id, remark, voided_at, created_at::text AS created_at
|
||
FROM self_purchase_stock_inbounds
|
||
WHERE id = $1::uuid
|
||
LIMIT 1
|
||
FOR UPDATE`,
|
||
[id]
|
||
);
|
||
const spi = spiResult.rows[0];
|
||
if (!spi) {
|
||
throw Object.assign(new Error('入库记录不存在'), { status: 404, code: 'not_found' });
|
||
}
|
||
if (String(spi.branch_code || '') !== branchCode) {
|
||
throw Object.assign(new Error('无权操作其它分公司的入库记录'), {
|
||
status: 403,
|
||
code: 'branch_mismatch',
|
||
});
|
||
}
|
||
if (spi.voided_at) {
|
||
throw Object.assign(new Error('该记录已删除,不能再完成'), { status: 409, code: 'already_voided' });
|
||
}
|
||
if (spi.inventory_id) {
|
||
throw Object.assign(new Error('该记录已入库,无需再完成'), { status: 409, code: 'already_inbound' });
|
||
}
|
||
if (spi.inspection_id) {
|
||
const live = await client.query(
|
||
`SELECT id FROM inspections WHERE id = $1::uuid AND inspection_time IS NULL LIMIT 1`,
|
||
[spi.inspection_id]
|
||
);
|
||
if (live.rowCount) {
|
||
throw Object.assign(new Error('已在待验,无需再完成'), {
|
||
status: 409,
|
||
code: 'already_pending_inspection',
|
||
});
|
||
}
|
||
}
|
||
|
||
const qty = roundQty(Number(spi.qty) || 0);
|
||
const unitCost = round2(Number(spi.unit_cost) || 0);
|
||
// 「允许成本价为 0」开关(分公司级,默认关闭):数量始终须 >0;成本价开启后可为 0
|
||
const allowZeroInboundCost = await isZeroSupplyCostAllowed(branchCode);
|
||
if (!(qty > 0) || (allowZeroInboundCost ? !(unitCost >= 0) : !(unitCost > 0))) {
|
||
throw Object.assign(
|
||
new Error(allowZeroInboundCost ? '数量须大于 0,成本价不能为负数' : '数量和成本价须大于 0'),
|
||
{ status: 400, code: 'invalid_request' }
|
||
);
|
||
}
|
||
|
||
const skuRow = await client.query(`SELECT unit FROM skus WHERE sku_code = $1 LIMIT 1`, [
|
||
spi.sku_code,
|
||
]);
|
||
const unit = String(skuRow.rows[0]?.unit || '').trim() || undefined;
|
||
const remark = String(spi.remark || '').trim() || '独立自采入库';
|
||
const flow = await getIndependentInboundFlowConfig(branchCode);
|
||
const requireInspection = flow.enabled !== false;
|
||
const reuseBatchNo = String(spi.batch_no || '').trim() || undefined;
|
||
|
||
let batchNo = reuseBatchNo || '';
|
||
let inventoryId = '';
|
||
let inspectionId: string | null = null;
|
||
|
||
if (requireInspection) {
|
||
const pending = await createIndependentInboundInspection(client, {
|
||
skuCode: String(spi.sku_code || ''),
|
||
itemName: String(spi.sku_name || spi.sku_code || ''),
|
||
qty,
|
||
unitCost,
|
||
branchCode,
|
||
unit,
|
||
remark,
|
||
batchNo: reuseBatchNo,
|
||
extraDetails: { spi_id: id },
|
||
});
|
||
batchNo = pending.batchNo;
|
||
inspectionId = pending.inspectionId;
|
||
} else {
|
||
const stocked = await inboundFromWeigh(
|
||
{
|
||
skuCode: String(spi.sku_code || ''),
|
||
qty,
|
||
unitCost,
|
||
branchCode,
|
||
unit,
|
||
remark,
|
||
operatorId: input.operatorId,
|
||
batchNo: reuseBatchNo,
|
||
},
|
||
client
|
||
);
|
||
batchNo = stocked.batch_no;
|
||
inventoryId = stocked.inventory_id;
|
||
}
|
||
|
||
const totalAmount = round2(qty * unitCost);
|
||
await client.query(
|
||
`UPDATE self_purchase_stock_inbounds
|
||
SET batch_no = $2, inventory_id = $3::uuid, inspection_id = $4::uuid,
|
||
total_amount = $5
|
||
WHERE id = $1::uuid`,
|
||
[id, batchNo || null, inventoryId || null, inspectionId, totalAmount]
|
||
);
|
||
|
||
await client.query('COMMIT');
|
||
await writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'stock_inbound_resubmit',
|
||
targetTable: 'self_purchase_stock_inbounds',
|
||
targetId: id,
|
||
newValue: {
|
||
sku_code: spi.sku_code,
|
||
pending: requireInspection,
|
||
batch_no: batchNo,
|
||
inspection_id: inspectionId,
|
||
inventory_id: inventoryId || null,
|
||
},
|
||
branchCode,
|
||
});
|
||
|
||
return {
|
||
id,
|
||
branch_code: branchCode,
|
||
sku_code: String(spi.sku_code || ''),
|
||
sku_name: spi.sku_name ? String(spi.sku_name) : null,
|
||
qty,
|
||
unit_cost: unitCost,
|
||
total_amount: totalAmount,
|
||
batch_no: batchNo,
|
||
inventory_id: inventoryId,
|
||
remark: remark || null,
|
||
created_at: String(spi.created_at || ''),
|
||
pending: requireInspection,
|
||
};
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
export async function listSelfPurchaseStockInboundHistory(input: {
|
||
branchCode: string;
|
||
dateFrom: string;
|
||
dateTo: string;
|
||
}): Promise<SelfPurchaseInboundHistoryRow[]> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const dateFrom = String(input.dateFrom || '').trim();
|
||
const dateTo = String(input.dateTo || '').trim();
|
||
if (!branchCode || !dateFrom || !dateTo) return [];
|
||
|
||
try {
|
||
const result = await pool.query(
|
||
`SELECT
|
||
spi.id::text AS id,
|
||
spi.sku_code,
|
||
COALESCE(
|
||
NULLIF(TRIM(s.sku_name), ''),
|
||
NULLIF(TRIM(spi.sku_name), ''),
|
||
NULLIF(TRIM(spi.sku_code), ''),
|
||
'商品'
|
||
) AS item_name,
|
||
spi.qty,
|
||
spi.unit_cost,
|
||
spi.total_amount,
|
||
spi.remark,
|
||
spi.created_at,
|
||
spi.inventory_id::text AS inventory_id,
|
||
to_char((spi.created_at AT TIME ZONE 'Asia/Shanghai')::date, 'YYYY-MM-DD') AS history_day,
|
||
COALESCE(
|
||
CASE
|
||
WHEN TRIM(COALESCE(s.unit, '')) !~ '(元[[:space:]]*/|[¥¥])'
|
||
THEN NULLIF(TRIM(s.unit), '')
|
||
END,
|
||
'个'
|
||
) AS unit,
|
||
NULLIF(TRIM(s.category_code), '') AS category_code,
|
||
COALESCE(NULLIF(TRIM(cat.category_name), ''), NULLIF(TRIM(s.category_code), '')) AS category_name
|
||
FROM self_purchase_stock_inbounds spi
|
||
LEFT JOIN skus s ON s.sku_code = spi.sku_code
|
||
LEFT JOIN categories cat ON cat.category_code = s.category_code
|
||
WHERE spi.branch_code = $1
|
||
AND spi.voided_at IS NULL
|
||
AND (spi.created_at AT TIME ZONE 'Asia/Shanghai')::date BETWEEN $2::date AND $3::date
|
||
ORDER BY spi.created_at DESC`,
|
||
[branchCode, dateFrom, dateTo]
|
||
);
|
||
|
||
return result.rows.map((row: any) => {
|
||
const qty = Number(row.qty) || 0;
|
||
const unitCost = Number(row.unit_cost) || 0;
|
||
const total = Number(row.total_amount);
|
||
const inboundDone = Boolean(row.inventory_id);
|
||
return {
|
||
purchase_code: `SPI-${row.id}`,
|
||
order_code: null,
|
||
sku_code: String(row.sku_code || ''),
|
||
purchase_qty: qty,
|
||
actual_qty: inboundDone ? qty : 0,
|
||
actual_price: unitCost,
|
||
purchase_price: unitCost,
|
||
total_amount: Number.isFinite(total) && total > 0 ? total : round2(qty * unitCost),
|
||
purchase_status: inboundDone ? 30 : 10,
|
||
created_at: row.created_at,
|
||
remark: row.remark || null,
|
||
purchaser_code: null,
|
||
purchaser_name: null,
|
||
item_name: String(row.item_name || row.sku_code || '商品'),
|
||
unit: String(row.unit || '个'),
|
||
category_code: row.category_code || null,
|
||
category_name: row.category_name || null,
|
||
customer_name: '',
|
||
history_day: String(row.history_day || ''),
|
||
source_type: 'self_purchase_inbound' as const,
|
||
};
|
||
});
|
||
} catch (e: any) {
|
||
if (!/self_purchase_stock_inbounds/i.test(String(e?.message || ''))) throw e;
|
||
console.warn('[selfPurchaseStockInbound] history 表不可用:', e.message);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
async function loadSelfPurchaseInboundByRequestId(
|
||
db: Pick<PoolClient, 'query'>,
|
||
branchCode: string,
|
||
requestId: string
|
||
): Promise<CreateSelfPurchaseStockInboundResult | null> {
|
||
const result = await db.query(
|
||
`SELECT id::text AS id, sku_code, sku_name, qty::float AS qty,
|
||
unit_cost::float AS unit_cost, total_amount::float AS total_amount,
|
||
batch_no, inventory_id::text AS inventory_id, remark, created_at::text AS created_at
|
||
FROM self_purchase_stock_inbounds
|
||
WHERE branch_code = $1 AND request_id = $2
|
||
LIMIT 1`,
|
||
[branchCode, requestId]
|
||
);
|
||
const row = result.rows[0];
|
||
if (!row) return null;
|
||
return {
|
||
id: String(row.id),
|
||
branch_code: branchCode,
|
||
sku_code: String(row.sku_code || ''),
|
||
sku_name: row.sku_name ? String(row.sku_name) : null,
|
||
qty: Number(row.qty) || 0,
|
||
unit_cost: Number(row.unit_cost) || 0,
|
||
total_amount: Number(row.total_amount) || 0,
|
||
batch_no: String(row.batch_no || ''),
|
||
inventory_id: String(row.inventory_id || ''),
|
||
remark: row.remark ? String(row.remark) : null,
|
||
created_at: String(row.created_at || ''),
|
||
pending: !String(row.inventory_id || ''),
|
||
};
|
||
}
|
||
|
||
export async function createSelfPurchaseStockInbound(
|
||
input: CreateSelfPurchaseStockInboundInput,
|
||
existingClient?: PoolClient
|
||
): Promise<CreateSelfPurchaseStockInboundResult> {
|
||
let skuCode = String(input.skuCode || '').trim();
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const qty = roundQty(Number(input.qty));
|
||
const unitCost = round2(Number(input.unitCost));
|
||
const remark = String(input.remark || '').trim() || '独立自采入库';
|
||
const requestId = String(input.requestId || '').trim() || null;
|
||
|
||
if (!branchCode) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
if (!Number.isFinite(qty) || qty <= 0) {
|
||
throw Object.assign(new Error('入库数量须大于 0'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
// 「允许成本价为 0」开关(分公司级,默认关闭):开启后 0 合法,负数/NaN 仍拒
|
||
const allowZeroInboundCost = await isZeroSupplyCostAllowed(branchCode);
|
||
if (allowZeroInboundCost) {
|
||
if (!Number.isFinite(unitCost) || unitCost < 0) {
|
||
throw Object.assign(new Error('成本价无效'), { status: 400, code: 'invalid_cost' });
|
||
}
|
||
} else if (!Number.isFinite(unitCost) || unitCost <= 0) {
|
||
throw Object.assign(new Error('成本价须大于 0'), { status: 400, code: 'invalid_cost' });
|
||
}
|
||
|
||
const client = existingClient || (await pool.connect());
|
||
const owns = !existingClient;
|
||
|
||
try {
|
||
if (owns) await client.query('BEGIN');
|
||
|
||
// 幂等重放:同一表单会话的重试/双击直接返回首次结果
|
||
if (requestId) {
|
||
const replay = await loadSelfPurchaseInboundByRequestId(client, branchCode, requestId);
|
||
if (replay) {
|
||
if (owns) await client.query('COMMIT');
|
||
return replay;
|
||
}
|
||
}
|
||
|
||
let skuName = '';
|
||
let unit = '';
|
||
|
||
if (skuCode) {
|
||
const skuRow = await client.query(
|
||
`SELECT sku_name, unit FROM skus WHERE sku_code = $1 LIMIT 1`,
|
||
[skuCode]
|
||
);
|
||
if (skuRow.rowCount) {
|
||
skuName = String(skuRow.rows[0]?.sku_name || '');
|
||
unit = String(skuRow.rows[0]?.unit || '');
|
||
}
|
||
}
|
||
|
||
if (!skuName) {
|
||
const createName = String(input.skuName || '').trim();
|
||
if (!createName) {
|
||
throw Object.assign(new Error('请选择或填写商品名称'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
if (!String(input.categoryCode || '').trim()) {
|
||
throw Object.assign(new Error('请选择商品分类'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
const created = await createCatalogSkuForInbound(client, {
|
||
name: createName,
|
||
parentCode: String(input.categoryCode || '').trim(),
|
||
branchCode,
|
||
unit: input.unit,
|
||
});
|
||
skuCode = created.skuCode;
|
||
skuName = created.name;
|
||
unit = input.unit || '斤';
|
||
}
|
||
|
||
const flow = await getIndependentInboundFlowConfig(branchCode);
|
||
const requireInspection = flow.enabled !== false;
|
||
|
||
let batchNo = '';
|
||
let inventoryId = '';
|
||
let inspectionId: string | null = null;
|
||
|
||
if (requireInspection) {
|
||
// 只建待验单,不写库存:验收称重后由验收链路按实称数量入库
|
||
const pending = await createIndependentInboundInspection(client, {
|
||
skuCode,
|
||
itemName: skuName || skuCode,
|
||
qty,
|
||
unitCost,
|
||
branchCode,
|
||
unit: unit || undefined,
|
||
remark,
|
||
});
|
||
batchNo = pending.batchNo;
|
||
inspectionId = pending.inspectionId;
|
||
} else {
|
||
const stocked = await inboundFromWeigh(
|
||
{
|
||
skuCode,
|
||
qty,
|
||
unitCost,
|
||
branchCode,
|
||
unit: unit || input.unit || undefined,
|
||
remark,
|
||
operatorId: input.operatorId,
|
||
},
|
||
client
|
||
);
|
||
batchNo = stocked.batch_no;
|
||
inventoryId = stocked.inventory_id;
|
||
}
|
||
|
||
const totalAmount = round2(qty * unitCost);
|
||
const inserted = await client.query(
|
||
`INSERT INTO self_purchase_stock_inbounds
|
||
(branch_code, sku_code, sku_name, qty, unit_cost, total_amount, batch_no, inventory_id, inspection_id, remark, operator_id, request_id)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8::uuid, $9::uuid, $10, $11::uuid, $12)
|
||
RETURNING id::text AS id, created_at::text AS created_at`,
|
||
[
|
||
branchCode,
|
||
skuCode,
|
||
skuName,
|
||
qty,
|
||
unitCost,
|
||
totalAmount,
|
||
batchNo || null,
|
||
inventoryId || null,
|
||
inspectionId,
|
||
remark,
|
||
input.operatorId || null,
|
||
requestId,
|
||
]
|
||
);
|
||
|
||
/**
|
||
* 独立入库(自采界面「新增自采」)**不与订单关联**(开发者 2026-10-15 定稿):
|
||
* 它是给需要加工的产品采购原材料的入口,`createIndependentInboundInspection` 恒写
|
||
* `order_code = NULL`,`CreateSelfPurchaseStockInboundInput` 也没有订单号字段 ⇒
|
||
* 根本不存在"订单侧实收"可回写。
|
||
*
|
||
* ⚠️ 历史缺陷(2026-10-15 修,见 `docs/design/20261015-独立入库不与订单关联(删掉订单实收回写与吞异常).md`):
|
||
* 此处原有 §8.7 的"订单实收回写"块,引用 `inspections.order_item_id` —— **该列不存在**。
|
||
* 语句在事务内报错被 `catch` 吞掉 ⇒ 事务进入 aborted 态 ⇒ 末尾 `COMMIT` 等价 **ROLLBACK**
|
||
* ⇒ 待验单与 SPI 行全部丢失,而返回值已由 `RETURNING` 取到、照常返回成功(静默丢数)。
|
||
* 结论:整块删除;**事务内不得出现"只记日志不抛"的 catch**(契约测试钉住)。
|
||
*/
|
||
if (owns) await client.query('COMMIT');
|
||
|
||
const createdId = String(inserted.rows[0]?.id || '');
|
||
void writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'stock_inbound_create',
|
||
actionCategory: 'purchase',
|
||
targetTable: 'self_purchase_stock_inbounds',
|
||
targetId: createdId,
|
||
newValue: {
|
||
sku_code: skuCode,
|
||
sku_name: skuName || null,
|
||
qty,
|
||
unit_cost: unitCost,
|
||
total_amount: totalAmount,
|
||
pending: requireInspection,
|
||
remark: remark || null,
|
||
},
|
||
branchCode,
|
||
}).catch((error) => {
|
||
console.error('[stock_inbound_create] writeAuditLog failed:', error);
|
||
});
|
||
|
||
return {
|
||
id: createdId,
|
||
branch_code: branchCode,
|
||
sku_code: skuCode,
|
||
sku_name: skuName || null,
|
||
qty,
|
||
unit_cost: unitCost,
|
||
total_amount: totalAmount,
|
||
batch_no: batchNo,
|
||
inventory_id: inventoryId,
|
||
remark: remark || null,
|
||
created_at: String(inserted.rows[0]?.created_at || ''),
|
||
pending: requireInspection,
|
||
};
|
||
} catch (error) {
|
||
if (owns) await client.query('ROLLBACK').catch(() => undefined);
|
||
// 并发撞幂等键(两个请求同时入库同一 request_id):回滚后返回已存在的那单
|
||
if (requestId && String((error as { code?: string } | null)?.code || '') === '23505') {
|
||
const replay = await loadSelfPurchaseInboundByRequestId(client, branchCode, requestId);
|
||
if (replay) return replay;
|
||
}
|
||
throw error;
|
||
} finally {
|
||
if (owns) client.release();
|
||
}
|
||
}
|
||
|
||
function newHealBatchNo(): string {
|
||
return `IN${Date.now().toString().slice(-9)}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
||
}
|
||
|
||
/**
|
||
* 验收已合格但 SPI 未挂库存(鲜品过手曾跳过台账)。列表查询前幂等补写。
|
||
*/
|
||
export async function healOrphanIndependentInboundsAfterPass(
|
||
branchCode?: string | null
|
||
): Promise<number> {
|
||
const branch = String(branchCode || '').trim();
|
||
const params: unknown[] = [];
|
||
const spiBranchSql = branch ? (params.push(branch), 'AND spi.branch_code = $1') : '';
|
||
const inspBranchSql = branch ? 'AND i.branch_code = $1' : '';
|
||
let orphans: {
|
||
spi_id: string | null;
|
||
inspection_id: string | null;
|
||
sku_code: string;
|
||
branch_code: string;
|
||
actual_qty: number;
|
||
purchase_price: number;
|
||
inbound_batch_no: string | null;
|
||
inspector_id: string | null;
|
||
}[];
|
||
try {
|
||
const found = await pool.query(
|
||
`SELECT spi.id::text AS spi_id,
|
||
i.id::text AS inspection_id,
|
||
spi.sku_code,
|
||
spi.branch_code,
|
||
i.actual_qty::float AS actual_qty,
|
||
COALESCE(NULLIF(i.purchase_price, 0), spi.unit_cost)::float AS purchase_price,
|
||
NULLIF(TRIM(i.inbound_batch_no), '') AS inbound_batch_no,
|
||
i.inspector_id::text AS inspector_id
|
||
FROM self_purchase_stock_inbounds spi
|
||
JOIN inspections i ON i.id = spi.inspection_id
|
||
WHERE spi.inventory_id IS NULL
|
||
AND spi.voided_at IS NULL
|
||
AND i.inspection_time IS NOT NULL
|
||
AND COALESCE(i.actual_qty, 0) > 0
|
||
${spiBranchSql}
|
||
UNION ALL
|
||
SELECT NULL::text AS spi_id,
|
||
i.id::text AS inspection_id,
|
||
i.sku_code,
|
||
i.branch_code,
|
||
i.actual_qty::float AS actual_qty,
|
||
COALESCE(NULLIF(i.purchase_price, 0), 0)::float AS purchase_price,
|
||
NULLIF(TRIM(i.inbound_batch_no), '') AS inbound_batch_no,
|
||
i.inspector_id::text AS inspector_id
|
||
FROM inspections i
|
||
WHERE COALESCE(i.processing_details->>'independent_inbound', '') = 'true'
|
||
AND i.inspection_time IS NOT NULL
|
||
AND COALESCE(i.actual_qty, 0) > 0
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM self_purchase_stock_inbounds spi2
|
||
WHERE spi2.inspection_id = i.id AND spi2.voided_at IS NULL
|
||
)
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM inventory inv
|
||
WHERE inv.sku_code IS NOT DISTINCT FROM i.sku_code
|
||
AND NULLIF(TRIM(i.inbound_batch_no), '') IS NOT NULL
|
||
AND inv.batch_no = i.inbound_batch_no
|
||
)
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM inventory inv
|
||
JOIN inventory_logs il
|
||
ON il.batch_no = inv.batch_no
|
||
AND il.sku_code IS NOT DISTINCT FROM inv.sku_code
|
||
AND il.operation_type = 'inspection_in'
|
||
AND il.remark LIKE '独立入库补写%'
|
||
WHERE inv.sku_code IS NOT DISTINCT FROM i.sku_code
|
||
AND inv.branch_code IS NOT DISTINCT FROM i.branch_code
|
||
AND ABS(COALESCE(inv.quantity, 0) - COALESCE(i.actual_qty, 0)) <= 1e-6
|
||
)
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM inventory_logs l
|
||
WHERE l.sku_code IS NOT DISTINCT FROM i.sku_code
|
||
AND l.operation_type = 'inspection_in'
|
||
AND COALESCE(l.quantity, 0) > 0
|
||
AND (
|
||
l.remark LIKE '%' || i.id::text || '%'
|
||
OR (
|
||
NULLIF(TRIM(i.inbound_batch_no), '') IS NULL
|
||
AND l.remark LIKE '独立入库补写%'
|
||
AND COALESCE(l.quantity, 0) = COALESCE(i.actual_qty, 0)
|
||
AND l.created_at >= i.inspection_time
|
||
)
|
||
)
|
||
)
|
||
${inspBranchSql}
|
||
LIMIT 80`,
|
||
params
|
||
);
|
||
orphans = found.rows;
|
||
} catch (e: any) {
|
||
if (!/self_purchase_stock_inbounds/i.test(String(e?.message || ''))) {
|
||
console.warn('[selfPurchaseStockInbound] heal 查询失败:', e?.message);
|
||
}
|
||
return 0;
|
||
}
|
||
if (!orphans.length) return 0;
|
||
|
||
let healed = 0;
|
||
for (const row of orphans) {
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
if (row.inspection_id) {
|
||
await client.query('SELECT pg_advisory_xact_lock(810828, hashtext($1::text))', [
|
||
row.inspection_id,
|
||
]);
|
||
const lockedInsp = await client.query(
|
||
`SELECT NULLIF(TRIM(inbound_batch_no), '') AS inbound_batch_no
|
||
FROM inspections
|
||
WHERE id = $1::uuid
|
||
FOR UPDATE`,
|
||
[row.inspection_id]
|
||
);
|
||
if (!lockedInsp.rowCount) {
|
||
await client.query('ROLLBACK');
|
||
continue;
|
||
}
|
||
if (lockedInsp.rows[0]?.inbound_batch_no) {
|
||
row.inbound_batch_no = String(lockedInsp.rows[0].inbound_batch_no);
|
||
}
|
||
}
|
||
if (row.spi_id) {
|
||
const locked = await client.query(
|
||
`SELECT id FROM self_purchase_stock_inbounds
|
||
WHERE id = $1::uuid AND inventory_id IS NULL AND voided_at IS NULL
|
||
FOR UPDATE`,
|
||
[row.spi_id]
|
||
);
|
||
if (!locked.rowCount) {
|
||
await client.query('ROLLBACK');
|
||
continue;
|
||
}
|
||
} else if (row.inspection_id) {
|
||
const insp = await client.query(
|
||
`SELECT id, NULLIF(TRIM(inbound_batch_no), '') AS inbound_batch_no
|
||
FROM inspections WHERE id = $1::uuid FOR UPDATE`,
|
||
[row.inspection_id]
|
||
);
|
||
if (!insp.rowCount) {
|
||
await client.query('ROLLBACK');
|
||
continue;
|
||
}
|
||
const inspBatch = String(insp.rows[0]?.inbound_batch_no || '').trim();
|
||
if (inspBatch) {
|
||
const existingByBatch = await client.query(
|
||
`SELECT id::text AS id FROM inventory
|
||
WHERE batch_no = $1 AND sku_code IS NOT DISTINCT FROM $2
|
||
LIMIT 1`,
|
||
[inspBatch, row.sku_code]
|
||
);
|
||
if (existingByBatch.rowCount) {
|
||
await client.query('ROLLBACK');
|
||
continue;
|
||
}
|
||
}
|
||
}
|
||
const actualQty = roundQty(Number(row.actual_qty) || 0);
|
||
const purchasePrice = round2(Number(row.purchase_price) || 0);
|
||
if (actualQty <= 0) {
|
||
await client.query('ROLLBACK');
|
||
continue;
|
||
}
|
||
let batchNo = String(row.inbound_batch_no || '').trim();
|
||
let inventoryId: string | null = null;
|
||
let inboundLogForInspection = false;
|
||
if (row.inspection_id) {
|
||
const logged = await client.query(
|
||
`SELECT l.batch_no
|
||
FROM inventory_logs l
|
||
WHERE l.operation_type = 'inspection_in'
|
||
AND COALESCE(l.quantity, 0) > 0
|
||
AND l.remark LIKE '%' || $1::text || '%'
|
||
ORDER BY l.created_at DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[row.inspection_id]
|
||
);
|
||
if (logged.rowCount) {
|
||
inboundLogForInspection = true;
|
||
const loggedBatch = String(logged.rows[0]?.batch_no || '').trim();
|
||
if (loggedBatch) batchNo = loggedBatch;
|
||
}
|
||
}
|
||
if (batchNo) {
|
||
const existing = await client.query(
|
||
`SELECT id::text AS id FROM inventory
|
||
WHERE batch_no = $1 AND sku_code IS NOT DISTINCT FROM $2
|
||
ORDER BY created_at DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[batchNo, row.sku_code]
|
||
);
|
||
inventoryId = existing.rows[0]?.id ? String(existing.rows[0].id) : null;
|
||
}
|
||
let insertedNewInventory = false;
|
||
if (healNeedsNewInventoryRow({ existingInventoryId: inventoryId, inboundLogForInspection })) {
|
||
if (!batchNo) batchNo = newHealBatchNo();
|
||
const inv = 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)
|
||
RETURNING id::text AS id`,
|
||
[batchNo, row.sku_code, actualQty, purchasePrice || null, row.branch_code]
|
||
);
|
||
inventoryId = inv.rows[0]?.id ? String(inv.rows[0].id) : null;
|
||
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, 'inspection_in', $3, 0, $3, NULL, $4, $5)`,
|
||
[
|
||
batchNo,
|
||
row.sku_code,
|
||
actualQty,
|
||
row.inspector_id || null,
|
||
`独立入库补写 ${row.inspection_id || row.spi_id || ''}`,
|
||
]
|
||
);
|
||
insertedNewInventory = true;
|
||
}
|
||
if (!inventoryId) {
|
||
await client.query('ROLLBACK');
|
||
continue;
|
||
}
|
||
if (row.inspection_id && batchNo) {
|
||
await client.query(
|
||
`UPDATE inspections
|
||
SET inbound_batch_no = COALESCE(NULLIF(TRIM(inbound_batch_no), ''), $2)
|
||
WHERE id = $1::uuid`,
|
||
[row.inspection_id, batchNo]
|
||
);
|
||
}
|
||
const independentTotal = round2(actualQty * purchasePrice);
|
||
if (row.spi_id) {
|
||
await client.query(
|
||
`UPDATE self_purchase_stock_inbounds
|
||
SET qty = $2, unit_cost = $3, total_amount = $4, batch_no = $5, inventory_id = $6::uuid
|
||
WHERE id = $1::uuid AND inventory_id IS NULL`,
|
||
[row.spi_id, actualQty, purchasePrice, independentTotal, batchNo, inventoryId]
|
||
);
|
||
}
|
||
if (insertedNewInventory && actualQty > 0 && purchasePrice > 0) {
|
||
await upsertInventoryHoldingCost(client, {
|
||
cycleCode: currentCycleCode(),
|
||
branchCode: row.branch_code,
|
||
skuCode: row.sku_code,
|
||
amount: independentTotal,
|
||
referenceId: batchNo,
|
||
operatorId: row.inspector_id,
|
||
unitPrice: purchasePrice,
|
||
surplusQty: actualQty,
|
||
costSource: 'stock_inbound',
|
||
referenceType: 'stock_in',
|
||
costSubtype: 'stock_inbound',
|
||
remarkPrefix: 'stock_inbound',
|
||
});
|
||
}
|
||
await client.query('COMMIT');
|
||
healed += 1;
|
||
} catch (err) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
console.warn('[selfPurchaseStockInbound] heal 跳过', row.spi_id, (err as Error)?.message);
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
return healed;
|
||
}
|