416 lines
17 KiB
TypeScript
416 lines
17 KiB
TypeScript
/**
|
||
* 库存管理「修改」——批次属性 + 商品档案字段编辑。
|
||
*
|
||
* 设计:docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md
|
||
*
|
||
* 口径:
|
||
* - **批次级**(只影响这一批):`storage_zone` / `shelf_life` / `cost_price` / `production_date`(写 `inventory`)。
|
||
* **有效期 `expiry_date` 不接受手填**:只要这一轮动了 `shelf_life` 或 `production_date`,
|
||
* 就用 `deriveExpiryDate(生产日期, 保质期原文)` 重算(推不出则清空)—— 见 `server/src/utils/shelfLife.ts`。
|
||
* - **商品级**(影响该商品所有批次):`category_code`/`spec`/`unit` 写 **商品真源 `product_catalog`**,
|
||
* 由既有单向触发器同步到 `skus`;**`origin` 不在 `product_catalog`**(实测无该列),故直写 `skus.origin`
|
||
* (先例:`skuProvisioningService` 的档案回写)。
|
||
* - **数量不在此接口**:可用数量仍走 `adjustInventoryAvailableQty`(双日志/预留释放等冻结语义不动)。
|
||
* - 成本价按开发者口径 **只改批次成本,不回冲已入账的持有成本流水**。
|
||
* - 留痕:写 `operation_logs`(跳 `inventory_logs`,避免与「数量流水」混淆)。
|
||
*/
|
||
import { pool } from '../db';
|
||
import { writeAuditLog } from './auditService';
|
||
import { deriveExpiryDate } from '../utils/shelfLife';
|
||
|
||
function trimText(v: unknown): string {
|
||
return String(v ?? '').trim();
|
||
}
|
||
|
||
/** pg 的 `date` 返回本地午夜 Date;统一成 'YYYY-MM-DD'(否则变更比对会被 `String(Date)` 弄乱) */
|
||
function toDateOnly(v: unknown): string | null {
|
||
if (v == null) return null;
|
||
if (v instanceof Date) {
|
||
if (Number.isNaN(v.getTime())) return null;
|
||
const y = v.getFullYear();
|
||
const m = String(v.getMonth() + 1).padStart(2, '0');
|
||
const d = String(v.getDate()).padStart(2, '0');
|
||
return `${y}-${m}-${d}`;
|
||
}
|
||
const s = String(v).trim();
|
||
return s ? s.slice(0, 10) : null;
|
||
}
|
||
|
||
/** 'YYYY-MM-DD' → 原样;空串/null → null;其它 → 抛错 */
|
||
function normalizeDateOrNull(v: unknown): string | null {
|
||
const t = trimText(v);
|
||
if (!t) return null;
|
||
const m = t.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/);
|
||
if (!m) {
|
||
throw Object.assign(new Error('日期格式应为 YYYY-MM-DD'), { status: 400, code: 'invalid_date' });
|
||
}
|
||
return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`;
|
||
}
|
||
|
||
export interface UpdateInventoryBatchInput {
|
||
inventoryId: string;
|
||
branchCode: string;
|
||
operatorId?: string | null;
|
||
remark: string;
|
||
/** 批次级;`undefined` = 不改 */
|
||
storageZone?: string | null;
|
||
/** 批次级:保质期原文(如 `7天`/`6个月`/`1年`)或 ''(清空);由它 + 生产日期推算有效期 */
|
||
shelfLife?: string | null;
|
||
/** 批次级:'YYYY-MM-DD' 或 ''(清空);不参与 FIFO/成本/预留 */
|
||
productionDate?: string | null;
|
||
/** 批次级:数字或 null(清空) */
|
||
costPrice?: number | null;
|
||
/** 批次级产地(生产地区);'' = 清空,undefined = 不改 */
|
||
batchOrigin?: string | null;
|
||
/** 商品级;`undefined` = 不改 */
|
||
categoryCode?: string | null;
|
||
spec?: string | null;
|
||
unit?: string | null;
|
||
origin?: string | null;
|
||
}
|
||
|
||
export interface UpdateInventoryBatchResult {
|
||
id: string;
|
||
batch_no: string;
|
||
sku_code: string;
|
||
changed: string[];
|
||
/**
|
||
* 本次改了成本价时的重算结果:`affected` = 被重算的未结算订单数,
|
||
* `skipped_settled` = 因已结算而未回改的订单数(口径见 inventoryBatchCostService)。
|
||
*/
|
||
cost_recalc?: { affected: number; skipped_settled: number } | null;
|
||
}
|
||
|
||
export async function updateInventoryBatchAttributes(
|
||
input: UpdateInventoryBatchInput
|
||
): Promise<UpdateInventoryBatchResult> {
|
||
const inventoryId = trimText(input.inventoryId);
|
||
const branchCode = trimText(input.branchCode);
|
||
/**
|
||
* 备注改为**选填**(开发者 2026-10-15:「当前这块 调整备注不是必填选项 改为可填」)。
|
||
* 空备注不再拦,落库时补一个中性标签(与 `inventoryAdjustService` 的
|
||
* `|| '入库量纠错'` 同一先例),保证审计里**永远有可读留痕**;本函数一贯
|
||
* **只写 `operation_logs` 审计、跳 `inventory_logs`**(避免与「数量流水」混淆),
|
||
* 这条既有设计连同「权限 + 通用网关禁写」一概不动。
|
||
*/
|
||
const remark = trimText(input.remark) || '库存批次修改';
|
||
if (!inventoryId) {
|
||
throw Object.assign(new Error('缺少库存记录'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
if (!branchCode) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
|
||
const locked = await client.query(
|
||
`SELECT id, batch_no, sku_code, storage_zone, shelf_life, expiry_date, production_date, cost_price, origin
|
||
FROM inventory
|
||
WHERE id = $1::uuid AND branch_code = $2
|
||
FOR UPDATE`,
|
||
[inventoryId, branchCode]
|
||
);
|
||
if (!locked.rowCount) {
|
||
throw Object.assign(new Error('库存记录不存在或不属于当前分公司'), {
|
||
status: 404,
|
||
code: 'not_found',
|
||
});
|
||
}
|
||
const row = locked.rows[0];
|
||
const skuCode = trimText(row.sku_code);
|
||
const beforeBatch = {
|
||
storage_zone: row.storage_zone == null ? null : String(row.storage_zone),
|
||
shelf_life: row.shelf_life == null ? null : String(row.shelf_life),
|
||
expiry_date: toDateOnly(row.expiry_date),
|
||
production_date: toDateOnly(row.production_date),
|
||
cost_price: row.cost_price == null ? null : Number(row.cost_price),
|
||
/** 批次产地(2026-10-21):写进前值才能判断"真的改了吗",避免同值重复写/重复审计 */
|
||
origin: row.origin == null ? null : String(row.origin),
|
||
};
|
||
|
||
const changed: string[] = [];
|
||
/**
|
||
* 商品档案(分类/规格/单位/产地)的**修改前**值:本轮改动前只记了批次级前值,
|
||
* 于是操作日志里"分类 从 X 改成 Y"根本没有 X。开发者也点名要求
|
||
* 「修改前是什么 / 修改后什么 / 改的什么 都要留痕」⇒ 前值补全。
|
||
*/
|
||
let beforeProductAudit: Record<string, string | null> | null = null;
|
||
|
||
// ── 批次级 ────────────────────────────────────────
|
||
const batchSets: string[] = [];
|
||
const batchParams: unknown[] = [];
|
||
|
||
// 「改后」值先算出来:有效期由 生产日期 + 保质期 派生,需要两者一致快照
|
||
const nextProductionDate =
|
||
input.productionDate !== undefined
|
||
? normalizeDateOrNull(input.productionDate)
|
||
: beforeBatch.production_date;
|
||
const nextShelfLife =
|
||
input.shelfLife !== undefined ? trimText(input.shelfLife) || null : beforeBatch.shelf_life;
|
||
|
||
if (input.storageZone !== undefined) {
|
||
const next = trimText(input.storageZone) || null;
|
||
if ((beforeBatch.storage_zone || null) !== next) {
|
||
batchParams.push(next);
|
||
batchSets.push(`storage_zone = $${batchParams.length}`);
|
||
changed.push('storage_zone');
|
||
}
|
||
}
|
||
if (input.shelfLife !== undefined) {
|
||
if ((beforeBatch.shelf_life || null) !== nextShelfLife) {
|
||
batchParams.push(nextShelfLife);
|
||
batchSets.push(`shelf_life = $${batchParams.length}`);
|
||
changed.push('shelf_life');
|
||
}
|
||
}
|
||
if (input.productionDate !== undefined) {
|
||
if ((beforeBatch.production_date || null) !== nextProductionDate) {
|
||
batchParams.push(nextProductionDate);
|
||
batchSets.push(`production_date = $${batchParams.length}::date`);
|
||
changed.push('production_date');
|
||
}
|
||
}
|
||
// 有效期**永远派生**:这一轮动了生产日期或保质期就重算(推不出则清空),不接受手填
|
||
if (input.productionDate !== undefined || input.shelfLife !== undefined) {
|
||
const derived = deriveExpiryDate(nextProductionDate, nextShelfLife);
|
||
if ((beforeBatch.expiry_date || null) !== (derived || null)) {
|
||
batchParams.push(derived);
|
||
batchSets.push(`expiry_date = $${batchParams.length}::date`);
|
||
changed.push('expiry_date');
|
||
}
|
||
}
|
||
/** 成本价变化时记下来:改完要在**同一事务**里重算订单抵扣账本(见下方) */
|
||
let costChange: { before: number; after: number } | null = null;
|
||
if (input.costPrice !== undefined) {
|
||
const raw = input.costPrice;
|
||
const next = raw == null || trimText(raw) === '' ? null : Number(raw);
|
||
if (next != null && (!Number.isFinite(next) || next < 0)) {
|
||
throw Object.assign(new Error('成本价须为不小于 0 的数字'), {
|
||
status: 400,
|
||
code: 'invalid_cost',
|
||
});
|
||
}
|
||
if ((beforeBatch.cost_price ?? null) !== (next ?? null)) {
|
||
batchParams.push(next);
|
||
batchSets.push(`cost_price = $${batchParams.length}::numeric`);
|
||
changed.push('cost_price');
|
||
costChange = { before: Number(beforeBatch.cost_price) || 0, after: Number(next) || 0 };
|
||
}
|
||
}
|
||
if (input.batchOrigin !== undefined) {
|
||
const next = trimText(input.batchOrigin) || null;
|
||
if (next && next.length > 200) {
|
||
throw Object.assign(new Error('产地不得超过 200 个字符'), { status: 400, code: 'invalid_origin' });
|
||
}
|
||
const before = (beforeBatch as Record<string, unknown>).origin;
|
||
const beforeText = before == null ? null : String(before);
|
||
if ((beforeText ?? null) !== (next ?? null)) {
|
||
batchParams.push(next);
|
||
batchSets.push(`origin = $${batchParams.length}`);
|
||
changed.push('origin');
|
||
}
|
||
}
|
||
if (batchSets.length) {
|
||
batchParams.push(inventoryId);
|
||
await client.query(
|
||
`UPDATE inventory SET ${batchSets.join(', ')} WHERE id = $${batchParams.length}::uuid`,
|
||
batchParams
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 改成本 ⇒ **同一事务**重算「抵扣了这一批」的未结算订单账本 + 写 `adjust` 流水。
|
||
*
|
||
* 2026-10-15 缺陷:本入口原先只写 `inventory.cost_price`,而订单详情「抵扣成本价」是
|
||
* **直读账本**(`cost_details.inventory_cover` ÷ 抵扣量)⇒ 改完成本订单里还是旧价
|
||
* (开发者实测:批次 11.00、订单仍显示 10.00)。现与抵扣弹窗「改成本」走**同一个**重算函数,
|
||
* 口径=只重算未结算订单(已结算不回改)。
|
||
*/
|
||
let costRecalc: { affected: number; skipped_settled: number } | null = null;
|
||
if (costChange) {
|
||
const { recalcCoverLedgerForBatchCostChange } = await import('./inventoryBatchCostService');
|
||
const impact = await recalcCoverLedgerForBatchCostChange(client, {
|
||
batchNo: String(row.batch_no),
|
||
skuCode,
|
||
beforeCost: costChange.before,
|
||
afterCost: costChange.after,
|
||
branchCode,
|
||
operatorId: input.operatorId || null,
|
||
remark,
|
||
});
|
||
costRecalc = { affected: impact.affected_count, skipped_settled: impact.skipped_count };
|
||
}
|
||
|
||
// ── 商品级 ──────────────────────────────────────────────
|
||
const productTouched =
|
||
input.categoryCode !== undefined ||
|
||
input.spec !== undefined ||
|
||
input.unit !== undefined ||
|
||
input.origin !== undefined;
|
||
|
||
if (productTouched) {
|
||
if (!skuCode) {
|
||
throw Object.assign(new Error('该库存批次没有商品编码,无法改商品档案'), {
|
||
status: 400,
|
||
code: 'no_sku',
|
||
});
|
||
}
|
||
const skuRow = await client.query(
|
||
`SELECT sku_name, category_code, spec, unit, origin FROM skus WHERE sku_code = $1 LIMIT 1`,
|
||
[skuCode]
|
||
);
|
||
const sku = skuRow.rows[0] || {};
|
||
const beforeProduct = {
|
||
category_code: sku.category_code == null ? null : String(sku.category_code),
|
||
spec: sku.spec == null ? null : String(sku.spec),
|
||
unit: sku.unit == null ? null : String(sku.unit),
|
||
origin: sku.origin == null ? null : String(sku.origin),
|
||
};
|
||
beforeProductAudit = { ...beforeProduct };
|
||
|
||
// 分类 / 规格 / 单位 → 写商品真源 product_catalog(触发器同步 skus)
|
||
const pcSets: string[] = [];
|
||
const pcParams: unknown[] = [];
|
||
const skuSets: string[] = [];
|
||
const skuParams: unknown[] = [];
|
||
|
||
if (input.categoryCode !== undefined) {
|
||
const next = trimText(input.categoryCode) || null;
|
||
if ((beforeProduct.category_code || null) !== next) {
|
||
pcParams.push(next);
|
||
pcSets.push(`parent_code = $${pcParams.length}`);
|
||
skuParams.push(next);
|
||
skuSets.push(`category_code = $${skuParams.length}`);
|
||
changed.push('category_code');
|
||
}
|
||
}
|
||
if (input.spec !== undefined) {
|
||
const next = trimText(input.spec) || null;
|
||
if ((beforeProduct.spec || null) !== next) {
|
||
pcParams.push(next);
|
||
pcSets.push(`spec = $${pcParams.length}`);
|
||
skuParams.push(next);
|
||
skuSets.push(`spec = $${skuParams.length}`);
|
||
changed.push('spec');
|
||
}
|
||
}
|
||
if (input.unit !== undefined) {
|
||
const next = trimText(input.unit) || null;
|
||
if ((beforeProduct.unit || null) !== next) {
|
||
pcParams.push(next);
|
||
pcSets.push(`unit = $${pcParams.length}`);
|
||
skuParams.push(next);
|
||
skuSets.push(`unit = $${skuParams.length}`);
|
||
changed.push('unit');
|
||
}
|
||
}
|
||
// origin 仅存在于 skus(product_catalog 无该列)
|
||
if (input.origin !== undefined) {
|
||
const next = trimText(input.origin) || null;
|
||
if ((beforeProduct.origin || null) !== next) {
|
||
skuParams.push(next);
|
||
skuSets.push(`origin = $${skuParams.length}`);
|
||
changed.push('origin');
|
||
}
|
||
}
|
||
|
||
if (pcSets.length) {
|
||
pcParams.push(skuCode, branchCode);
|
||
await client.query(
|
||
`UPDATE product_catalog
|
||
SET ${pcSets.join(', ')}
|
||
WHERE item_type = 'product'
|
||
AND code = $${pcParams.length - 1}
|
||
AND (branch_code = $${pcParams.length} OR branch_code IS NULL)`,
|
||
pcParams
|
||
);
|
||
}
|
||
if (skuSets.length) {
|
||
skuParams.push(skuCode);
|
||
await client.query(
|
||
`UPDATE skus SET ${skuSets.join(', ')} WHERE sku_code = $${skuParams.length}`,
|
||
skuParams
|
||
);
|
||
}
|
||
}
|
||
|
||
await client.query('COMMIT');
|
||
|
||
const result: UpdateInventoryBatchResult = {
|
||
id: String(row.id),
|
||
batch_no: String(row.batch_no),
|
||
sku_code: skuCode,
|
||
changed,
|
||
cost_recalc: costRecalc,
|
||
};
|
||
|
||
// 审计(提交后写,失败不回滚主流程)
|
||
try {
|
||
/**
|
||
* 「修改后」快照:提交后按同一组字段名重读一遍(含商品档案),
|
||
* 使 操作日志 能对**每个改动字段**渲染 `前 → 后`(含由 生产日期+保质期 推导的效期,
|
||
* 它不在请求体里,光看 input 是拿不到的)。
|
||
*/
|
||
let afterAudit: Record<string, unknown> = {};
|
||
try {
|
||
const afterRow = await client.query(
|
||
`SELECT i.batch_no, i.sku_code, s.sku_name,
|
||
i.storage_zone, i.shelf_life, i.expiry_date, i.production_date, i.cost_price,
|
||
s.category_code, s.spec, s.unit, s.origin
|
||
FROM inventory i
|
||
LEFT JOIN skus s ON s.sku_code = i.sku_code
|
||
WHERE i.id = $1::uuid
|
||
LIMIT 1`,
|
||
[result.id]
|
||
);
|
||
const a = afterRow.rows[0] || {};
|
||
afterAudit = {
|
||
batch_no: a.batch_no == null ? null : String(a.batch_no),
|
||
sku_code: a.sku_code == null ? null : String(a.sku_code),
|
||
sku_name: a.sku_name == null ? null : String(a.sku_name),
|
||
storage_zone: a.storage_zone == null ? null : String(a.storage_zone),
|
||
shelf_life: a.shelf_life == null ? null : String(a.shelf_life),
|
||
expiry_date: a.expiry_date == null ? null : toDateOnly(a.expiry_date),
|
||
production_date: a.production_date == null ? null : toDateOnly(a.production_date),
|
||
cost_price: a.cost_price == null ? null : Number(a.cost_price),
|
||
category_code: a.category_code == null ? null : String(a.category_code),
|
||
spec: a.spec == null ? null : String(a.spec),
|
||
unit: a.unit == null ? null : String(a.unit),
|
||
origin: a.origin == null ? null : String(a.origin),
|
||
};
|
||
} catch (afterError) {
|
||
console.error('[inventoryBatchEdit] after-snapshot failed (审计仍写):', afterError);
|
||
}
|
||
|
||
await writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'inventory_batch_edit',
|
||
targetTable: 'inventory',
|
||
targetId: result.id,
|
||
// 身份(商品/批次)+ 批次级前值 + 商品档案前值 ⇒ "改的是谁、改前是什么"
|
||
oldValue: {
|
||
batch_no: String(row.batch_no || ''),
|
||
sku_code: skuCode,
|
||
...beforeBatch,
|
||
...(beforeProductAudit || {}),
|
||
},
|
||
// 请求体(camelCase)+ 同名列的"修改后"快照 + 改动清单 ⇒ "改成什么、改了什么"
|
||
newValue: { ...input, ...afterAudit, changed, cost_recalc: costRecalc },
|
||
branchCode,
|
||
actionCategory: 'inventory',
|
||
});
|
||
} catch (auditError) {
|
||
console.error('[inventoryBatchEdit] writeAuditLog failed:', auditError);
|
||
}
|
||
|
||
return result;
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|