From 33f2f7b75aa0553f1a963b6b48491432c06e3732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9B=A8=E5=A4=A9?= Date: Tue, 13 Oct 2026 13:42:03 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=BA=93=E5=AD=98):=20=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E6=94=B9=E5=BD=95=E4=BF=9D=E8=B4=A8=E6=9C=9F?= =?UTF-8?q?=EF=BC=8C=E6=9C=89=E6=95=88=E6=9C=9F=E7=94=B1=E7=94=9F=E4=BA=A7?= =?UTF-8?q?=E6=97=A5=E6=9C=9F+=E4=BF=9D=E8=B4=A8=E6=9C=9F=E6=B4=BE?= =?UTF-8?q?=E7=94=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 inventory.shelf_life VARCHAR(32)(迁移 20261042,遍历 public/tenant_template/所有 tenant_*),存保质期原文(7天/6个月/1年)。 库存管理「修改」不再手填有效期:只要动了保质期或生产日期,就用 deriveExpiryDate 重算 expiry_date(推不出则清空)。解析与推算提到 server/src/utils/shelfLife.ts 与入库链路共用(月=30天、年=360天)。 入库链路(batchStockInboundRows)随行落 shelf_life 原文(原先算完即弃);列表行映射补 shelf_life;弹窗字段与三语文案同步。不做历史回填。 --- ...1028-库存管理修改弹窗扩展批次与商品属性.md | 22 +++++ migrations/20261042_inventory_shelf_life.sql | 67 +++++++++++++ .../workflow/routes/inventoryRoutes.ts | 2 +- .../src/services/inventoryBatchEditService.ts | 47 ++++++--- server/src/services/inventoryQueryService.ts | 2 + .../src/services/stockInboundBatchService.ts | 57 +---------- server/src/services/stockInboundService.ts | 16 ++- server/src/utils/shelfLife.ts | 71 +++++++++++++ server/tests/inventoryShelfLife.test.ts | 99 +++++++++++++++++++ src/i18n/locales/en/inventory.ts | 2 + src/i18n/locales/id/inventory.ts | 2 + src/i18n/locales/zh-CN/inventory.ts | 2 + src/pages/inventory/InventoryManagement.tsx | 19 ++-- src/utils/workflowApi.ts | 5 +- 14 files changed, 330 insertions(+), 83 deletions(-) create mode 100644 migrations/20261042_inventory_shelf_life.sql create mode 100644 server/src/utils/shelfLife.ts create mode 100644 server/tests/inventoryShelfLife.test.ts diff --git a/docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md b/docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md index 749d259..02f3a30 100644 --- a/docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md +++ b/docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md @@ -82,3 +82,25 @@ - **库存管理冻结**:未改 `adjust` 语义;新增的是独立的属性编辑通道,仅写审计、不写数量流水。 - **商品主数据冻结**:以 `product_catalog` 为写入源,未加反向触发器;`origin` 因列不在真源而直写 `skus`(与既有档案回写先例一致)。 - **财务冻结**:成本价按 A 口径——**不触账**;如需回冲需另立财务流程。 + +## 7. 口径变更(2026-10-14,开发者指令):**手填「有效期」→ 手填「保质期」,有效期由生产日期+保质期推算** + +> 开发者原话:「修改的应该是保质期 而不是有效期」「保质期可能是年月日(三种单位),存储的应该是一个字符串然后解析」。 + +**取代 §3.1 表格中「有效期 `expiry_date` | 批次 | `inventory.expiry_date`」与 §3.4「有效期格式 `YYYY-MM-DD`,空串 → `NULL`」两条手填口径。** + +| 项 | 变更后 | +|---|---| +| 弹窗字段 | 「有效期」日期输入 ⇒ **「保质期」文本输入**(`7天`/`6个月`/`1年`);生产日期保留;**有效期不再手填** | +| 存储 | 新增 **`inventory.shelf_life VARCHAR(32)`**(保质期**原文**,历史批次为空)—— 迁移 `migrations/20261042_inventory_shelf_life.sql`(遍历 public + tenant_template + 所有 tenant_* schema) | +| 派生 | 只要这一轮动了 `shelf_life` 或 `production_date`,服务端就用 `deriveExpiryDate(生产日期, 保质期)` **重算 `expiry_date`**(推不出则清空)。共用实现:`server/src/utils/shelfLife.ts`(与入库链路同一套,月=30 天、年=360 天) | +| 接口 | `POST /workflow/inventory/batch-update` 入参 `expiry_date` ⇒ **`shelf_life`**(`inventoryBatchEditService`) | +| 入库链路 | `batchStockInboundRows` 原先只拿 `shelf_life` 算有效期、**原文丢弃** ⇒ 现在随行落 `inventory.shelf_life`(`stockInboundService.writeStockImportRow`) | +| 列表 | `listInventoryForManagement` 行映射补 `shelf_life`(`SELECT inv.*` 已含该列) | +| 文案 | 新增 `inventory.adjust.shelfLife` / `inventory.adjust.shelfLifePh`(中/英/印尼) | + +**边界(有意不做)**: + +- **不做历史回填**(回填会改 FIFO 排序语义,属库存冻结面;且原文无法从 `expiry_date` 反推)。 +- **验收入库 / 独立入库不动**(现在不录保质期)。 +- 没有 `production_date` 或保质期解析不出 ⇒ **不写 `expiry_date`**(沿用入库口径,不瞎写)。 diff --git a/migrations/20261042_inventory_shelf_life.sql b/migrations/20261042_inventory_shelf_life.sql new file mode 100644 index 0000000..198a2d1 --- /dev/null +++ b/migrations/20261042_inventory_shelf_life.sql @@ -0,0 +1,67 @@ +-- 库存批次「保质期原文」列(字符串)+ 有效期口径变更(2026-10-14) +-- +-- 背景:保质期可能是「7天」「6个月」「1年」等**原文**,单位有 天/月/年 三种; +-- 有效期不再由人直接填,而是由「生产日期 + 保质期原文」推算(见 server/src/utils/shelfLife.ts)。 +-- 故批次上要能**存原文**,才能在「库存管理 → 修改」弹窗回显、并在生产日期变化时重算有效期。 +-- +-- 落点:`inventory.shelf_life`(可空,历史批次为空)。`inventory` 是**每租户一张表**, +-- 故遍历 public + tenant_template + 所有 tenant_* schema 逐库加列(沿用 +-- migrations/20261028_warehouse_storage_zone.sql 的写法)。 +-- 注:legacy_public 为归档 schema,沿用既有做法跳过。 +-- +-- 不做历史回填(回填会改 FIFO 排序语义,属库存冻结面;且「保质期」不是能从 expiry_date 反推的原文)。 +-- +-- 设计:docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md(「口径变更」节) + +-- ============================================================ +-- 1) 加列(遍历所有 schema) +-- ============================================================ +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT nspname + FROM pg_namespace + WHERE nspname IN ('public', 'tenant_template') + OR nspname LIKE 'tenant_%' + ORDER BY CASE nspname + WHEN 'public' THEN 0 + WHEN 'tenant_template' THEN 1 + ELSE 2 + END, nspname + LOOP + IF to_regclass(format('%I.inventory', sch)) IS NOT NULL THEN + EXECUTE format( + 'ALTER TABLE %I.inventory ADD COLUMN IF NOT EXISTS shelf_life VARCHAR(32)', + sch + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.inventory.shelf_life IS %L', + sch, + '批次保质期原文(如 7天/6个月/1年;单位 天/月/年)。可空;有效期 expiry_date 由 生产日期+保质期 推算' + ); + END IF; + END LOOP; +END $$; + +-- ============================================================ +-- 2) 响亮失败守卫:public / tenant_template 的 inventory 上必须有该列 +-- ============================================================ +DO $$ +BEGIN + IF to_regclass('public.inventory') IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'inventory' AND column_name = 'shelf_life' + ) THEN + RAISE EXCEPTION '迁移未生效:public.inventory.shelf_life 不存在'; + END IF; + IF to_regclass('tenant_template.inventory') IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'tenant_template' AND table_name = 'inventory' AND column_name = 'shelf_life' + ) THEN + RAISE EXCEPTION '迁移未生效:tenant_template.inventory.shelf_life 不存在'; + END IF; +END $$; diff --git a/server/src/modules/workflow/routes/inventoryRoutes.ts b/server/src/modules/workflow/routes/inventoryRoutes.ts index c9d7310..f4445ce 100644 --- a/server/src/modules/workflow/routes/inventoryRoutes.ts +++ b/server/src/modules/workflow/routes/inventoryRoutes.ts @@ -435,7 +435,7 @@ export function mountInventoryWorkflowRoutes(router: Router): void { operatorId: req.userId || null, remark: String(body.remark || ''), storageZone: 'storage_zone' in body ? body.storage_zone : undefined, - expiryDate: 'expiry_date' in body ? body.expiry_date : undefined, + shelfLife: 'shelf_life' in body ? body.shelf_life : undefined, productionDate: 'production_date' in body ? body.production_date : undefined, costPrice: 'cost_price' in body ? body.cost_price : undefined, categoryCode: 'category_code' in body ? body.category_code : undefined, diff --git a/server/src/services/inventoryBatchEditService.ts b/server/src/services/inventoryBatchEditService.ts index a9826e7..ecb3297 100644 --- a/server/src/services/inventoryBatchEditService.ts +++ b/server/src/services/inventoryBatchEditService.ts @@ -4,7 +4,9 @@ * 设计:docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md * * 口径: - * - **批次级**(只影响这一批):`storage_zone` / `expiry_date` / `cost_price`(写 `inventory`)。 + * - **批次级**(只影响这一批):`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` 的档案回写)。 @@ -14,6 +16,7 @@ */ import { pool } from '../db'; import { writeAuditLog } from './auditService'; +import { deriveExpiryDate } from '../utils/shelfLife'; function trimText(v: unknown): string { return String(v ?? '').trim(); @@ -51,8 +54,8 @@ export interface UpdateInventoryBatchInput { remark: string; /** 批次级;`undefined` = 不改 */ storageZone?: string | null; - /** 批次级:'YYYY-MM-DD' 或 ''(清空) */ - expiryDate?: string | null; + /** 批次级:保质期原文(如 `7天`/`6个月`/`1年`)或 ''(清空);由它 + 生产日期推算有效期 */ + shelfLife?: string | null; /** 批次级:'YYYY-MM-DD' 或 ''(清空);不参与 FIFO/成本/预留 */ productionDate?: string | null; /** 批次级:数字或 null(清空) */ @@ -92,7 +95,7 @@ export async function updateInventoryBatchAttributes( await client.query('BEGIN'); const locked = await client.query( - `SELECT id, batch_no, sku_code, storage_zone, expiry_date, production_date, cost_price + `SELECT id, batch_no, sku_code, storage_zone, shelf_life, expiry_date, production_date, cost_price FROM inventory WHERE id = $1::uuid AND branch_code = $2 FOR UPDATE`, @@ -108,6 +111,7 @@ export async function updateInventoryBatchAttributes( 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), @@ -115,10 +119,18 @@ export async function updateInventoryBatchAttributes( const changed: string[] = []; - // ── 批次级 ────────────────────────────────────────────── + // ── 批次级 ──────────────────────────────────────── 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) { @@ -127,22 +139,29 @@ export async function updateInventoryBatchAttributes( 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.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) { - const next = normalizeDateOrNull(input.productionDate); - if ((beforeBatch.production_date || null) !== next) { - batchParams.push(next); + 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'); + } + } if (input.costPrice !== undefined) { const raw = input.costPrice; const next = raw == null || trimText(raw) === '' ? null : Number(raw); diff --git a/server/src/services/inventoryQueryService.ts b/server/src/services/inventoryQueryService.ts index 6b33884..9437b47 100644 --- a/server/src/services/inventoryQueryService.ts +++ b/server/src/services/inventoryQueryService.ts @@ -321,6 +321,8 @@ export async function listInventoryForManagement( /** 日期列统一出 'YYYY-MM-DD':pg 的 date 返回本地午夜 Date,直接 JSON 化会差一天 */ production_date: toDateOnlyText(item.production_date), expiry_date: toDateOnlyText(item.expiry_date), + /** 保质期原文(如 7天/6个月/1年);有效期由「生产日期+保质期」推算 */ + shelf_life: item.shelf_life == null ? null : String(item.shelf_life), /** 是否存在已确认的入库批次报告关联(供列表标注「缺少批次报告」) */ has_batch_report: item.has_batch_report === true, }; diff --git a/server/src/services/stockInboundBatchService.ts b/server/src/services/stockInboundBatchService.ts index ea0b81a..4c9bba1 100644 --- a/server/src/services/stockInboundBatchService.ts +++ b/server/src/services/stockInboundBatchService.ts @@ -21,6 +21,7 @@ import { type StockImportRowInput, type StockImportRowResult, } from './stockInboundService'; +import { normalizeRecognizedDate } from '../utils/shelfLife'; export interface InboundLineBackfill { unit: string | null; @@ -124,59 +125,6 @@ function normalizeKey(value: unknown): string { return trimText(value).toLowerCase().replace(/\s+/g, ''); } -function toYmd(d: Date): string { - const pad = (n: number) => String(n).padStart(2, '0'); - return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; -} - -/** 识别出的日期归一为 YYYY-MM-DD;只有年月时补 01;否则 null */ -function normalizeRecognizedDate(value: unknown): string | null { - const t = trimText(value); - if (!t) return null; - const full = t.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/); - if (full) { - return `${full[1]}-${full[2].padStart(2, '0')}-${full[3].padStart(2, '0')}`; - } - const ym = t.match(/^(\d{4})[-/.](\d{1,2})$/); - if (ym) return `${ym[1]}-${ym[2].padStart(2, '0')}-01`; - return null; -} - -/** 保质期原文 → 天数/月数/年数(支持「7天」「180天」「6个月」「1年」) */ -function parseShelfLife(text: string): { unit: 'day' | 'month' | 'year'; n: number } | null { - const m = text.match(/(\d+)\s*(天|日|个月|月|年)/); - if (!m) return null; - const n = Number(m[1]); - if (!Number.isFinite(n) || n <= 0) return null; - const u = m[2]; - if (u === '天' || u === '日') return { unit: 'day', n }; - if (u === '个月' || u === '月') return { unit: 'month', n }; - return { unit: 'year', n }; -} - -/** 由「生产日期 + 保质期」推算有效期(expiry_date);推不出则 null(不写) */ -function deriveExpiryDate(productionDate: string | null, shelfLife: string | null): string | null { - const shelf = trimText(shelfLife); - if (!shelf) return null; - const absShelf = normalizeRecognizedDate(shelf); - // 有些标签直接印截止日期;若保质期本身是个完整日期,直接用 - if (absShelf && /^\d{4}-\d{2}-\d{2}$/.test(absShelf) && /\d{4}[-/.]\d{1,2}[-/.]\d{1,2}/.test(shelf)) { - return absShelf; - } - const baseYmd = normalizeRecognizedDate(productionDate); - if (!baseYmd) return null; - const parsed = parseShelfLife(shelf); - if (!parsed) return null; - const base = new Date(`${baseYmd}T00:00:00`); - if (Number.isNaN(base.getTime())) return null; - const d = new Date(base.getTime()); - // 统一按「天」推进:1 个月 = 30 天、1 年 = 360 天 - if (parsed.unit === 'day') d.setDate(d.getDate() + parsed.n); - else if (parsed.unit === 'month') d.setDate(d.getDate() + parsed.n * 30); - else d.setDate(d.getDate() + parsed.n * 360); - return toYmd(d); -} - function parseItemsJson(raw: string | null): { kind: 'document' | 'goods' | 'none'; items: unknown[] } { const text = trimText(raw); if (!text) return { kind: 'none', items: [] }; @@ -702,7 +650,8 @@ export async function batchStockInboundRows(input: { qty, unitCost: toNumOrNull(row.unit_cost), productionDate, - expiryDate: deriveExpiryDate(productionDate, row.shelf_life ?? null), + // 保质期原文随行落库(`inventory.shelf_life`);有效期在 writeStockImportRow 里由它推算 + shelfLife: trimText(row.shelf_life) || null, storageZone, }); } diff --git a/server/src/services/stockInboundService.ts b/server/src/services/stockInboundService.ts index 8d50af7..f1ea5fa 100644 --- a/server/src/services/stockInboundService.ts +++ b/server/src/services/stockInboundService.ts @@ -12,6 +12,7 @@ import { upsertInventoryHoldingCost } from './inventorySurplusCostService'; import { resolveStockMode } from './stockModeService'; import { createIndependentInboundInspection } from './independentInboundService'; import { assertBranchAllowsProductCatalog } from './platformBranch'; +import { deriveExpiryDate } from '../utils/shelfLife'; type Db = Pick; @@ -382,7 +383,10 @@ export interface StockImportRowInput { /** 可空:给了且已存在 → 累加该批次;否则新建批次 */ batchNo?: string | null; productionDate?: string | null; + /** 有效期(可空):显式给了就用;未给且给了 shelfLife 时由「生产日期+保质期」推算 */ expiryDate?: string | null; + /** 保质期原文(如「7天」「6个月」「1年」);落 inventory.shelf_life 并参与推算有效期 */ + shelfLife?: string | null; storageZone?: string | null; } @@ -528,25 +532,29 @@ async function writeStockImportRow( const batchNo = trimText(row.batchNo) || newStockBatchNo(); const productionDate = normalizeProductionDate(row.productionDate); - const expiryDate = normalizeProductionDate(row.expiryDate); + const shelfLife = trimText(row.shelfLife) || null; + // 有效期:显式给了用给的;否则由「生产日期 + 保质期原文」推算(推不出保持 null,不瞎写) + const expiryDate = + normalizeProductionDate(row.expiryDate) || deriveExpiryDate(productionDate, shelfLife); 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 + production_date, expiry_date, storage_zone, shelf_life ) VALUES ($1, $2, $3, $3, NULL, $4, 10, $5, - COALESCE($6::date, (NOW() AT TIME ZONE 'Asia/Shanghai')::date), $7::date, $8) + COALESCE($6::date, (NOW() AT TIME ZONE 'Asia/Shanghai')::date), $7::date, $8, $9) 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), + shelf_life = COALESCE(EXCLUDED.shelf_life, inventory.shelf_life), status = 10 RETURNING id::text AS id, available_qty, (xmax = 0) AS inserted`, - [batchNo, skuCode, qty, unitCost, branchCode, productionDate, expiryDate, storageZone] + [batchNo, skuCode, qty, unitCost, branchCode, productionDate, expiryDate, storageZone, shelfLife] ); const inventoryId = String(up.rows[0]?.id || ''); const afterQty = Number(up.rows[0]?.available_qty) || qty; diff --git a/server/src/utils/shelfLife.ts b/server/src/utils/shelfLife.ts new file mode 100644 index 0000000..1a3aa41 --- /dev/null +++ b/server/src/utils/shelfLife.ts @@ -0,0 +1,71 @@ +/** + * 保质期原文 → 有效期(`inventory.expiry_date`)的**共用口径**。 + * + * 背景(开发者口径):保质期以**字符串原文**存储(`inventory.shelf_life`),单位可能是 + * 天 / 月 / 年(如「7天」「6个月」「1年」);有效期**一律由「生产日期 + 保质期」推算**, + * 不再让人直接填一个日期(库存管理「修改」弹窗与入库链路同一套)。 + * + * ⚠️ 换算口径:**月按 30 天、年按 360 天**推进(不是日历月/年)—— 沿用入库链路既有口径。 + * ⚠️ 推不出(生产日期缺失 / 保质期识别不出)**返回 null** —— 调用方不得瞎写日期。 + */ + +function trimText(value: unknown): string { + return String(value ?? '').trim(); +} + +function toYmd(d: Date): string { + const pad = (n: number) => String(n).padStart(2, '0'); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; +} + +/** 识别出的日期归一为 YYYY-MM-DD;只有年月时补 01;否则 null */ +export function normalizeRecognizedDate(value: unknown): string | null { + const t = trimText(value); + if (!t) return null; + const full = t.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/); + if (full) { + return `${full[1]}-${full[2].padStart(2, '0')}-${full[3].padStart(2, '0')}`; + } + const ym = t.match(/^(\d{4})[-/.](\d{1,2})$/); + if (ym) return `${ym[1]}-${ym[2].padStart(2, '0')}-01`; + return null; +} + +/** 保质期原文 → 单位与数量(支持「7天」「180天」「6个月」「1年」);识别不出返回 null */ +export function parseShelfLife(text: unknown): { unit: 'day' | 'month' | 'year'; n: number } | null { + const m = trimText(text).match(/(\d+)\s*(天|日|个月|月|年)/); + if (!m) return null; + const n = Number(m[1]); + if (!Number.isFinite(n) || n <= 0) return null; + const u = m[2]; + if (u === '天' || u === '日') return { unit: 'day', n }; + if (u === '个月' || u === '月') return { unit: 'month', n }; + return { unit: 'year', n }; +} + +/** + * 由「生产日期 + 保质期原文」推算有效期(`YYYY-MM-DD`);推不出返回 null。 + * + * - 保质期本身是个**完整日期**时(有些标签直接印截止日)⇒ 直接用它; + * - 否则 = 生产日期 + 保质期(天/月/年,月=30天、年=360天); + * - 生产日期缺失或保质期识别不出 ⇒ null(**不写**)。 + */ +export function deriveExpiryDate(productionDate: unknown, shelfLife: unknown): string | null { + const shelf = trimText(shelfLife); + if (!shelf) return null; + const absShelf = normalizeRecognizedDate(shelf); + if (absShelf && /^\d{4}-\d{2}-\d{2}$/.test(absShelf) && /\d{4}[-/.]\d{1,2}[-/.]\d{1,2}/.test(shelf)) { + return absShelf; + } + const baseYmd = normalizeRecognizedDate(productionDate); + if (!baseYmd) return null; + const parsed = parseShelfLife(shelf); + if (!parsed) return null; + const base = new Date(`${baseYmd}T00:00:00`); + if (Number.isNaN(base.getTime())) return null; + const d = new Date(base.getTime()); + if (parsed.unit === 'day') d.setDate(d.getDate() + parsed.n); + else if (parsed.unit === 'month') d.setDate(d.getDate() + parsed.n * 30); + else d.setDate(d.getDate() + parsed.n * 360); + return toYmd(d); +} diff --git a/server/tests/inventoryShelfLife.test.ts b/server/tests/inventoryShelfLife.test.ts new file mode 100644 index 0000000..ca76aae --- /dev/null +++ b/server/tests/inventoryShelfLife.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { + deriveExpiryDate, + normalizeRecognizedDate, + parseShelfLife, +} from '../src/utils/shelfLife'; + +/** + * 保质期「存原文 + 解析推算有效期」的口径(2026-10-14 开发者指令): + * 「修改的应该是保质期 而不是有效期」「保质期可能是年月日(三种单位),存储的应该是一个字符串然后解析」。 + * + * 钉住四件事: + * ① 解析支持 天 / 月 / 年;② 月 = 30 天、年 = 360 天;③ 推不出返回 null(不瞎写); + * ④ 库存管理「修改」弹窗把手填「有效期」换成「保质期」,有效期由服务端派生。 + */ +const batchEditSrc = readFileSync( + new URL('../src/services/inventoryBatchEditService.ts', import.meta.url), + 'utf8' +); +const routeSrc = readFileSync( + new URL('../src/modules/workflow/routes/inventoryRoutes.ts', import.meta.url), + 'utf8' +); +const inboundSrc = readFileSync( + new URL('../src/services/stockInboundService.ts', import.meta.url), + 'utf8' +); +const migrationSrc = readFileSync( + new URL('../../migrations/20261042_inventory_shelf_life.sql', import.meta.url), + 'utf8' +); +const modalSrc = readFileSync( + new URL('../../src/pages/inventory/InventoryManagement.tsx', import.meta.url), + 'utf8' +); + +describe('保质期解析与有效期推算', () => { + it('parseShelfLife:天 / 月 / 年 三种单位(含带前缀文案)', () => { + expect(parseShelfLife('7天')).toEqual({ unit: 'day', n: 7 }); + expect(parseShelfLife('180日')).toEqual({ unit: 'day', n: 180 }); + expect(parseShelfLife('6个月')).toEqual({ unit: 'month', n: 6 }); + expect(parseShelfLife('1年')).toEqual({ unit: 'year', n: 1 }); + expect(parseShelfLife('常温12个月')).toEqual({ unit: 'month', n: 12 }); + expect(parseShelfLife('')).toBeNull(); + expect(parseShelfLife('新鲜')).toBeNull(); + }); + + it('deriveExpiryDate:生产日期 + 保质期(月=30 天、年=360 天)', () => { + expect(deriveExpiryDate('2026-01-01', '30天')).toBe('2026-01-31'); + expect(deriveExpiryDate('2026-01-01', '6个月')).toBe('2026-06-30'); + expect(deriveExpiryDate('2026-01-01', '1年')).toBe('2026-12-27'); + }); + + it('deriveExpiryDate:保质期本身是截止日期 ⇒ 直接用;推不出 ⇒ null(不瞎写)', () => { + expect(deriveExpiryDate(null, '2026-03-01')).toBe('2026-03-01'); + expect(deriveExpiryDate('2026-01-01', '')).toBeNull(); + expect(deriveExpiryDate(null, '7天')).toBeNull(); + expect(deriveExpiryDate('2026-01-01', '新鲜')).toBeNull(); + }); + + it('normalizeRecognizedDate:只有年月补 01', () => { + expect(normalizeRecognizedDate('2026-03')).toBe('2026-03-01'); + expect(normalizeRecognizedDate('2026-03-05')).toBe('2026-03-05'); + expect(normalizeRecognizedDate('')).toBeNull(); + }); +}); + +describe('库存管理「修改」:存保质期原文 + 有效期派生(源码契约)', () => { + it('服务层:收 shelf_life、不再收手填 expiryDate,并用 deriveExpiryDate 重算', () => { + expect(batchEditSrc).toContain('shelfLife?: string | null;'); + expect(batchEditSrc).not.toContain('expiryDate?: string | null;'); + expect(batchEditSrc).toContain('deriveExpiryDate(nextProductionDate, nextShelfLife)'); + expect(batchEditSrc).toMatch(/shelf_life = \$/); + }); + + it('路由:入参由 expiry_date 改为 shelf_life', () => { + expect(routeSrc).toContain("shelfLife: 'shelf_life' in body ? body.shelf_life : undefined,"); + expect(routeSrc).not.toContain("expiryDate: 'expiry_date' in body"); + }); + + it('入库链路:保质期原文随行落库(writeStockImportRow 写 shelf_life)', () => { + expect(inboundSrc).toContain('shelfLife?: string | null;'); + expect(inboundSrc).toContain('deriveExpiryDate(productionDate, shelfLife)'); + expect(inboundSrc).toContain('shelf_life'); + }); + + it('迁移:所有 schema 加 inventory.shelf_life 列 + 响亮失败守卫', () => { + expect(migrationSrc).toContain('ADD COLUMN IF NOT EXISTS shelf_life VARCHAR(32)'); + expect(migrationSrc).toContain('tenant_template'); + expect(migrationSrc).toContain('RAISE EXCEPTION'); + }); + + it('弹窗:字段换成「保质期」,不再手填有效期', () => { + expect(modalSrc).toContain("t('inventory.adjust.shelfLife')"); + expect(modalSrc).not.toContain("t('inventory.adjust.expiry')"); + expect(modalSrc).toContain('payload.shelf_life = adjustShelfLife;'); + }); +}); diff --git a/src/i18n/locales/en/inventory.ts b/src/i18n/locales/en/inventory.ts index 55d6ed1..dd92b56 100644 --- a/src/i18n/locales/en/inventory.ts +++ b/src/i18n/locales/en/inventory.ts @@ -152,6 +152,8 @@ export const inventory: MessageDict = { 'adjust.zoneCreate': '+ Use this zone', 'adjust.zoneCreateNamed': '+ Use zone "{name}"', 'adjust.expiry': 'Expiry date', + 'adjust.shelfLife': 'Shelf life', + 'adjust.shelfLifePh': 'e.g. 7 days / 6 months / 1 year', 'adjust.productionDate': 'Production date', 'adjust.cost': 'Cost price', 'adjust.productSection': 'Product profile (affects all batches of this product)', diff --git a/src/i18n/locales/id/inventory.ts b/src/i18n/locales/id/inventory.ts index cf657da..78476ef 100644 --- a/src/i18n/locales/id/inventory.ts +++ b/src/i18n/locales/id/inventory.ts @@ -156,6 +156,8 @@ export const inventory: MessageDict = { 'adjust.zoneCreate': '+ Pakai zona ini', 'adjust.zoneCreateNamed': '+ Pakai zona "{name}"', 'adjust.expiry': 'Tanggal kedaluwarsa', + 'adjust.shelfLife': 'Masa simpan', + 'adjust.shelfLifePh': 'mis. 7 hari / 6 bulan / 1 tahun', 'adjust.productionDate': 'Tanggal produksi', 'adjust.cost': 'Harga pokok', 'adjust.productSection': 'Profil produk (berlaku semua batch produk ini)', diff --git a/src/i18n/locales/zh-CN/inventory.ts b/src/i18n/locales/zh-CN/inventory.ts index 96ec676..40c5cb0 100644 --- a/src/i18n/locales/zh-CN/inventory.ts +++ b/src/i18n/locales/zh-CN/inventory.ts @@ -151,6 +151,8 @@ export const inventory: MessageDict = { 'adjust.zoneCreate': '+ 使用该区域', 'adjust.zoneCreateNamed': '+ 使用区域「{name}」', 'adjust.expiry': '有效期', + 'adjust.shelfLife': '保质期', + 'adjust.shelfLifePh': '如 7天 / 6个月 / 1年', 'adjust.productionDate': '生产日期', 'adjust.cost': '成本价', 'adjust.productSection': '商品档案(影响该商品所有批次)', diff --git a/src/pages/inventory/InventoryManagement.tsx b/src/pages/inventory/InventoryManagement.tsx index adda884..80da648 100644 --- a/src/pages/inventory/InventoryManagement.tsx +++ b/src/pages/inventory/InventoryManagement.tsx @@ -159,6 +159,7 @@ interface InventoryItem { batch_attribution_ok?: boolean; production_date?: string; expiry_date?: string; + shelf_life?: string; supplier_code?: string; supplier_name?: string; storage_zone?: string; @@ -227,7 +228,7 @@ export const InventoryManagement: React.FC = () => { const [adjustRemark, setAdjustRemark] = useState(''); const [adjustSaving, setAdjustSaving] = useState(false); const [adjustStorageZone, setAdjustStorageZone] = useState(''); - const [adjustExpiry, setAdjustExpiry] = useState(''); + const [adjustShelfLife, setAdjustShelfLife] = useState(''); const [adjustProductionDate, setAdjustProductionDate] = useState(''); const [adjustCost, setAdjustCost] = useState(''); const [adjustCategoryCode, setAdjustCategoryCode] = useState(''); @@ -355,7 +356,7 @@ export const InventoryManagement: React.FC = () => { setAdjustQty(String(item.available_qty ?? 0)); setAdjustRemark(''); setAdjustStorageZone(item.storage_zone || ''); - setAdjustExpiry(item.expiry_date ? String(item.expiry_date).slice(0, 10) : ''); + setAdjustShelfLife(item.shelf_life || ''); setAdjustProductionDate(item.production_date ? String(item.production_date).slice(0, 10) : ''); setAdjustCost(item.cost_price != null ? String(item.cost_price) : ''); setAdjustCategoryCode(item.category_code || ''); @@ -370,6 +371,7 @@ export const InventoryManagement: React.FC = () => { setAdjustQty(''); setAdjustRemark(''); setAdjustProductionDate(''); + setAdjustShelfLife(''); }; // 分类 / 单位 选项(供修改弹窗选择) @@ -485,7 +487,7 @@ export const InventoryManagement: React.FC = () => { const branch = operatingBranchCode || readOperatingBranchCode(); const beforeZone = adjustItem.storage_zone || ''; - const beforeExpiry = adjustItem.expiry_date ? String(adjustItem.expiry_date).slice(0, 10) : ''; + const beforeShelfLife = adjustItem.shelf_life || ''; const beforeProdDate = adjustItem.production_date ? String(adjustItem.production_date).slice(0, 10) : ''; @@ -497,7 +499,7 @@ export const InventoryManagement: React.FC = () => { const payload: UpdateInventoryBatchPayload = {}; if (adjustStorageZone !== beforeZone) payload.storage_zone = adjustStorageZone; - if (adjustExpiry !== beforeExpiry) payload.expiry_date = adjustExpiry; + if (adjustShelfLife !== beforeShelfLife) payload.shelf_life = adjustShelfLife; if (adjustProductionDate !== beforeProdDate) payload.production_date = adjustProductionDate; if (adjustCost !== beforeCost) payload.cost_price = adjustCost.trim() === '' ? null : Number(adjustCost); if (adjustCategoryCode !== beforeCategory) payload.category_code = adjustCategoryCode; @@ -1805,11 +1807,12 @@ export const InventoryManagement: React.FC = () => { />
- + setAdjustExpiry(e.target.value)} + type="text" + value={adjustShelfLife} + onChange={(e) => setAdjustShelfLife(e.target.value)} + placeholder={t('inventory.adjust.shelfLifePh')} className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none" />
diff --git a/src/utils/workflowApi.ts b/src/utils/workflowApi.ts index 6a139f7..b746116 100644 --- a/src/utils/workflowApi.ts +++ b/src/utils/workflowApi.ts @@ -3307,7 +3307,8 @@ export async function adjustInventoryAvailableApi(input: { /** 库存管理「修改」:批次属性 + 商品档案字段(数量走 adjustInventoryAvailableApi) */ export interface UpdateInventoryBatchPayload { storage_zone?: string; - expiry_date?: string; + /** 保质期原文(如 7天/6个月/1年);有效期由 生产日期+保质期 在服务端推算 */ + shelf_life?: string; production_date?: string; cost_price?: number | null; category_code?: string; @@ -3330,7 +3331,7 @@ export async function updateInventoryBatchApi(input: { remark: input.remark, operating_branch_code: input.operatingBranchCode || undefined, ...(input.storage_zone !== undefined ? { storage_zone: input.storage_zone } : {}), - ...(input.expiry_date !== undefined ? { expiry_date: input.expiry_date } : {}), + ...(input.shelf_life !== undefined ? { shelf_life: input.shelf_life } : {}), ...(input.production_date !== undefined ? { production_date: input.production_date } : {}), ...(input.cost_price !== undefined ? { cost_price: input.cost_price } : {}), ...(input.category_code !== undefined ? { category_code: input.category_code } : {}),