Files
SupplierSystem/server/src/services/stockInboundService.ts
T
雨天 71dfe78f2a
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
feat(库存): 批次报告上传匹配 + 库存修改扩展 + 入库收尾
入库批次报告(独立表,隔离于 quality_reports):
- 上传图/PDF → OCR → 按「商品名 + 生产日期」匹配入库批次 → 人工确认落关联
- 库存列表加「批次报告」列,缺报告时标红商品名;未命中可手动选批次

库存管理「修改」扩展:批次属性加「生产日期」;区域/有效期/成本价 +
商品档案(分类/规格/单位/产地)

独立入库:备注区分 Web/小程序;生产日期多格式容错;/units 空时回退模板字典

修复:
- 库存列表日期差一天(date 出参统一 YYYY-MM-DD,避免回写日期逐次前移)
- OCR 提示词不再把检验项目当品名
2026-10-11 12:50:30 +08:00

809 lines
27 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 库存入库(无订单):inboundFromWeigh 为库存入库 / 称重终端直收入口。
* 采购「新增自采 / 加单独立入库」待验走 independentInboundService,不经过本文件的 stock-in 路由。
* 见 docs/design/20260816-ad-hoc-inbound-from-recognize.md
* docs/design/20260827-independent-inbound-flow-switch.md
*/
import type { PoolClient } from 'pg';
import { isZeroSupplyCostAllowed } from './zeroSupplyCostConfigService';
import { pool } from '../db';
import { writeAuditLog } from './auditService';
import { upsertInventoryHoldingCost } from './inventorySurplusCostService';
import { resolveStockMode } from './stockModeService';
import { createIndependentInboundInspection } from './independentInboundService';
import { assertBranchAllowsProductCatalog } from './platformBranch';
type Db = Pick<PoolClient, 'query'>;
function trimText(v: unknown): string {
return String(v || '').trim();
}
function roundQty(n: number): number {
return Math.round(n * 1000) / 1000;
}
function round2(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 newStockBatchNo(): string {
const d = new Date();
const ymd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
return `STK${ymd}${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
}
/**
* 归一为 YYYY-MM-DD。兼容 Excel/手填常见写法:
* 2026-10-09 / 2026/10/9 / 2026.10.9 / 2026年10月9日 / 2026-10(补 01)/ 20261009;无法识别返回 null。
*/
function normalizeProductionDate(raw: unknown): string | null {
let s = trimText(raw);
if (!s) return null;
s = s
.replace(/[年月]/g, '-')
.replace(/日/g, '')
.replace(/[./]/g, '-')
.replace(/\s+/g, '')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
const full = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
if (full) {
const mm = Number(full[2]);
const dd = Number(full[3]);
if (mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31) {
return `${full[1]}-${full[2].padStart(2, '0')}-${full[3].padStart(2, '0')}`;
}
return null;
}
const ym = s.match(/^(\d{4})-(\d{1,2})$/);
if (ym) {
const mm = Number(ym[2]);
if (mm >= 1 && mm <= 12) return `${ym[1]}-${ym[2].padStart(2, '0')}-01`;
return null;
}
const compact = s.match(/^(\d{4})(\d{2})(\d{2})$/);
if (compact) {
const mm = Number(compact[2]);
const dd = Number(compact[3]);
if (mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31) {
return `${compact[1]}-${compact[2]}-${compact[3]}`;
}
return null;
}
return null;
}
export interface StockInboundInput {
skuCode: string;
qty: number;
unitCost: number;
branchCode: string;
productionDate?: string | null;
remark?: string | null;
operatorId?: string | null;
/** 可选入库照片 base64 */
imageBase64?: string | null;
/** 可选:写入商品档案单位 */
unit?: string | null;
/** 再完成独立入库时复用 SPI 批次号 */
batchNo?: string | null;
/** 可选:拍照入库时人工改过的商品档案字段(见 docs/design/20261012-……档案回写.md) */
archive?: ArchiveWritebackInput | null;
}
/**
* 拍照入库的人工修正值:**只回写调用方显式传进来的字段**。
* 未传的字段一律不动 —— 「人工值优先直接覆盖」的操作定义就是「只认人工编辑过的字段」,
* 避免未经人工确认的 AI 识别值污染商品档案。
*
* `manufacturer`(厂家,前端语义)映射到库里的 `skus.origin` 列(复用现有列,未新增 manufacturer 列)。
*/
export interface ArchiveWritebackInput {
spec?: string | null;
brand?: string | null;
manufacturer?: string | null;
}
/** skus.spec / brand / origin 三列均为 VARCHAR(100),先截断再落库,避免 22001 打断入库事务 */
const ARCHIVE_FIELD_MAX = 100;
/** 客户端上报值的长度上限;落库时还会按列宽再截断一次 */
const ARCHIVE_INPUT_MAX = 200;
const ARCHIVE_FIELDS = ['spec', 'brand', 'manufacturer'] as const;
/**
* 归一化移动端上报的 `archive`:**逐个字段判在不在**,不在的字段保持 `undefined`(服务端就不写它)。
* 返回 `null` = 本次不产生任何档案回写。
*
* 与 `applyArchiveWriteback` 放在一起:二者是「校验入参 → 落库写入」的一对,
* 分开会让「哪些字段算人工值」的判据在两层各写一份。
*/
export function normalizeArchive(raw: unknown): ArchiveWritebackInput | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const source = raw as Record<string, unknown>;
const archive: ArchiveWritebackInput = {};
let any = false;
for (const field of ARCHIVE_FIELDS) {
if (!Object.prototype.hasOwnProperty.call(source, field)) continue;
const value = source[field];
if (value == null) continue;
archive[field] = String(value).slice(0, ARCHIVE_INPUT_MAX);
any = true;
}
return any ? archive : null;
}
function hasAnyArchiveField(archive?: ArchiveWritebackInput | null): boolean {
if (!archive) return false;
return (
archive.spec != null || archive.brand != null || archive.manufacturer != null
);
}
/**
* 把人工确认过的规格 / 品牌 / 厂家写回商品档案。
*
* · 规格、品牌 → `product_catalog`,由触发器 `sync_product_catalog_to_legacy()` 同步到 `skus`;
* · 厂家 → **显式写 `skus.origin`**,因为该触发器不复制 `origin`;
* · 与入库同事务:入库失败则回写一并回滚,不会出现「档案改了但货没入库」;
* · 取值先 TRIM(与既有 `trimText` 口径一致),空串会被**当成一次真实的清空**写入。
*/
export async function applyArchiveWriteback(
db: Db,
input: { skuCode: string; branchCode?: string | null; archive?: ArchiveWritebackInput | null }
): Promise<void> {
if (!hasAnyArchiveField(input.archive)) return;
const skuCode = trimText(input.skuCode);
if (!skuCode) return;
assertBranchAllowsProductCatalog(trimText(input.branchCode) || null);
const archive = input.archive!;
const hasCatalogField = archive.spec != null || archive.brand != null;
if (hasCatalogField) {
await db.query(
`UPDATE product_catalog
SET spec = CASE WHEN $1::boolean THEN LEFT(TRIM($2), ${ARCHIVE_FIELD_MAX}) ELSE spec END,
brand = CASE WHEN $3::boolean THEN LEFT(TRIM($4), ${ARCHIVE_FIELD_MAX}) ELSE brand END,
updated_at = NOW()
WHERE item_type = 'product' AND code = $5`,
[
archive.spec != null,
archive.spec == null ? null : String(archive.spec),
archive.brand != null,
archive.brand == null ? null : String(archive.brand),
skuCode,
]
);
}
// 触发器不复制 origin ⇒ 厂家必须显式写 skus
if (archive.manufacturer != null) {
await db.query(
`UPDATE skus SET origin = LEFT(TRIM($2), ${ARCHIVE_FIELD_MAX}) WHERE sku_code = $1`,
[skuCode, String(archive.manufacturer)]
);
}
}
export interface StockInboundResult {
batch_no: string;
sku_code: string;
qty: number;
unit_cost: number;
inventory_id: string;
sku_name?: string | null;
unit?: string | null;
photo_path?: string | null;
}
export async function inboundFromWeigh(
input: StockInboundInput,
client?: PoolClient
): Promise<StockInboundResult> {
const skuCode = trimText(input.skuCode);
const branchCode = trimText(input.branchCode);
const qty = roundQty(Number(input.qty));
const unitCost = round2(Number(input.unitCost));
const productionDate = normalizeProductionDate(input.productionDate);
const remark = trimText(input.remark) || '独立入库';
if (!skuCode) {
throw Object.assign(new Error('缺少商品编码'), { status: 400, code: 'invalid_request' });
}
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 allowZeroCost = await isZeroSupplyCostAllowed(branchCode);
if (allowZeroCost) {
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 own = client ? null : await pool.connect();
const db: Db = client || own!;
const manageTx = !client;
try {
if (manageTx) await db.query('BEGIN');
const skuRow = await db.query(
`SELECT s.sku_code, s.sku_name, s.unit
FROM skus s
WHERE s.sku_code = $1
LIMIT 1`,
[skuCode]
);
if (!skuRow.rowCount) {
throw Object.assign(new Error('商品不存在'), { status: 404, code: 'not_found' });
}
const skuName = skuRow.rows[0]?.sku_name ? String(skuRow.rows[0].sku_name) : null;
let unit = skuRow.rows[0]?.unit ? String(skuRow.rows[0].unit) : null;
const inboundUnit = trimText(input.unit);
if (inboundUnit && inboundUnit !== unit) {
await db.query(`UPDATE skus SET unit = $1 WHERE sku_code = $2`, [inboundUnit, skuCode]);
unit = inboundUnit;
}
// 拍照入库:人工改过的规格/品牌/厂家回写商品档案(只写传进来的字段,与入库同事务)
await applyArchiveWriteback(db, {
skuCode,
branchCode,
archive: input.archive,
});
const mode = await resolveStockMode({ skuCode, branchCode }, db);
if (mode !== 'inventory') {
throw Object.assign(new Error('过手商品不能独立入库,请先在商品管理改为「管库存」'), {
status: 400,
code: 'pass_through_rejected',
});
}
const batchNo = trimText(input.batchNo) || newStockBatchNo();
let photoPath: string | null = null;
const imageBase64 = trimText(input.imageBase64);
if (imageBase64) {
try {
const { saveBase64Upload } = await import('./storageUploadService');
const saved = await saveBase64Upload('inspection-photos', imageBase64, 'jpg', {
objectPrefix: `stock-in/${batchNo}`,
});
photoPath = typeof saved === 'string' ? saved : null;
} catch (err) {
console.warn('[stock-inbound] photo upload failed:', err);
}
}
const logRemark = photoPath ? `${remark};photo=${photoPath}` : remark;
const inserted = await db.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,
COALESCE($6::date, (NOW() AT TIME ZONE 'Asia/Shanghai')::date))
RETURNING id::text AS id`,
[batchNo, skuCode, qty, unitCost, branchCode, productionDate]
);
const inventoryId = String(inserted.rows[0]?.id || '');
await db.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', $3, 0, $3, NULL, $4, $5)`,
[batchNo, skuCode, qty, input.operatorId || null, logRemark]
);
const amount = round2(qty * unitCost);
await upsertInventoryHoldingCost(db, {
cycleCode: currentCycleCode(),
branchCode,
skuCode,
amount,
referenceId: batchNo,
operatorId: input.operatorId,
unitPrice: unitCost,
surplusQty: qty,
costSource: 'stock_inbound',
referenceType: 'stock_in',
costSubtype: 'stock_inbound',
remarkPrefix: 'stock_inbound',
});
if (manageTx) await db.query('COMMIT');
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'stock_inbound',
targetTable: 'inventory',
targetId: batchNo,
newValue: {
sku_code: skuCode,
qty,
unit_cost: unitCost,
branch_code: branchCode,
inventory_id: inventoryId,
photo_path: photoPath,
},
branchCode,
});
return {
batch_no: batchNo,
sku_code: skuCode,
qty,
unit_cost: unitCost,
inventory_id: inventoryId,
sku_name: skuName,
unit,
photo_path: photoPath,
};
} catch (e) {
if (manageTx) {
try {
await db.query('ROLLBACK');
} catch {
/* ignore */
}
}
throw e;
} finally {
if (own) own.release();
}
}
// ============================================================
// 批量导入库存(Excel 导入;只增不覆盖;成本可空)
// 设计:docs/design/20261010-仓库区域编号与批量导入库存.md
// ============================================================
export interface StockImportRowInput {
rowNumber?: number;
skuCode: string;
qty: number;
/** 可空:空/0 = 成本为 0(不生成持有成本),事后可补 */
unitCost?: number | null;
/** 可空:给了且已存在 → 累加该批次;否则新建批次 */
batchNo?: string | null;
productionDate?: string | null;
expiryDate?: string | null;
storageZone?: string | null;
}
export interface StockImportRowResult {
rowNumber: number;
sku_code: string;
sku_name: string | null;
unit: string | null;
batch_no: string | null;
qty: number;
unit_cost: number;
mode: 'new_batch' | 'accumulated' | 'failed';
inventory_id: string | null;
storage_zone: string | null;
error?: string;
}
export interface BulkStockInboundResult {
results: StockImportRowResult[];
ok_count: number;
failed_count: number;
new_batch_count: number;
accumulated_count: number;
}
/**
* 批量入库:每 chunkSize 行一个事务(默认/上限 200,沿用冻结参数);
* 行级 SAVEPOINT 容错(单行失败不拖垮整块);同 (sku_code,batch_no) 累加(绝不覆盖)。
* 成本可空(空/0 写 0),**不依赖**「允许成本价为 0」开关。商品须已存在(建品在前置步骤完成)。
*/
export async function bulkStockInbound(input: {
branchCode: string;
operatorId?: string | null;
rows: StockImportRowInput[];
chunkSize?: number;
/** 库存流水备注;不传则用 Excel 导入默认文案 */
remark?: string | null;
}): Promise<BulkStockInboundResult> {
const branchCode = trimText(input.branchCode);
if (!branchCode) {
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
}
const rows = Array.isArray(input.rows) ? input.rows : [];
const chunkSize = Math.min(Math.max(1, Number(input.chunkSize) || 200), 200);
const results: StockImportRowResult[] = [];
const client = await pool.connect();
try {
for (let start = 0; start < rows.length; start += chunkSize) {
const chunk = rows.slice(start, start + chunkSize);
await client.query('BEGIN');
try {
for (let i = 0; i < chunk.length; i += 1) {
const row = chunk[i];
const rowNumber = Number(row.rowNumber) || start + i + 1;
await client.query('SAVEPOINT sp_row');
try {
const r = await writeStockImportRow(client, {
branchCode,
operatorId: input.operatorId,
rowNumber,
row,
remark: input.remark,
});
results.push(r);
await client.query('RELEASE SAVEPOINT sp_row');
} catch (e: any) {
await client.query('ROLLBACK TO SAVEPOINT sp_row');
results.push({
rowNumber,
sku_code: trimText(row.skuCode),
sku_name: null,
unit: null,
batch_no: trimText(row.batchNo) || null,
qty: Number.isFinite(Number(row.qty)) ? roundQty(Number(row.qty)) : 0,
unit_cost: 0,
mode: 'failed',
inventory_id: null,
storage_zone: trimText(row.storageZone) || null,
error: e?.message || '入库失败',
});
}
}
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
}
}
} finally {
client.release();
}
const ok = results.filter((r) => r.mode !== 'failed');
return {
results,
ok_count: ok.length,
failed_count: results.length - ok.length,
new_batch_count: ok.filter((r) => r.mode === 'new_batch').length,
accumulated_count: ok.filter((r) => r.mode === 'accumulated').length,
};
}
async function writeStockImportRow(
db: Db,
args: {
branchCode: string;
operatorId?: string | null;
rowNumber: number;
row: StockImportRowInput;
remark?: string | null;
}
): Promise<StockImportRowResult> {
const { branchCode, operatorId, rowNumber, row } = args;
const skuCode = trimText(row.skuCode);
if (!skuCode) throw Object.assign(new Error('缺少商品编码'), { status: 400 });
const qty = roundQty(Number(row.qty));
if (!Number.isFinite(qty) || qty <= 0) {
throw Object.assign(new Error('入库数量须大于 0'), { status: 400 });
}
const rawCost = row.unitCost;
const unitCost =
rawCost === null || rawCost === undefined || String(rawCost).trim() === ''
? 0
: round2(Number(rawCost));
if (!Number.isFinite(unitCost) || unitCost < 0) {
throw Object.assign(new Error('成本价无效'), { status: 400 });
}
const skuRow = await db.query(
`SELECT sku_code, sku_name, unit FROM skus WHERE sku_code = $1 LIMIT 1`,
[skuCode]
);
if (!skuRow.rowCount) throw Object.assign(new Error('商品不存在'), { status: 404 });
const skuName = skuRow.rows[0]?.sku_name ? String(skuRow.rows[0].sku_name) : null;
const unit = skuRow.rows[0]?.unit ? String(skuRow.rows[0].unit) : null;
const mode = await resolveStockMode({ skuCode, branchCode }, db);
if (mode !== 'inventory') {
throw Object.assign(new Error('过手商品不能入库,请先在商品管理改为「管库存」'), { status: 400 });
}
const batchNo = trimText(row.batchNo) || newStockBatchNo();
const productionDate = normalizeProductionDate(row.productionDate);
const expiryDate = normalizeProductionDate(row.expiryDate);
const storageZone = trimText(row.storageZone) || null;
const up = await db.query(
`INSERT INTO inventory (
batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status, branch_code,
production_date, expiry_date, storage_zone
)
VALUES ($1, $2, $3, $3, NULL, $4, 10, $5,
COALESCE($6::date, (NOW() AT TIME ZONE 'Asia/Shanghai')::date), $7::date, $8)
ON CONFLICT (sku_code, batch_no) DO UPDATE SET
quantity = inventory.quantity + EXCLUDED.quantity,
available_qty = inventory.available_qty + EXCLUDED.available_qty,
cost_price = CASE WHEN EXCLUDED.cost_price > 0 THEN EXCLUDED.cost_price ELSE inventory.cost_price END,
expiry_date = COALESCE(EXCLUDED.expiry_date, inventory.expiry_date),
storage_zone = COALESCE(EXCLUDED.storage_zone, inventory.storage_zone),
status = 10
RETURNING id::text AS id, available_qty, (xmax = 0) AS inserted`,
[batchNo, skuCode, qty, unitCost, branchCode, productionDate, expiryDate, storageZone]
);
const inventoryId = String(up.rows[0]?.id || '');
const afterQty = Number(up.rows[0]?.available_qty) || qty;
const inserted = up.rows[0]?.inserted === true;
const beforeQty = roundQty(afterQty - qty);
await db.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', $3, $4, $5, NULL, $6, $7)`,
[batchNo, skuCode, qty, beforeQty, afterQty, operatorId || null, trimText(args.remark) || 'Excel 批量导入库存']
);
if (unitCost > 0) {
await applyHoldingDelta(db, {
branchCode,
skuCode,
batchNo,
delta: round2(qty * unitCost),
unitPrice: unitCost,
qty,
operatorId,
});
}
return {
rowNumber,
sku_code: skuCode,
sku_name: skuName,
unit,
batch_no: batchNo,
qty,
unit_cost: unitCost,
mode: inserted ? 'new_batch' : 'accumulated',
inventory_id: inventoryId,
storage_zone: storageZone,
};
}
/** 进仓持有成本:同批次**累加**(不覆盖历史),无则新建(reference_type=stock_in) */
async function applyHoldingDelta(
db: Db,
args: {
branchCode: string;
skuCode: string;
batchNo: string;
delta: number;
unitPrice: number;
qty: number;
operatorId?: string | null;
}
): Promise<void> {
const { branchCode, skuCode, batchNo, delta } = args;
const existing = await db.query(
`SELECT id::text AS id FROM cost_details
WHERE cost_type = 'inventory_holding' AND reference_id = $1
LIMIT 1 FOR UPDATE`,
[batchNo]
);
if (existing.rowCount) {
await db.query(
`UPDATE cost_details
SET amount = COALESCE(amount, 0) + $2,
cycle_code = $3,
branch_code = COALESCE($4, branch_code),
sku_code = $5,
status = 20,
order_code = NULL
WHERE id = $1`,
[existing.rows[0].id, delta, currentCycleCode(), branchCode, skuCode]
);
return;
}
await db.query(
`INSERT INTO cost_details (
cycle_code, order_code, cost_type, cost_subtype, amount, status,
branch_code, sku_code, reference_type, reference_id, inputter_id, cost_source, remark
) VALUES ($1, NULL, 'inventory_holding', 'stock_inbound', $2, 20, $3, $4, 'stock_in', $5, $6::uuid, 'stock_inbound', $7)`,
[
currentCycleCode(),
delta,
branchCode,
skuCode,
batchNo,
args.operatorId || null,
`stock_inbound;qty=${round2(args.qty)};unit=${round2(args.unitPrice)}`,
]
);
}
export interface PendingStockInboundResult {
inspection_id: string;
batch_no: string;
sku_code: string;
qty: number;
unit_cost: number;
sku_name?: string | null;
unit?: string | null;
}
/**
* 独立入库默认入口:只建待验单(inspections 待验行),不写库存;
* 仓管称重验收通过后才由验收链路写库存(数量以实称为准)。
* 称重终端 STOCK_IN 模式仍走 inboundFromWeigh 直收。
*/
export async function createPendingStockInbound(
input: StockInboundInput,
client?: PoolClient
): Promise<PendingStockInboundResult> {
const skuCode = trimText(input.skuCode);
const branchCode = trimText(input.branchCode);
const qty = roundQty(Number(input.qty));
const unitCost = round2(Number(input.unitCost));
if (!skuCode) {
throw Object.assign(new Error('缺少商品编码'), { status: 400, code: 'invalid_request' });
}
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 allowZeroCost = await isZeroSupplyCostAllowed(branchCode);
if (allowZeroCost) {
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 own = client ? null : await pool.connect();
const db: Db = client || own!;
const manageTx = !client;
try {
if (manageTx) await db.query('BEGIN');
const skuRow = await db.query(
`SELECT s.sku_code, s.sku_name, s.unit
FROM skus s
WHERE s.sku_code = $1
LIMIT 1`,
[skuCode]
);
if (!skuRow.rowCount) {
throw Object.assign(new Error('商品不存在'), { status: 404, code: 'not_found' });
}
const skuName = skuRow.rows[0]?.sku_name ? String(skuRow.rows[0].sku_name) : null;
let unit = skuRow.rows[0]?.unit ? String(skuRow.rows[0].unit) : null;
const inboundUnit = trimText(input.unit);
if (inboundUnit && inboundUnit !== unit) {
await db.query(`UPDATE skus SET unit = $1 WHERE sku_code = $2`, [inboundUnit, skuCode]);
unit = inboundUnit;
}
const mode = await resolveStockMode({ skuCode, branchCode }, db);
if (mode !== 'inventory') {
throw Object.assign(new Error('过手商品不能独立入库,请先在商品管理改为「管库存」'), {
status: 400,
code: 'pass_through_rejected',
});
}
const created = await createIndependentInboundInspection(db, {
skuCode,
itemName: skuName || skuCode,
qty,
unitCost,
branchCode,
unit: unit || undefined,
remark: trimText(input.remark) || '独立入库',
productionDate: input.productionDate,
});
if (manageTx) await db.query('COMMIT');
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'stock_inbound_pending',
targetTable: 'inspections',
targetId: created.inspectionId,
newValue: {
sku_code: skuCode,
qty,
unit_cost: unitCost,
branch_code: branchCode,
},
branchCode,
});
return {
inspection_id: created.inspectionId,
batch_no: created.batchNo,
sku_code: skuCode,
qty,
unit_cost: unitCost,
sku_name: skuName,
unit,
};
} catch (e) {
if (manageTx) {
try {
await db.query('ROLLBACK');
} catch {
/* ignore */
}
}
throw e;
} finally {
if (own) own.release();
}
}
export async function listInboundHoldingCosts(input: {
branchCode?: string | null;
cycleCode?: string | null;
costSource?: string | null;
limit?: number;
}): Promise<any[]> {
const branch = trimText(input.branchCode) || null;
const cycle = trimText(input.cycleCode) || null;
const costSource = trimText(input.costSource) || null;
const limit = Math.min(200, Math.max(1, Number(input.limit) || 50));
const params: unknown[] = [];
const filters: string[] = [`cd.cost_type = 'inventory_holding'`];
if (branch) {
params.push(branch);
filters.push(`cd.branch_code IS NOT DISTINCT FROM $${params.length}`);
}
if (cycle) {
params.push(cycle);
filters.push(`cd.cycle_code = $${params.length}`);
}
if (costSource) {
params.push(costSource);
filters.push(`cd.cost_source IS NOT DISTINCT FROM $${params.length}`);
}
params.push(limit);
const result = await pool.query(
`SELECT cd.id::text AS id, cd.cycle_code, cd.branch_code, cd.sku_code,
COALESCE(s.sku_name, pc.name, cd.sku_code) AS sku_name,
cd.amount, cd.cost_source, cd.cost_subtype, cd.reference_type, cd.reference_id,
cd.remark, cd.created_at, cd.status
FROM cost_details cd
LEFT JOIN skus s ON s.sku_code = cd.sku_code
LEFT JOIN product_catalog pc ON pc.item_type = 'product' AND pc.code = cd.sku_code
WHERE ${filters.join(' AND ')}
ORDER BY cd.created_at DESC NULLS LAST
LIMIT $${params.length}`,
params
);
return result.rows;
}