From 06589ecd487afc26f703b471fc013dcd6cb5ff6f Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Sun, 11 Oct 2026 14:22:37 +0800 Subject: [PATCH] =?UTF-8?q?refactor(=E5=BA=93=E5=AD=98=E5=85=A5=E5=BA=93):?= =?UTF-8?q?=20=E5=95=86=E5=93=81=E9=80=89=E6=8B=A9=E5=BD=92=E4=BD=8D?= =?UTF-8?q?=E5=88=B0=E3=80=8C=E5=93=81=E5=90=8D=E3=80=8D=E6=A0=BC=20+=20?= =?UTF-8?q?=E5=AD=98=E6=94=BE=E5=8C=BA=E5=9F=9F=E6=94=B9=E5=8C=BA=E5=9F=9F?= =?UTF-8?q?=E9=80=89=E6=8B=A9=EF=BC=88=E5=BC=80=E5=8F=91=E8=80=85=E6=8C=87?= =?UTF-8?q?=E6=AD=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 开发者指正(原话):「商品选择应该是放到这里 **品名的选择这里面**,然后存放区域就是一个**区域选择(支持新增区域)**。」 改动: · **「品名」格 = 商品选择器**(复用 SearchableSelect + 远程检索 sku-options,300ms 防抖): 选中已有商品 ⇒ 写 sku_code/item_name 并按**只补空**规则带出上次设置; 直接输入文字(下拉「新建「x」」)⇒ 仍是"待新建商品",与手动加一行/拍照未命中同一口径。 · **删除上一轮单独加的「选择已有商品」控件**(含其 i18n key `stockIn.pickExisting`,三语一并清理)。 · **「存放区域」格 = 区域选择器**:新增只读接口 `GET /inventory/storage-zones`(**复用既有 `listStorageZones()`**,与移动端同名接口同源);区域是自由文本、无独立表 ⇒ **新增区域 = 输入新值**, 该批入库落库后自动进候选,不需要建表/建接口。 · 文案:本轮**零新增**(复用 phName / phZone / createNamed 三个既有 key)。 口径保持:**数量与生产日期一律不被预填触碰**(预填函数体里根本没有这两个键,源码级单测钉死); 成本价/区域/保质期/产地**只补空**,不覆盖操作员已填。 验证: · 前端 8/8(预填规则 + 两字段不被触碰 + 品名/区域两格接线 + 旧控件已移除)、服务端 10/10 (选品接口、区域接口、limit 上限、无分公司不查库、路由权限与 SQL 归属) · 前后端 tsc 均通过 · **端到端实测**(真账号 token + 真库):`GET /inventory/sku-options?search=抄手` ⇒ 200 命中抄手皮; `GET /inventory/storage-zones` ⇒ 200 `{"data":[]}`(本系统尚无区域,首次入库后自动出现) · **运行实例已生效**:两个路由从 404 → 401(已注册待鉴权);3021 的库存 chunk 里 `listInventoryStorageZonesApi`/`pickSkuForLine`/`zoneOptions` 均在,`addLineFromSku` = 0(旧控件已移除) · 回归:前端 734 用例失败 2(另一条工作线遗留的 SystemConfig.allowZeroCost); 服务端 2378 用例失败 33/25 文件 = 基线 24 文件 + zeroCostClearsPlanPrice; weighInspectionMergeSimilar 的 2–3 条波动是**既有**问题(它读的设计文档在本 fork 不存在 + 5s 超时在负载下 flaky), 非本次引入(已在 srv19 之前就红) · 门禁同基线(8 通过 / check-ai-cost 有意为红 / verify-facts 未执行) --- ...11-入库直接选择已有商品并按上次设置预填.md | 60 ++++--- .../workflow/routes/inventoryRoutes.ts | 19 +++ server/tests/inventorySkuOptions.test.ts | 36 +++- src/i18n/locales/en/inventory.ts | 1 - src/i18n/locales/id/inventory.ts | 1 - src/i18n/locales/zh-CN/inventory.ts | 1 - src/pages/inventory/StockInboundPanel.tsx | 155 +++++++++++------- src/utils/inboundSkuPrefill.test.ts | 148 +++++++++-------- src/utils/inboundSkuPrefill.ts | 30 +--- src/utils/workflowApi.ts | 7 +- 10 files changed, 257 insertions(+), 201 deletions(-) diff --git a/docs/design/20261011-入库直接选择已有商品并按上次设置预填.md b/docs/design/20261011-入库直接选择已有商品并按上次设置预填.md index 861778e..5c43855 100644 --- a/docs/design/20261011-入库直接选择已有商品并按上次设置预填.md +++ b/docs/design/20261011-入库直接选择已有商品并按上次设置预填.md @@ -39,9 +39,9 @@ ## 3. 设计 -### 3.1 服务端:一个只读接口(复用既有回填,不新增口径) +### 3.1 服务端:两个只读接口(复用既有实现,不新增口径) -`GET /workflow/inventory/sku-options?search=&limit=`,权限与识别接口一致(`inventory_manage` 或 `inspection_manage`)。 +**① 选品**:`GET /workflow/inventory/sku-options?search=&limit=`,权限与识别接口一致(`inventory_manage` 或 `inspection_manage`)。 返回:`[{ sku_code, sku_name, spec, brand, unit, origin, category_code, category_name, backfill }]` @@ -50,47 +50,59 @@ - SQL 全部落在 service(`stockInboundBatchService.listInboundSkuOptions`),路由层只做参数与权限 —— `server/tests/routeLayerBoundary.test.ts` 的钉子(路由文件不许写 SQL)。 -### 3.2 前端:一个入口 + 复用回填 +**② 存放区域候选**:`GET /workflow/inventory/storage-zones`(同权限),**直接复用既有 `listStorageZones()`** +(`inventory.storage_zone` 去重,上限 200)—— 移动端早有同名接口,本轮只是给 Web 补上; +区域是自由文本、**无独立表** ⇒ 不需要"新建区域"接口:首次入库填的新值落库后自然出现在候选里。 -- **入口**:待审核区「+ 添加一行」旁边放一个搜索选择器(复用 `SearchableSelect`),选中即追加一行; -- **新行赋值**:`sku_code` / `item_name = sku_name` / `spec` / `unit` 来自商品; - `unit_cost` / `category_code+name` / `shelf_life` / `storage_zone` / `origin` 来自 `backfill`; - **`production_date` 显式留空**; -- **复用 `applyMatchedFields`**:选品与拍照命中走**同一份**预填规则,避免两条路径两套口径漂移。 +### 3.2 前端:选择放进「品名」格 + 区域改成区域选择(2026-10-11 开发者归位) -### 3.3 生产日期为什么必须留空 +- **「品名」格 = 商品选择器**(复用 `SearchableSelect`,远程检索 `sku-options`,输入 300ms 防抖): + - 选中已有商品 ⇒ 该行写入 `sku_code` / `item_name`,并按**只补空**规则带出上次设置; + - **直接输入文字**(下拉里「新建「x」」)⇒ `item_name = 输入值`、`sku_code = ''`,与「手动加一行 / 拍照未命中」同一口径(不新建商品档案,仍走提交时的 `new_product`); +- **「存放区域」格 = 区域选择器**:候选来自 `GET /inventory/storage-zones`(`inventory.storage_zone` 去重);区域是**自由文本、无独立表** ⇒ 「新增区域」= 输入新值即可,**该批入库落库后自动进入候选**,不需要建表/建接口; +- **复用 `applyMatchedFields`(= `applyInboundBackfill`)**:选品与拍照命中走**同一份**预填规则,避免两条路径两套口径漂移; +- 文案:**全部复用既有 key**(`phName`/`phZone`/`createNamed`),本轮未新增任何文案。 -同一商品每批生产日期不同,带出上次日期极易被忽略而记错批次。因此**只留空、不新增强制校验**(见非目标 ②): -页面上该字段空白可见,提交后仍可在库存管理「修改」里更正。 +### 3.3 生产日期与数量:预填一律不碰 + +同一商品每批生产日期不同,带出上次日期极易被忽略而记错批次;数量同理(每批数量必然不同)。 +因此**预填函数根本不写这两个字段**(源码级单测钉住:函数体里没有 `production_date` / `qty`), +且**不新增强制校验**(见非目标 ②)。 ## 4. 验收标准(编码后逐条实测) -- [ ] 选中商品后:规格/单位/分类/成本价/保质期/存放区域/生产地区 = 该商品**上次设置**值(无历史则留空); -- [ ] **生产日期恒为空**(即使该商品有历史生产日期也不带出); -- [ ] 选品搜索按编码/名称模糊匹配;无 `inventory_manage`/`inspection_manage` 时 403; -- [ ] 拍照识别路径行为**不变**(回归); -- [ ] 回归守卫:前端单测(预填映射 + 生产日期不带出)、服务端单测(接口形状/搜索/权限/回填复用)。 +- [x] 行内选中商品后:规格/单位 = 商品档案;成本价/分类/保质期/存放区域/生产地区 = 该商品**上次设置**(无历史则留空); +- [x] **数量与生产日期原地不动**(操作员已填的值不被预填覆盖;未填则保持为空); +- [x] 品名格可**直接输入文字**(不选商品)⇒ 该行按待新建商品提交,能力与改造前一致; +- [x] 存放区域为**区域选择**:候选来自既有区域,且可**输入新增**(落库后进候选); +- [x] 选品搜索按编码/名称模糊匹配;无 `inventory_manage`/`inspection_manage` 时 403; +- [x] 拍照识别路径行为**不变**(回归); +- [x] 回归守卫:前端单测(预填规则 + 数量/生产日期不被触碰 + 两格接线)、服务端单测(选品接口 / 区域接口 / 权限 / 回填复用)。 ## 5. 风险与回滚 | 风险 | 处置 | |---|---| -| 预填了不合适/过期的成本价 | 只取"上一次入库行"的值;字段可改;本功能**不写库存**,真正写入仍走既有批量入库 | -| 生产日期被误带出 | 赋值处显式留空 + 单测钉死(§4 第二条) | -| 两条录入路径口径漂移 | 复用 `applyMatchedFields` 与 `loadInboundBackfill`,不复制算法 | -| 回滚 | 前端去掉入口 + 后端下线接口即可:无迁移、无数据写入、无兼容负担 | +| 预填了不合适/过期的成本价 | 只取"上一次入库行"的值;**只补空**(已填的不覆盖);字段可改;本功能**不写库存** | +| 生产日期/数量被误带出 | 预填函数不写这两个字段 + 源码级单测(§4 第二条) | +| 两条录入路径口径漂移 | 复用同一份 `applyInboundBackfill` 与 `loadInboundBackfill`,不复制算法 | +| 品名格改为选择器后"打不出新商品名" | 保留自由输入 ⇒ 直接输入文字即待新建商品(护栏单测 ③) | +| 回滚 | 前端把两格还原成普通输入框、后端下线两个只读接口即可:无迁移、无数据写入 | ## 6. 已裁决(2026-10-11,开发者逐项选择) | # | 问题 | 裁决 | 落地 | |---|---|---|---| -| A | 「数量」是否带出上次值 | **不带出,留空由操作员填**(每次入库数量必然不同,带出容易被忽略而多记/少记) | 前端 `prefillFromSkuOption` 返回结构里**没有 qty**;单测钉死 | -| B | 入口按钮/占位文案 | **「选择已有商品」** | i18n `inventory.stockIn.pickExisting`(zh/en/id 三语同步);未新增其它任何文案 | -| C | 生产日期是否提交强制必填 | **不加强制,只留空**(与既有全部录入路径口径一致;不新增报错文案) | 新行 `production_date: ''`;后端仍无必填校验 | +| A | 「数量」是否带出上次值 | **不带出,留空由操作员填**(每次入库数量必然不同,带出容易被忽略而多记/少记) | 预填函数不写 `qty`;单测钉死 | +| B | 入口位置与文案 | **不单独放入口**:开发者归位为「**商品选择放到品名的选择这里面**」⇒ 品名格即选品器(占位沿用 `phName`,未新增文案) | `StockInboundPanel` 品名格 = `SearchableSelect` + `pickSkuForLine` | +| C | 生产日期是否提交强制必填 | **不加强制,只留空**(与既有全部录入路径口径一致;不新增报错文案) | 预填不写;后端仍无必填校验 | +| D | 存放区域 | 「**就是一个区域选择(支持新增区域)**」 | 新增只读接口 `GET /inventory/storage-zones`(复用 `listStorageZones`);格内可输入新增 | ## 7. 修订记录 | 版本 | 日期 | 变更 | |---|---|---| | v1 | 2026-10-11 | 首版设计(含三项待裁决) | -| v2 | 2026-10-11 | 三项已裁决(§6)并落地;补实测:真库 `listInboundSkuOptions(BR003)` 检索到 4 个商品、关键词「抄手」命中 1 个、无入库历史时回填全空 | +| v2 | 2026-10-11 | 三项已裁决(§6 A/B/C)并落地;补实测:真库 `listInboundSkuOptions(BR003)` 检索到 4 个商品、关键词「抄手」命中 1 个、无入库历史时回填全空 | +| v3 | 2026-10-11 | **UI 归位(开发者)**:商品选择移入「品名」格(不再单独控件)、「存放区域」改为区域选择且支持新增(新增接口 `storage-zones`);预填改为**只补空**语义(不覆盖操作员已填);文案全复用既有 key;单测补接线与"两字段不被触碰"护栏 | + diff --git a/server/src/modules/workflow/routes/inventoryRoutes.ts b/server/src/modules/workflow/routes/inventoryRoutes.ts index 2e27099..20db78b 100644 --- a/server/src/modules/workflow/routes/inventoryRoutes.ts +++ b/server/src/modules/workflow/routes/inventoryRoutes.ts @@ -250,6 +250,25 @@ export function mountInventoryWorkflowRoutes(router: Router): void { } }); + /** + * 库存入库「存放区域」候选(2026-10-11):区域是**自由文本、无独立表** ⇒ 候选取自 + * `inventory.storage_zone` 去重值;「新增区域」不需要建表 —— 首次入库填的新值落库后即出现在候选里。 + * 权限与识别/选品接口一致。(移动端同名接口见 routes/mobile/mobileInventoryRoutes.ts) + */ + router.get('/inventory/storage-zones', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['inventory_manage', 'inspection_manage']); + const { listStorageZones } = await import('../../../services/stockInboundBatchService'); + return res.json({ data: await listStorageZones() }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载存放区域失败', + }); + } + }); + /** Web 库存入库:始终直接入库,不走验收、不受「独立入库验收」开关影响 */ router.post('/inventory/stock-in', authMiddleware, async (req: AuthRequest, res: Response) => { try { diff --git a/server/tests/inventorySkuOptions.test.ts b/server/tests/inventorySkuOptions.test.ts index 6022403..c2936bd 100644 --- a/server/tests/inventorySkuOptions.test.ts +++ b/server/tests/inventorySkuOptions.test.ts @@ -15,13 +15,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; * ⑤ 路由权限与识别接口一致(inventory_manage | inspection_manage),且 SQL 不在路由文件里。 */ const connect = vi.hoisted(() => vi.fn()); +const query = vi.hoisted(() => vi.fn()); vi.mock('../src/db', () => ({ - pool: { query: vi.fn(), connect: (...args: unknown[]) => connect(...args) }, - getRawPoolQuery: () => vi.fn(), + pool: { query: (...args: unknown[]) => query(...args), connect: (...args: unknown[]) => connect(...args) }, + getRawPoolQuery: () => query, })); -import { listInboundSkuOptions } from '../src/services/stockInboundBatchService'; +import { listInboundSkuOptions, listStorageZones } from '../src/services/stockInboundBatchService'; function makeClient() { const query = vi.fn(async (sql: string) => { @@ -68,6 +69,7 @@ function makeClient() { beforeEach(() => { connect.mockReset(); + query.mockReset(); }); describe('listInboundSkuOptions', () => { @@ -144,11 +146,12 @@ describe('listInboundSkuOptions', () => { }); }); +const routeSrc = readFileSync( + path.join(__dirname, '../src/modules/workflow/routes/inventoryRoutes.ts'), + 'utf8' +); + describe('路由接线(源码级)', () => { - const routeSrc = readFileSync( - path.join(__dirname, '../src/modules/workflow/routes/inventoryRoutes.ts'), - 'utf8' - ); it('⑤ 权限与识别接口一致:inventory_manage | inspection_manage', () => { const start = routeSrc.indexOf("router.get('/inventory/sku-options'"); @@ -164,3 +167,22 @@ describe('路由接线(源码级)', () => { expect(body).not.toMatch(/SELECT|FROM skus/i); }); }); + +describe('存放区域候选(区域是自由文本,无独立表)', () => { + it('listStorageZones 取既有区域去重(新增区域 = 首次入库落库后自动出现)', async () => { + query.mockResolvedValueOnce({ rows: [{ storage_zone: '冷库A' }, { storage_zone: '常温区' }] }); + await expect(listStorageZones()).resolves.toEqual(['冷库A', '常温区']); + const sql = String(query.mock.calls[0]?.[0] || ''); + expect(sql).toContain('DISTINCT storage_zone'); + expect(sql).toContain('FROM inventory'); + }); + + it('路由:/inventory/storage-zones 权限与识别/选品一致,SQL 不在路由文件里', () => { + const start = routeSrc.indexOf("router.get('/inventory/storage-zones'"); + expect(start, '路由必须存在').toBeGreaterThan(-1); + const body = routeSrc.slice(start, start + 600); + expect(body).toContain("requireWorkflowPermission(ctx, ['inventory_manage', 'inspection_manage'])"); + expect(body).toContain('listStorageZones'); + expect(body).not.toMatch(/SELECT|FROM inventory/i); + }); +}); diff --git a/src/i18n/locales/en/inventory.ts b/src/i18n/locales/en/inventory.ts index 7726fd5..63dc395 100644 --- a/src/i18n/locales/en/inventory.ts +++ b/src/i18n/locales/en/inventory.ts @@ -238,7 +238,6 @@ export const inventory: MessageDict = { 'stockIn.reviewSection': 'Recognized · review ({n})', 'stockIn.reviewEmpty': 'No items yet. Recognize images, or tap “Add a row” below.', 'stockIn.addLine': '+ Add a row', - 'stockIn.pickExisting': 'Choose an existing product', 'stockIn.badgeNew': 'To create', 'stockIn.badgeMatched': 'Matched', 'stockIn.phName': 'Name', diff --git a/src/i18n/locales/id/inventory.ts b/src/i18n/locales/id/inventory.ts index f2c2cf4..48e2373 100644 --- a/src/i18n/locales/id/inventory.ts +++ b/src/i18n/locales/id/inventory.ts @@ -245,7 +245,6 @@ export const inventory: MessageDict = { 'stockIn.reviewSection': 'Dikenali · tinjau ({n})', 'stockIn.reviewEmpty': 'Belum ada item. Kenali dulu, atau ketuk “Tambah baris” di bawah.', 'stockIn.addLine': '+ Tambah baris', - 'stockIn.pickExisting': 'Pilih produk yang ada', 'stockIn.badgeNew': 'Akan dibuat', 'stockIn.badgeMatched': 'Cocok', 'stockIn.phName': 'Nama', diff --git a/src/i18n/locales/zh-CN/inventory.ts b/src/i18n/locales/zh-CN/inventory.ts index e161ffb..feb5ba3 100644 --- a/src/i18n/locales/zh-CN/inventory.ts +++ b/src/i18n/locales/zh-CN/inventory.ts @@ -238,7 +238,6 @@ export const inventory: MessageDict = { 'stockIn.reviewSection': '识别结果 · 待审核({n})', 'stockIn.reviewEmpty': '还没有商品:可先识别,或点下方「手动加一行」。', 'stockIn.addLine': '+ 手动加一行', - 'stockIn.pickExisting': '选择已有商品', 'stockIn.badgeNew': '待新建', 'stockIn.badgeMatched': '已匹配', 'stockIn.phName': '品名', diff --git a/src/pages/inventory/StockInboundPanel.tsx b/src/pages/inventory/StockInboundPanel.tsx index 2b04e8b..e59bbd7 100644 --- a/src/pages/inventory/StockInboundPanel.tsx +++ b/src/pages/inventory/StockInboundPanel.tsx @@ -14,6 +14,7 @@ import { useFileDropUpload } from '../../hooks/useFileDropUpload'; import { createInventoryCategoryApi, listInventorySkuOptionsApi, + listInventoryStorageZonesApi, listUnitsApi, recognizeInventoryLinesApi, submitInventoryStockInBatchApi, @@ -23,7 +24,7 @@ import { type InventoryInboundRecognizedLine, type InventoryInboundSkuOption, } from '../../utils/workflowApi'; -import { applyInboundBackfill, prefillFromSkuOption } from '../../utils/inboundSkuPrefill'; +import { applyInboundBackfill } from '../../utils/inboundSkuPrefill'; import { useT } from '../../i18n'; import { SearchableSelect } from '../../components/ui/SearchableSelect'; @@ -144,7 +145,8 @@ export const StockInboundPanel: React.FC = () => { const [unitChoices, setUnitChoices] = useState([]); /** 「选择已有商品」的检索结果(远程搜索,见 fetchSkuOptions) */ const [skuOptions, setSkuOptions] = useState([]); - const [skuOptionsLoading, setSkuOptionsLoading] = useState(false); + /** 「存放区域」候选(区域是自由文本:首次入库用了新值,下次就会出现在这里) */ + const [zoneChoices, setZoneChoices] = useState([]); const recognizeInputRef = useRef(null); const recognizeDropRef = useRef(null); @@ -184,6 +186,26 @@ export const StockInboundPanel: React.FC = () => { }; }, []); + // 存放区域候选(只读、失败即空:不阻塞入库) + useEffect(() => { + let cancelled = false; + void listInventoryStorageZonesApi() + .then((res) => { + if (!cancelled) setZoneChoices((res.data || []).filter(Boolean)); + }) + .catch(() => { + if (!cancelled) setZoneChoices([]); + }); + return () => { + cancelled = true; + }; + }, []); + + const zoneOptions = useMemo( + () => zoneChoices.map((z) => ({ value: z, label: z })), + [zoneChoices] + ); + const categoryOptions = useMemo( () => categories.map((c) => ({ @@ -196,14 +218,11 @@ export const StockInboundPanel: React.FC = () => { /** 「选择已有商品」:按关键词远程检索商品档案(带上次设置回填) */ const fetchSkuOptions = useCallback( async (search = '') => { - setSkuOptionsLoading(true); try { const res = await listInventorySkuOptionsApi(search, 20); setSkuOptions(res.data || []); } catch (e: any) { notify.error(e?.message || t('inventory.stockIn.similarFail')); - } finally { - setSkuOptionsLoading(false); } }, [t] @@ -344,34 +363,28 @@ export const StockInboundPanel: React.FC = () => { }; /** - * 「选择已有商品」:选中即追加一行 —— 规格/单位取商品档案,成本价/分类/保质期/存放区域/生产地区取 - * **该商品上次设置**(无历史则留空);**数量与生产日期一律留空**(数量每次不同、生产日期每批不同)。 + * 行内「品名」格选中已有商品:规格/单位取商品档案;成本价/分类/保质期/存放区域/生产地区按 + * **只补空**规则取该商品**上次设置**(操作员已填的不被覆盖);**数量与生产日期不动** + * (数量每次不同、生产日期每批不同,由操作员按本批填)。 */ - const addLineFromSku = (skuCode: string) => { + const pickSkuForLine = (line: InboundLine, skuCode: string) => { const option = skuOptions.find((o) => o.sku_code === skuCode); if (!option) return; - const prefill = prefillFromSkuOption(option); - setLines((prev) => [ - ...prev, - { - id: lineId(), - qty: '', - production_date: '', - candidates: [], - item_name: prefill.item_name, - spec: prefill.spec, - unit: prefill.unit, - unit_cost: prefill.unit_cost, - sku_code: prefill.sku_code, - category_code: prefill.category_code, - category_name: prefill.category_name, - shelf_life: prefill.shelf_life, - storage_zone: prefill.storage_zone, - origin: prefill.origin, - }, - ]); - // 选完即恢复成"搜索框"形态,方便连续加多个商品 - setSkuOptions([]); + const next: InboundLine = { ...line, sku_code: option.sku_code, item_name: option.sku_name }; + applyInboundBackfill( + next, + { spec: option.spec, unit: option.unit || option.backfill?.unit || '' }, + option.backfill ?? null + ); + updateLine(line.id, next); + }; + + /** 品名格输入自由文本 ⇒ 该行按「待新建商品」处理(与手动加一行/拍照未命中同一口径) */ + const onLineNameQuery = (line: InboundLine, query: string) => { + onSkuQueryChange(query); + const name = query.trim(); + if (!name) return; + updateLine(line.id, { item_name: query }); }; /** 行内「新建分类」:建好后自动选中该行 */ @@ -593,11 +606,37 @@ export const StockInboundPanel: React.FC = () => {
- ({ + value: o.sku_code, + label: o.spec ? `${o.sku_name} · ${o.spec}` : o.sku_name, + searchText: o.sku_code, + }))} + onChange={(code) => { + if (code) pickSkuForLine(line, code); + }} + onQueryChange={(q) => onLineNameQuery(line, q)} + onOpenChange={(open) => { + if (open) void fetchSkuOptions(''); + }} placeholder={t('inventory.stockIn.phName')} - value={line.item_name} - onChange={(e) => updateLine(line.id, { item_name: e.target.value })} + allowEmpty + emptyLabel={t('inventory.stockIn.phName')} + allowCreateFromQuery + alwaysShowCreate + createFromQueryLabel={(q) => + q.trim() ? t('inventory.stockIn.createNamed', { name: q }) : t('inventory.stockIn.phName') + } + onCreateFromQuery={(q) => updateLine(line.id, { item_name: q, sku_code: '' })} + hideSearchIcon + compact + portal + portalZIndex={10200} /> { value={line.shelf_life} onChange={(e) => updateLine(line.id, { shelf_life: e.target.value })} /> - updateLine(line.id, { storage_zone: e.target.value })} + fallbackLabel={line.storage_zone} + options={zoneOptions} + onChange={(zone) => updateLine(line.id, { storage_zone: zone })} + placeholder={t('inventory.stockIn.phZone')} + allowEmpty + emptyLabel={t('inventory.stockIn.phZone')} + allowCreateFromQuery + alwaysShowCreate + createFromQueryLabel={(q) => + q.trim() ? t('inventory.stockIn.createNamed', { name: q }) : t('inventory.stockIn.phZone') + } + onCreateFromQuery={(q) => updateLine(line.id, { storage_zone: q })} + hideSearchIcon + compact + portal + portalZIndex={10200} /> { {t('inventory.stockIn.addLine')} - {/* 直接选择已有商品:不拍照也能入库;带出上次设置,数量与生产日期留空由操作员填 */} - addLineFromSku(code)} - options={skuOptions.map((o) => ({ - value: o.sku_code, - label: o.spec ? `${o.sku_name} · ${o.spec}` : o.sku_name, - searchText: o.sku_code, - }))} - placeholder={t('inventory.stockIn.pickExisting')} - allowEmpty - emptyLabel={t('inventory.stockIn.pickExisting')} - disabled={skuOptionsLoading} - onQueryChange={onSkuQueryChange} - onOpenChange={(open) => { - if (open) void fetchSkuOptions(''); - }} - hideSearchIcon - compact - portal - portalZIndex={10200} - />
{/* 确认入库 */} diff --git a/src/utils/inboundSkuPrefill.test.ts b/src/utils/inboundSkuPrefill.test.ts index a227f16..5291048 100644 --- a/src/utils/inboundSkuPrefill.test.ts +++ b/src/utils/inboundSkuPrefill.test.ts @@ -1,20 +1,18 @@ +import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { - applyInboundBackfill, - prefillFromSkuOption, - type InboundSkuOption, -} from './inboundSkuPrefill'; +import { applyInboundBackfill } from './inboundSkuPrefill'; import type { InventoryInboundLineBackfill } from './workflowApi'; /** - * 库存入库「选择已有商品 → 按上次设置预填」(开发者 2026-10-11): - * 「这个商品之前设置过 规格/单位/成本价/分类/保质期/存放区域/生产地区 就携带上,方便快速输入, - * **但是生产日期需要其自己再次填写**,因为同一个商品生产日期肯定是不一样的。」 + * 库存入库「选已有商品 → 带出上次设置」(开发者 2026-10-11,UI 归位版): + * 「商品选择应该是放到这里 **品名的选择这里面**,然后存放区域就是一个**区域选择(支持新增区域)**。」 * - * 钉住两条硬规则 + 一处"空才回填"语义: - * ① 生产日期**永远不带出**; - * ② 数量**永远不带出**(开发者裁决:留空由操作员填); - * ③ 操作员已填/已改的字段不被"上次设置"覆盖(规格/单位以商品档案为准除外)。 + * 于是: + * · 「品名」格 = 商品选择器(输入即搜已有商品;选中 → 带出上次设置;直接输入文字 → 待新建商品); + * · 「存放区域」格 = 区域选择器(候选 = 既有区域;输入没有的即新增,落库后自动进候选); + * · **生产日期不带出**(同商品每批不同);**数量也不带出**(开发者裁决)。 + * + * 本文件钉住:① 预填规则本身;② 数量/生产日期**不被预填触碰**;③ 两格确实接上了对应接口。 */ const backfill: InventoryInboundLineBackfill = { unit: '箱', @@ -27,20 +25,13 @@ const backfill: InventoryInboundLineBackfill = { last_inbound_at: '20261001120000', }; -const option: InboundSkuOption = { - sku_code: 'SKU001', - sku_name: '土豆', - spec: '5kg/箱', - brand: '某某', - unit: '箱', - origin: '山东', - category_code: 'CAT-VEG', - category_name: '蔬菜', - backfill, -}; +const panel = readFileSync(new URL('../pages/inventory/StockInboundPanel.tsx', import.meta.url), 'utf8'); -function emptyLine() { +/** 模拟一行:数量与生产日期已由操作员填好(选中商品时这两个值必须原地不动) */ +function lineWithOperatorInput() { return { + qty: '8', + production_date: '2026-10-11', spec: '', unit: '', unit_cost: '', @@ -52,73 +43,80 @@ function emptyLine() { }; } -describe('选择已有商品 → 预填上次设置', () => { +describe('选中商品 → 带出上次设置', () => { it('规格/单位取商品档案;成本价/分类/保质期/存放区域/生产地区取上次设置', () => { - const p = prefillFromSkuOption(option); - expect(p.sku_code).toBe('SKU001'); - expect(p.item_name).toBe('土豆'); - expect(p.spec).toBe('5kg/箱'); - expect(p.unit).toBe('箱'); - expect(p.unit_cost).toBe('12.5'); - expect(p.category_code).toBe('CAT-VEG'); - expect(p.category_name).toBe('蔬菜'); - expect(p.shelf_life).toBe('30天'); - expect(p.storage_zone).toBe('冷库A'); - expect(p.origin).toBe('山东'); + const line = lineWithOperatorInput(); + applyInboundBackfill(line, { spec: '5kg/箱', unit: '箱' }, backfill); + expect(line.spec).toBe('5kg/箱'); + expect(line.unit).toBe('箱'); + expect(line.unit_cost).toBe('12.5'); + expect(line.category_code).toBe('CAT-VEG'); + expect(line.category_name).toBe('蔬菜'); + expect(line.shelf_life).toBe('30天'); + expect(line.storage_zone).toBe('冷库A'); + expect(line.origin).toBe('山东'); }); - it('① 生产日期永不带出 —— 返回结构里根本没有这个字段', () => { - const p = prefillFromSkuOption(option) as unknown as Record; - expect('production_date' in p).toBe(false); - expect(Object.keys(p)).not.toContain('production_date'); + it('① 数量与生产日期**不被预填触碰**(操作员先填了数量/日期,选中商品后原地保留)', () => { + const line = lineWithOperatorInput(); + applyInboundBackfill(line, { spec: '5kg/箱', unit: '箱' }, backfill); + expect(line.qty).toBe('8'); + expect(line.production_date).toBe('2026-10-11'); }); - it('② 数量永不带出(开发者裁决:留空,避免多记/少记)', () => { - const p = prefillFromSkuOption(option) as unknown as Record; - expect('qty' in p).toBe(false); - expect('quantity' in p).toBe(false); + it('② 预填函数自身不写数量/生产日期字段(源码级:函数体里没有这两个键)', () => { + const util = readFileSync(new URL('./inboundSkuPrefill.ts', import.meta.url), 'utf8'); + const body = util.slice(util.indexOf('export function applyInboundBackfill')); + expect(body).not.toContain('production_date'); + expect(body).not.toContain('qty'); }); it('无入库历史(backfill 为空)⇒ 除商品自带规格/单位外全留空,不报错', () => { - const p = prefillFromSkuOption({ - ...option, - unit: null, - origin: null, - category_code: null, - category_name: null, - backfill: null, - }); - expect(p.spec).toBe('5kg/箱'); - expect(p.unit).toBe(''); - expect(p.unit_cost).toBe(''); - expect(p.category_code).toBe(''); - expect(p.shelf_life).toBe(''); - expect(p.storage_zone).toBe(''); - expect(p.origin).toBe(''); - }); - - it('option.unit 为空但回填里有单位 ⇒ 用回填的单位(不丢字段)', () => { - const p = prefillFromSkuOption({ ...option, unit: null }); - expect(p.unit).toBe('箱'); + const line = lineWithOperatorInput(); + applyInboundBackfill(line, { spec: '5kg/箱', unit: '' }, null); + expect(line.spec).toBe('5kg/箱'); + expect(line.unit).toBe(''); + expect(line.unit_cost).toBe(''); + expect(line.category_code).toBe(''); + expect(line.storage_zone).toBe(''); + expect(line.origin).toBe(''); }); }); -describe('预填规则:只补空,不覆盖已填', () => { +describe('预填规则:只补空,不覆盖操作员已填', () => { it('成本价/存放区域/保质期/生产地区:已有值不被上次设置覆盖', () => { - const line = { ...emptyLine(), unit_cost: '9.9', storage_zone: '常温区', shelf_life: '7天', origin: '本地' }; + const line = { + ...lineWithOperatorInput(), + unit_cost: '9.9', + storage_zone: '常温区', + shelf_life: '7天', + origin: '本地', + }; applyInboundBackfill(line, null, backfill); expect(line.unit_cost).toBe('9.9'); expect(line.storage_zone).toBe('常温区'); expect(line.shelf_life).toBe('7天'); expect(line.origin).toBe('本地'); - // 分类与规格/单位沿用既有口径(商品/回填为准) - expect(line.category_code).toBe('CAT-VEG'); - }); - - it('规格/单位以商品档案为准(与拍照识别命中商品同一口径)', () => { - const line = { ...emptyLine(), spec: '旧规格', unit: '旧单位' }; - applyInboundBackfill(line, { spec: '5kg/箱', unit: '箱' }, null); - expect(line.spec).toBe('5kg/箱'); - expect(line.unit).toBe('箱'); + expect(line.category_code).toBe('CAT-VEG'); // 分类沿用既有口径(商品/回填为准) + }); +}); + +describe('UI 接线:商品选择在「品名」格、存放区域是区域选择', () => { + it('③ 品名格是商品选择器:接 sku-options 接口 + 选中走 pickSkuForLine(且带"新建"出口)', () => { + expect(panel).toContain('listInventorySkuOptionsApi'); + expect(panel).toContain('pickSkuForLine'); + expect(panel).toContain("onCreateFromQuery={(q) => updateLine(line.id, { item_name: q, sku_code: '' })}"); + expect(panel).toContain('createFromQueryLabel'); + }); + + it('④ 存放区域格是区域选择器:接 storage-zones 接口 + 支持新增区域', () => { + expect(panel).toContain('listInventoryStorageZonesApi'); + expect(panel).toContain('zoneOptions'); + expect(panel).toContain('onCreateFromQuery={(q) => updateLine(line.id, { storage_zone: q })}'); + }); + + it('⑤ 独立选品控件已移除(选择归到品名格内);「手动加一行」仍保留', () => { + expect(panel).not.toContain('addLineFromSku'); + expect(panel).toContain("t('inventory.stockIn.addLine')"); }); }); diff --git a/src/utils/inboundSkuPrefill.ts b/src/utils/inboundSkuPrefill.ts index 85af5a5..3304b77 100644 --- a/src/utils/inboundSkuPrefill.ts +++ b/src/utils/inboundSkuPrefill.ts @@ -6,7 +6,7 @@ import type { InventoryInboundLineBackfill } from './workflowApi'; * 规格/单位/成本价/分类/保质期/存放区域/生产地区 就携带上,方便快速输入; * **但生产日期需要自己再次填写**,因为同一个商品每批生产日期肯定不一样。」 * - * 这里放**唯一一份**预填规则:拍照识别命中商品与"直接选已有商品"两条路径共用, + * 这里放**唯一一份**预填规则:拍照识别命中商品、行内「品名」格选中已有商品两条路径共用, * 避免两边各写一套而漂移。设计见 * docs/design/20261011-入库直接选择已有商品并按上次设置预填.md。 * @@ -74,31 +74,3 @@ export function applyInboundBackfill( } return line; } - -/** 选中已有商品后要写进新行的字段:**没有数量、没有生产日期**(见文件头两条硬规则) */ -export interface InboundSkuPrefill extends InboundPrefillTarget { - sku_code: string; - item_name: string; -} - -export function prefillFromSkuOption(option: InboundSkuOption): InboundSkuPrefill { - const base: InboundPrefillTarget = { - spec: '', - unit: '', - unit_cost: '', - category_code: '', - category_name: '', - shelf_life: '', - storage_zone: '', - origin: '', - }; - const spec = option.spec || ''; - const unit = option.unit || option.backfill?.unit || ''; - const filled = applyInboundBackfill(base, { spec, unit }, option.backfill ?? null); - // 返回结构里**没有** qty / production_date 字段 —— 类型层面即保证带不出来(调用方显式置空) - return { - sku_code: option.sku_code, - item_name: option.sku_name, - ...filled, - }; -} diff --git a/src/utils/workflowApi.ts b/src/utils/workflowApi.ts index b04b8e8..3f08319 100644 --- a/src/utils/workflowApi.ts +++ b/src/utils/workflowApi.ts @@ -3010,7 +3010,7 @@ export interface InventoryInboundSkuOption { backfill: InventoryInboundLineBackfill | null; } -/** Web 库存入库:按关键词检索商品档案(供「选择已有商品」用;权限与识别接口一致) */ +/** Web 库存入库:按关键词检索商品档案(供「品名」格内选品用;权限与识别接口一致) */ export async function listInventorySkuOptionsApi(search?: string, limit = 20) { const params = new URLSearchParams(); if (search) params.set('search', search); @@ -3020,6 +3020,11 @@ export async function listInventorySkuOptionsApi(search?: string, limit = 20) { ); } +/** Web 库存入库:既有存放区域候选(区域是自由文本;新增区域 = 首次使用并入库后自动出现在候选里) */ +export async function listInventoryStorageZonesApi() { + return workflowFetch<{ data: string[] }>('/inventory/storage-zones'); +} + /** Web 多商品识别(送货单/实物堆):多图一次调用 → 多行 + 匹配回填 */ export async function recognizeInventoryLinesApi(input: { images_base64: string[];