入库批次报告(独立表,隔离于 quality_reports): - 上传图/PDF → OCR → 按「商品名 + 生产日期」匹配入库批次 → 人工确认落关联 - 库存列表加「批次报告」列,缺报告时标红商品名;未命中可手动选批次 库存管理「修改」扩展:批次属性加「生产日期」;区域/有效期/成本价 + 商品档案(分类/规格/单位/产地) 独立入库:备注区分 Web/小程序;生产日期多格式容错;/units 空时回退模板字典 修复: - 库存列表日期差一天(date 出参统一 YYYY-MM-DD,避免回写日期逐次前移) - OCR 提示词不再把检验项目当品名
294 lines
10 KiB
TypeScript
294 lines
10 KiB
TypeScript
/**
|
||
* 库存管理「修改」——批次属性 + 商品档案字段编辑。
|
||
*
|
||
* 设计:docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md
|
||
*
|
||
* 口径:
|
||
* - **批次级**(只影响这一批):`storage_zone` / `expiry_date` / `cost_price`(写 `inventory`)。
|
||
* - **商品级**(影响该商品所有批次):`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';
|
||
|
||
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;
|
||
/** 批次级:'YYYY-MM-DD' 或 ''(清空) */
|
||
expiryDate?: string | null;
|
||
/** 批次级:'YYYY-MM-DD' 或 ''(清空);不参与 FIFO/成本/预留 */
|
||
productionDate?: string | null;
|
||
/** 批次级:数字或 null(清空) */
|
||
costPrice?: number | 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[];
|
||
}
|
||
|
||
export async function updateInventoryBatchAttributes(
|
||
input: UpdateInventoryBatchInput
|
||
): Promise<UpdateInventoryBatchResult> {
|
||
const inventoryId = trimText(input.inventoryId);
|
||
const branchCode = trimText(input.branchCode);
|
||
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' });
|
||
}
|
||
if (!remark) {
|
||
throw Object.assign(new Error('请填写修改备注'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
|
||
const locked = await client.query(
|
||
`SELECT id, batch_no, sku_code, storage_zone, expiry_date, production_date, cost_price
|
||
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),
|
||
expiry_date: toDateOnly(row.expiry_date),
|
||
production_date: toDateOnly(row.production_date),
|
||
cost_price: row.cost_price == null ? null : Number(row.cost_price),
|
||
};
|
||
|
||
const changed: string[] = [];
|
||
|
||
// ── 批次级 ──────────────────────────────────────────────
|
||
const batchSets: string[] = [];
|
||
const batchParams: unknown[] = [];
|
||
|
||
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.expiryDate !== undefined) {
|
||
const next = normalizeDateOrNull(input.expiryDate);
|
||
if ((beforeBatch.expiry_date || null) !== next) {
|
||
batchParams.push(next);
|
||
batchSets.push(`expiry_date = $${batchParams.length}::date`);
|
||
changed.push('expiry_date');
|
||
}
|
||
}
|
||
if (input.productionDate !== undefined) {
|
||
const next = normalizeDateOrNull(input.productionDate);
|
||
if ((beforeBatch.production_date || null) !== next) {
|
||
batchParams.push(next);
|
||
batchSets.push(`production_date = $${batchParams.length}::date`);
|
||
changed.push('production_date');
|
||
}
|
||
}
|
||
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');
|
||
}
|
||
}
|
||
if (batchSets.length) {
|
||
batchParams.push(inventoryId);
|
||
await client.query(
|
||
`UPDATE inventory SET ${batchSets.join(', ')} WHERE id = $${batchParams.length}::uuid`,
|
||
batchParams
|
||
);
|
||
}
|
||
|
||
// ── 商品级 ──────────────────────────────────────────────
|
||
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),
|
||
};
|
||
|
||
// 分类 / 规格 / 单位 → 写商品真源 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,
|
||
};
|
||
|
||
// 审计(提交后写,失败不回滚主流程)
|
||
try {
|
||
await writeAuditLog({
|
||
operatorId: input.operatorId || null,
|
||
operationType: 'inventory_batch_edit',
|
||
targetTable: 'inventory',
|
||
targetId: result.id,
|
||
oldValue: { ...beforeBatch },
|
||
newValue: { ...input, changed },
|
||
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();
|
||
}
|
||
}
|