diff --git a/docs/design/20261016-订单入库批量上传批次报告并落生产日期.md b/docs/design/20261016-订单入库批量上传批次报告并落生产日期.md new file mode 100644 index 0000000..4b01a2e --- /dev/null +++ b/docs/design/20261016-订单入库批量上传批次报告并落生产日期.md @@ -0,0 +1,160 @@ +# 订单入库:一键上传批次报告 → 提取生产日期 → 随入库落库 + +> 2026-10-16 · 开发者需求(原话):「一键全部合格入库的下方加一个按钮 一键上传批次报告,支持多张, +> 根据商品名进行匹配,匹配到后我们的批次报告中应该是存在生产日期的,就记录下来,入库时一起携带着, +> 这样我们的商品就存在批次报告与生产时间了」。 +> +> 逐项确认(2026-10-16):① 上传=拍照/相册(多张),**微信里能选到的 PDF 也要支持**;② 按**当前列表待验收行的商品名**匹配,一般只有一个品名; +> ④ 匹配档位=精确直接给、疑似给提示、未命中不填;⑤ **流程=上传匹配后把日期展示出来,人核对/修改,没问题关闭,然后照旧「合格入库」**(AI 只提取、人来终确认); +> ⑨ 订单入库侧的**管理员/仓管都可以**;⑪ 降级与报告落库参考**库存入库/Web 报告**的既有做法。 +> +> **状态:已实现**(2026-10-16,开发者确认「执行」)——实现清单与验证见 §10。含 §4 的关键变更(验收普通行生产日期由“今天”改为真实日期)。 + +## 0. 一句话 + +在订单入库页「一键全部合格入库」**下方**加「**一键上传批次报告**」:选多张报告(图/PDF)→ OCR 抽出**商品名 + 生产日期** → +按商品名匹配**当前待验收行** → **弹一张核对表**把日期显示出来(可改)→ 关掉后照旧「合格入库」⇒ +**生产日期随该行进 `inventory.production_date`**,报告**挂到入库后那一批**上。 + +## 1. 目标 / 非目标 + +**目标** + +1. 小程序订单入库页新增入口,支持**多张图 / PDF** 一次性上传; +2. 复用既有 OCR(`quality.report.meta`)抽 **品名一览 + 生产日期**; +3. 按**商品名**匹配当前**待验收行**;把报告的**生产日期**落到该行; +4. **入库时把该日期写进 `inventory.production_date`**,并把该报告**关联到新建的库存批次**; +5. 「人核对 → 关闭 → 合格入库」的短流程;AI 只提取、人工可改。 + +**非目标** + +1. **不新增任何闸门**(不做"报告不齐不许入库"); +2. **不碰 `quality_reports`**(会进验收「报告齐全」硬闸的覆盖计算,`product-freeze` 点名); +3. **不推主系统**(沿用 `20261029` 的"本期不推"边界); +4. 不改库存列表/看板的取数口径;不新增文案之外的小字(本次仅新增按钮与核对表字段名,**先在本文登记,编码前另行确认措辞**)。 + +## 2. 改前实测事实(先立事实) + +| # | 事实 | 证据 | +|---|---|---| +| F1 | 小程序订单入库**没有**任何批次报告入口;页内是任务卡(拍照/实收/结果/存放区域)+ 底部「一键全部合格入库」 | `miniprogram/components/inspection-panel/*`;`submitAllEligible`(`:959`) | +| F2 | 后端**已有一套「入库批次报告」**:`inventoryBatchReportService.ts`(AI-29)——**图/PDF → OCR → 品名一览 + `produced_at`(生产日期) + 检测机构**;提示词 `quality.report.meta`(已登记);表 `inventory_batch_reports` / `inventory_batch_report_matches`(迁移 `20261033`);**只在 Web 有入口**(`/inventory/batch-reports`,需 `inventory_manage`) | 该服务 `createInventoryBatchReports` / `getInventoryBatchReport` / `confirmInventoryBatchReportMatches`;`inventoryRoutes.ts:462/488/512/539` | +| F3 | **验收本来就写 `inventory.production_date`**:`INSERT INTO inventory (… production_date …) VALUES (… COALESCE($8::date, (NOW() AT TIME ZONE 'Asia/Shanghai')::date) …)`;`$8` 只由 **`production_date_month`(预包装)**推出「YYYY-MM-01」,**普通行 = null ⇒ 落"今天"** | `inspectionComplianceService.ts:1613`(取值)+`:1650`(INSERT) | +| F4 | 移动端 `POST /mobile/inspection/complete` 只映射 `production_date_month`(无逐行生产日期) | `mobileWarehouseRoutes.ts:217/265` | +| F5 | 小程序**已有**往 `quality-reports` 桶上传的能力(供应商报告上传在用) | `miniprogram/utils/request.js:382`(`/storage/quality-reports/upload`) | +| F6 | 验收链路**不写 `expiry_date`**(效期不在此推算);(与「库存入库」链路不同,那条会由 生产日期+保质期 推算) | 同 F3 的 INSERT 未含 `expiry_date` | + +## 3. 设计 + +### 3.1 小程序 UI + +- **按钮**:`inspection-panel` 底部操作区,在「一键全部合格入库」**下方**新增「**一键上传批次报告**」(同宽、次级样式,避免抢主按钮)。 +- **选择**:`wx.chooseMedia`(拍照/相册、多选);PDF 走 `wx.chooseMessageFile`(微信里能从聊天选到 PDF)。每次最多 N 张(建议 9,与既有拍照一致)。 +- **上传+解析**:逐张上传到 `quality-reports` 桶(复用 F5),再调**新增的 mobile 端点**(§3.3)→ 返回每份报告 `{report_id, product_names, produced_at}`。 +- **核对表(弹层)**:列出 `报告 → 品名 → 匹配到的待验收行 → 生产日期`,其中: + - 生产日期**可编辑**(AI 只提取、人来改); + - 精确命中给「已匹配」,疑似给「疑似」标记,未命中给「未匹配该商品」(**不填**,可手选行); + - 底部「**确定**」= 采用(写入各行状态)/「取消」= 丢弃本次。 +- **之后**:照旧点「一键全部合格入库」或逐行「确认入库」(§3.4)。 + +### 3.2 匹配口径 + +- 归一化商品名(去空格/全半角括号等,复用既有 `normalizeName` 口径)后比较; +- 精确相等 ⇒ `unique`;包含/别名 ⇒ `fuzzy`(疑似);都不中 ⇒ `none`; +- **一份报告一般只有一个品名**(开发者口径);若 OCR 出多个品名 ⇒ 逐个匹配、共用该报告的 `produced_at`(逐品名可各自改)。 + +### 3.3 服务端 + +| 层 | 内容 | +| --- | --- | +| mobile 路由 | `POST /mobile/inspection/batch-reports`(`requireStockInboundRole` 或等价仓管/检验守卫):body `{ files: string[] }`(已上传对象路径)→ **复用 `createInventoryBatchReports`**(不改其口径:不写 inventory、不碰 quality_reports)→ 返回 `[{report_id, product_names, produced_at, ai_parsed}]` | +| 入库 | `POST /mobile/inspection/complete` 每行新增可选 `production_date`(`YYYY-MM-DD`)与 `batch_report_id`(uuid);`inspectionComplianceService`:`productionDate` 取值改为 **`production_date`(逐行,优先)→ `production_date_month`(预包装)→ null(仍兜底今天)**;**入库成功后**若带 `batch_report_id` ⇒ 调既有 `confirmInventoryBatchReportMatches({reportId, matches:[{inventoryId: 新建库存行}]})` 关联报告 | +| 复用 | OCR、表、关联写库**全部复用**既有实现,**不新增提示词、不新增表、不新增 AI 计量点**(AI-29 已登记) | + +### 3.4 落库效果 + +- 该行入库 ⇒ `inventory.production_date` = 报告的生产日期(人改后的值); +- 同时写 `inventory_batch_report_matches`(report ↔ 新库存批次)⇒ 库存列表「批次报告」列显示**已有**; +- ⇒ 商品同时有「**批次报告**」与「**生产时间**」。 + +### 3.5 降级(参考库存入库/Web 报告,对齐 ⑪) + +| 情形 | 处理 | +| --- | --- | +| 未配置多模态 / OCR 失败 | **只存文件**、`ai_parsed=false`,核对表里品名/日期留空由人工填,**不阻断**; +按钮不报错(与 Web 批次报告同款降级) | +| 报告无生产日期 | 核对表该格留空,人工可填;不填则该行入库时**仍落今天**(与改前一致) | +| 商品名对不上 | 标「未匹配」,不写该行;人工可从行下拉手选(可选,见 §5 默认) | +| 小程序中途退出 | 报告与 OCR 结果**已在服务端留档**(`inventory_batch_reports`),但**行上的日期是本会话状态**(见 §5-③) | + +## 4. ⚠️ 需要你批准的点(冻结面) + +**唯一实质行为变更**:订单入库(验收)**普通行**的 `inventory.production_date` 由**"今天"**改为**报告的真实生产日期**。 + +- 改动面:`inspectionComplianceService` 的 `productionDate` 取值多一个来源(逐行 `production_date`); + INSERT 语句本身**不动**(列与 `COALESCE` 兜底都已在)。 +- 影响面:该列的**读侧** = 库存列表「生产日期」列、商品溯源、批次报告匹配、`20261033` 的缺报告判定等; + **不影响** FIFO(FIFO 用 `created_at`/`expiry_date`,而验收链路**不写 `expiry_date`**,见 F6)、不影响成本/财务。 +- 回滚:前端不传 `production_date` ⇒ 行为立刻回到改前(落"今天");代码回滚只需 revert。 +- 归属:触【库存管理冻结】(入库写入的取值)与【验收与加工冻结】(验收链路)⇒ **本设计即为"先告知",请明确批准后再编码。** + +## 5. 我假定的默认(不反对就照此做) + +| # | 项 | 默认 | +| --- | --- | --- | +| ① | 疑似/未命中 | 都在**同一张核对表**里展示(疑似打标、未命中标"未匹配"),人工在核对表里确认;不做额外的二次弹窗 | +| ② | 命中行**已有**生产日期 | **覆盖**(本次上传的日期优先;因为此前普通行本来就是"今天"这个占位值) | +| ③ | 会话状态 | 行上的生产日期/报告 id **本会话内有效**(与既有 `input_qty` 等同款,刷新不丢;**小程序完全重进需重新上传**);**不新增表/列** | +| ④ | 同一行被多份报告命中 | 取**最后一份**(核对表里可改) | +| ⑤ | 手选未命中的行 | **本期不做**(未命中就不填;如需要再说) | +| ⑥ | 上传上限 | 一次最多 9 张 | +| ⑦ | 报告编号 / 检测机构 | 本期**不展示**(沿用 Web 的留档字段,不进小程序界面) | + +## 6. 验收标准 + +1. 订单入库页「一键全部合格入库」下方出现「一键上传批次报告」;可拍照/相册多选,也能选到 PDF。 +2. 上传后弹出核对表:显示 报告→品名→匹配行→生产日期;日期可改;关闭后各行带上该日期。 +3. 该行照旧「合格入库」⇒ `inventory.production_date` = 该日期(不是今天);`inventory_batch_report_matches` 有该报告与新批次的关联(库存列表「批次报告」列显示**已有**,前提是既有列已上线)。 +4. 未配多模态/OCR 失败 ⇒ 只存文件、核对表可手填、流程不阻断(与 Web 批次报告同款降级)。 +5. **回归**:不传 `production_date` 时行为与改前**逐字一致**(普通行仍落今天、预包装仍落 年月-01);`quality_reports` 与「报告齐全」硬闸**零变化**;不动 FIFO/成本/财务。 +6. 契约/单测钉住:取值优先级(逐行 > 预包装年月 > null 兜底)、降级不阻断、报告关联在入库成功后写。 + +## 7. 影响面与回滚 + +- 新增:1 个 mobile 路由(复用既有服务)+ 小程序按钮/核对表 + `complete` 两个可选字段 + `productionDate` 一个来源。 +- **不改**:`quality_reports`、库存/出库写入方、FIFO、成本账本、订单状态链、`expiry_date`。 +- 无迁移(不新增表/列;`inventory_batch_reports*` 既已存在)。 +- 回滚:前端不传新字段即可;代码 revert 本提交(小程序需重新上传)。 + +## 8. 冻结面自查 + +| 冻结面 | 是否触碰 | 说明 | +| --- | --- | --- | +| 库存管理(`inventory-freeze`) | **是(取值)** | 不改写入方/不走新链路;只把**已存在的** `production_date` 写入喂上真实值(见 §4) | +| 验收与加工(`inspection-processing-freeze`) | **是(值)** | 入库门槛、退回语义、损耗**未动** | +| 商品主数据(`product-freeze`) | 否 | 不碰 `quality_reports` 的分享/覆盖口径 | +| 前端文案 | **是(新增 1 个按钮 + 核对表)** | 按 frontend-copy 规矩**先报备**:拟「一键上传批次报告」(核对表字段名编码前另定) | +| AI 门槛登记 | 否 | 复用 `quality.report.meta`(AI-29 已登记)、不新增提示词/计量点 | +| 平台(新业务表登记) | 否 | **不新增表** | + +## 9. 修订记录 + +| 版本 | 日期 | 变更 | +| --- | --- | --- | +| v1 | 2026-10-16 | 首版设计(含 §4 待批准、§5 默认) | +| v2 | 2026-10-16 | 开发者确认「执行」⇒ 已实现;补 §10 实施清单与验证 | + +## 10. 实施清单与验证(2026-10-16 回填) + +| 层 | 文件 | 改动 | +| --- | --- | --- | +| 服务 | `server/src/services/inspectionComplianceService.ts` | `InspectionComplianceInput` 增 `production_date` / `batch_report_id`;`productionDate` 取值=**逐行 > 预包装年月 > null**(INSERT 不变);`COMMIT` 后 best-effort 调 `confirmInventoryBatchReportMatches({inventoryId: inboundInventoryId})` | +| 路由 | `server/src/routes/mobile/mobileWarehouseRoutes.ts` | `complete` 映射两字段;新增 `POST /mobile/inspection/batch-reports`(`requireInspectionManageRole`,复用 `createInventoryBatchReports`) | +| 小程序 | `miniprogram/utils/request.js` | 新增 `createInspectionBatchReports` | +| 小程序 | `miniprogram/components/inspection-panel/index.{js,wxml,wxss}` | 「一键上传批次报告」按钮(在主按钮下方)+ 核对表(可改日期、按商品名匹配)+两个提交路径都带两字段;`loadRows` 保留两字段(刷新不丢) | +| 测试 | `server/tests/inspectionBatchReportProductionDate.test.ts` | 13 例契约(取值优先级 / COMMIT 后关联 / 移动端映射与新端点 / 小程序按钮-核对表-提交接线) | +| 文档 | 本文件 + `docs/design/README.md` | 设计 + 索引 | +| 迁移 | — | **无**(不新增表/列;`inventory_batch_reports*` 既有) | + +- `npx vitest run tests/inspectionBatchReportProductionDate.test.ts` → **13/13 通过**;`npm run typecheck` → 0 错误;设计门禁 8 道 PASS(`check-ai-cost` 保持既定红)。 +- **未做**:真实图/PDF 的 OCR 与「入库→关联」全链路(需真库 + 执行 9~10 步,留待环境点测)。 diff --git a/docs/design/README.md b/docs/design/README.md index 6a5409e..62b677a 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -55,6 +55,7 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、 小程序分拣**已确认的行即时移出列表**(开发者:大量待拣时已拣完的还占视野)—— 未完成单(`pick_status < 30`)由「展示全部(含已确认)」改为**只展示待分拣行**;已完成单(`≥30`)仍为「只看待补录、全确认回退全部」,KPI/进度仍按全部行统计;口径抽到 `miniprogram/utils/pickingAssembly.js#visibleItemsForStatus` 并加单测,见 [20261016-小程序分拣已确认行即时隐藏.md](./20261016-小程序分拣已确认行即时隐藏.md)。 小程序分拣**出库照缩略图可点击预览大图**(开发者:「小程序拍照的图片 可用点击查看图片详情」)—— 行内 `.row-photo-item` 加 `bindtap` → `wx.previewImage`(用会话内 `tempFilePath`,`photo.path` 是对象存储 key 不可直接预览;删除按钮仍 `catchtap` 不误触);其它面板早有预览、只分拣这处缺,见 [20261016-小程序分拣出库照可点击预览.md](./20261016-小程序分拣出库照可点击预览.md)。 订单入库任务卡**「退回」与「商品名」换位**(开发者:点「拍照」易误触「退回」)—— 第一行由 `[退回][商品名][确认入库]` 改为 **`[商品名][退回][确认入库]`**,使第一行左侧=商品名、不再与第二行左侧的「拍照」竖向对齐;退回/入库**语义、门槛、文案、样式一字未动**,见 [20261016-订单入库任务卡退回与品名换位.md](./20261016-订单入库任务卡退回与品名换位.md)。 +订单入库**一键上传批次报告 → 提取生产日期 → 随入库落库**(设计草案,待开发者批准 §4 后编码):在「一键全部合格入库」下方加按钮,支持多张图/PDF,复用 AI-29 的 OCR(`quality.report.meta`)抽品名+生产日期,按商品名匹配**当前待验收行**,弹核对表让人改日期后关闭,入库时把日期写进 `inventory.production_date` 并把报告挂到新批次;**关键变更=验收普通行的生产日期由“今天”改为真实日期**(该列本就在写、只是取值只有预包装年月),见 [20261016-订单入库批量上传批次报告并落生产日期.md](./20261016-订单入库批量上传批次报告并落生产日期.md)。 批次报告**推送到主系统**(第九批「批次报告同步」我方推送侧:按备货行逐条登记到主系统既有「供应商上传报告」通道、台账按 `(prep_id, report_type)` 去重、**未绑定/非主系统下发的行一律不推**、默认关)见 [20261011-批次报告推送主系统.md](./20261011-批次报告推送主系统.md)。 库存**全额抵扣即视为已履约**(修「抵扣完了订单还停在待备货」:履约判据接受『链接的自采单已取消』+ 对账记录未推进原因)见 [20261012-库存全额抵扣即视为已履约(修订单卡在待备货).md](./20261012-库存全额抵扣即视为已履约(修订单卡在待备货).md)。 订单详情**「报告」列并显示批次报告**(此前只显示质检报告 ⇒ 抄手皮那几批明明绑了报告、订单行却空白;批次判据与推送侧同口径、只显示已人工确认、失败降级不卡详情)见 [20261012-订单详情显示批次报告.md](./20261012-订单详情显示批次报告.md)。 diff --git a/miniprogram/components/inspection-panel/index.js b/miniprogram/components/inspection-panel/index.js index d5066ed..8fca0c5 100644 --- a/miniprogram/components/inspection-panel/index.js +++ b/miniprogram/components/inspection-panel/index.js @@ -5,6 +5,8 @@ const { deleteInspectionPhoto, analyzeInspectionQuality, fetchStockInboundStorageZones, + uploadQualityReportStorageFile, + createInspectionBatchReports, } = require('../../utils/request'); const { getSession } = require('../../utils/auth'); const { ensureMobileRole } = require('../../utils/roleGuard'); @@ -235,6 +237,10 @@ Component({ pendingCount: 0, doneCount: 0, photoRequiredCount: 0, + /** 批次报告上传/解析进行中 */ + reportBusy: false, + /** 批次报告核对表(null = 不显示):[{key, report_id, product_name, production_date, row_id, match_label}] */ + reportReview: null, foldSameSku: false, skuGroups: [], dayCategoryGroups: [], @@ -403,6 +409,11 @@ Component({ prev && prev.storage_zone !== undefined ? prev.storage_zone : String(row.last_storage_zone || '').trim(), + // 批次报告提取的生产日期与报告 id:本会话内保留(同 input_qty,刷新不丢) + production_date: + prev && prev.production_date !== undefined ? prev.production_date : '', + batch_report_id: + prev && prev.batch_report_id !== undefined ? prev.batch_report_id : '', zoneIndex: zoneIndexOf( prev && prev.storage_zone !== undefined ? prev.storage_zone @@ -869,6 +880,160 @@ Component({ } }, + /** 批次报告:上传(拍照/相册 或 聊天里的 PDF)→ 解析 → 按商品名匹配待验收行 → 弹核对表 */ + onUploadBatchReports() { + if (this.data.reportBusy) return; + wx.showActionSheet({ + itemList: ['拍照/相册', '聊天文件(PDF)'], + success: (res) => { + if (res.tapIndex === 0) this.pickReportImages(); + else if (res.tapIndex === 1) this.pickReportFiles(); + }, + fail: () => undefined, + }); + }, + + pickReportImages() { + wx.chooseMedia({ + count: 9, + mediaType: ['image'], + sourceType: ['camera', 'album'], + success: (res) => { + const files = (res.tempFiles || []).filter((f) => f && f.tempFilePath); + if (files.length) { + this.submitReportFiles(files.map((f) => ({ path: f.tempFilePath, name: 'report.jpg' }))); + } + }, + fail: () => undefined, + }); + }, + + pickReportFiles() { + if (typeof wx.chooseMessageFile !== 'function') { + wx.showToast({ title: '当前微信版本不支持选文件', icon: 'none' }); + return; + } + wx.chooseMessageFile({ + count: 9, + type: 'file', + extension: ['pdf'], + success: (res) => { + const files = (res.tempFiles || []).filter((f) => f && f.path); + if (files.length) { + this.submitReportFiles(files.map((f) => ({ path: f.path, name: f.name || 'report.pdf' }))); + } + }, + fail: () => undefined, + }); + }, + + /** 逐张上传到 quality-reports 桶 → 调后端 OCR → 匹配 → 弹核对表 */ + async submitReportFiles(files) { + this.setData({ reportBusy: true }); + wx.showLoading({ title: '识别批次报告中…', mask: true }); + try { + const paths = []; + for (const f of files) { + try { + paths.push(await uploadQualityReportStorageFile(f.path, f.name)); + } catch (err) { + wx.showToast({ title: (err && err.message) || '报告上传失败', icon: 'none' }); + } + } + if (!paths.length) return; + const res = await createInspectionBatchReports({ files: paths }); + const reports = (res && res.data) || []; + const review = this.buildReportReview(reports); + if (!review.length) { + wx.showToast({ title: '未从报告中识别到商品', icon: 'none' }); + return; + } + this.setData({ reportReview: review }); + } catch (err) { + wx.showToast({ title: (err && err.message) || '批次报告识别失败', icon: 'none' }); + } finally { + wx.hideLoading(); + this.setData({ reportBusy: false }); + } + }, + + /** 把 OCR 结果按商品名匹配到当前待验收行,生成核对表行 */ + buildReportReview(reports) { + const rows = this.data.rows || []; + const norm = (v) => + String(v || '') + .toLowerCase() + .replace(/[\s\u3000]+/g, '') + .replace(/[()()【】\[\]「」『』《》<>·•..]/g, ''); + const out = []; + (reports || []).forEach((rep, ri) => { + const reportId = String((rep && rep.id) || ''); + const producedAt = String((rep && rep.produced_at) || '').slice(0, 10); + const names = Array.isArray(rep && rep.product_names) ? rep.product_names : []; + const list = names.length ? names : ['']; + list.forEach((name, ni) => { + const key = norm(name); + let rowId = ''; + let matchLabel = '未匹配'; + if (key) { + const hits = rows.filter((r) => norm(resolveInspectionItemName(r)) === key); + if (hits.length >= 1) { + rowId = hits[0].id; + matchLabel = `已匹配:${resolveInspectionItemName(hits[0])}`; + } else { + const fuzzy = rows.filter((r) => { + const n = norm(resolveInspectionItemName(r)); + return n && (n.indexOf(key) >= 0 || key.indexOf(n) >= 0); + }); + if (fuzzy.length) { + rowId = fuzzy[0].id; + matchLabel = `疑似:${resolveInspectionItemName(fuzzy[0])}`; + } + } + } + out.push({ + key: `r${ri}_${ni}`, + report_id: reportId, + product_name: String(name || ''), + production_date: producedAt, + row_id: rowId, + match_label: matchLabel, + }); + }); + }); + return out; + }, + + onReportDateChange(e) { + const index = Number(e.currentTarget.dataset.index); + if (!Number.isInteger(index) || !this.data.reportReview) return; + this.setData({ [`reportReview[${index}].production_date`]: String(e.detail.value || '').slice(0, 10) }); + }, + + onReportCancel() { + this.setData({ reportReview: null }); + }, + + /** 确定:把核对表里(匹配到行且有日期)的生产日期写到该行,连同报告 id 随入库提交 */ + onReportConfirm() { + const review = this.data.reportReview || []; + let applied = 0; + review.forEach((item) => { + if (!item.row_id) return; + const date = String(item.production_date || '').slice(0, 10); + const patch = { batch_report_id: item.report_id || '' }; + if (/^\d{4}-\d{2}-\d{2}$/.test(date)) { + patch.production_date = date; + applied += 1; + } + this.patchRow(item.row_id, patch); + }); + this.setData({ reportReview: null }); + wx.showToast({ title: applied ? `已记录 ${applied} 项生产日期` : '未匹配到可入库的行', icon: 'none' }); + }, + + noop() {}, + async submitInspection(e) { if (this.data.batchSubmitting) return; const id = e.currentTarget.dataset.id; @@ -927,6 +1092,9 @@ Component({ loss_qty: 0, storage_zone: String(row?.storage_zone || '').trim() || undefined, production_date_month: row?.requires_prepackaged_check ? row.production_month : undefined, + // 批次报告提取的生产日期与报告 id(人工在核对表确认过)——入库时带上 + production_date: String(row?.production_date || '').trim() || undefined, + batch_report_id: String(row?.batch_report_id || '').trim() || undefined, location: session?.profile?.branch_name || '', watermark_meta: { branch_code: session?.profile?.branch_code, @@ -991,6 +1159,8 @@ Component({ quality_rating: RESULT_PASS, loss_qty: 0, storage_zone: String(row.storage_zone || '').trim() || undefined, + production_date: String(row.production_date || '').trim() || undefined, + batch_report_id: String(row.batch_report_id || '').trim() || undefined, location: session?.profile?.branch_name || '', watermark_meta: { branch_code: session?.profile?.branch_code, diff --git a/miniprogram/components/inspection-panel/index.wxml b/miniprogram/components/inspection-panel/index.wxml index ce06803..992ddd9 100644 --- a/miniprogram/components/inspection-panel/index.wxml +++ b/miniprogram/components/inspection-panel/index.wxml @@ -132,6 +132,9 @@ + + + + + + 批次报告识别结果 + + + + {{item.product_name || '未识别品名'}} + {{item.match_label}} + + + {{item.production_date || '选择生产日期'}} ▾ + + + + + 取消 + 确定 + + + diff --git a/miniprogram/components/inspection-panel/index.wxss b/miniprogram/components/inspection-panel/index.wxss index d4318a1..eeb3069 100644 --- a/miniprogram/components/inspection-panel/index.wxss +++ b/miniprogram/components/inspection-panel/index.wxss @@ -146,6 +146,14 @@ line-height: 2.1; } +/* 「一键上传批次报告」:紧随主按钮下方,次级(描边)样式,避免抢主按钮 */ +.batch-btn--report { + margin-top: 12rpx !important; + background: #fff; + color: #059669; + border: 1rpx solid #a7f3d0; +} + .cat-grid { flex: 1; min-width: 0; @@ -456,3 +464,112 @@ color: #b45309; font-weight: 600; } + +/* 批次报告核对表(一键上传批次报告 → 提取生产日期,人工核对/修改后确定) */ +.report-mask { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.45); + z-index: 10500; +} + +.report-sheet { + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 10501; + background: #fff; + border-radius: 20rpx 20rpx 0 0; + padding: 24rpx; + display: flex; + flex-direction: column; +} + +.report-sheet-head { + font-size: 30rpx; + font-weight: 700; + color: #0a0a0b; + margin-bottom: 12rpx; +} + +.report-sheet-body { + max-height: 52vh; +} + +.report-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12rpx; + padding: 14rpx 0; + border-bottom: 1rpx solid #f1f5f9; +} + +.report-row-info { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4rpx; +} + +.report-row-name { + font-size: 26rpx; + font-weight: 600; + color: #0a0a0b; +} + +.report-row-match { + font-size: 20rpx; + color: #71717a; +} + +.report-row-match.is-hit { + color: #059669; +} + +.report-row-match.is-miss { + color: #dc2626; +} + +.report-row-date { + flex-shrink: 0; + font-size: 26rpx; + color: #0a0a0b; + padding: 8rpx 16rpx; + background: #f4f4f5; + border-radius: 10rpx; +} + +.report-row-date.is-empty { + color: #a1a1aa; +} + +.report-sheet-foot { + display: flex; + gap: 16rpx; + margin-top: 20rpx; +} + +.report-btn { + flex: 1; + text-align: center; + padding: 20rpx 0; + border-radius: 12rpx; + font-size: 28rpx; +} + +.report-btn.ghost { + background: #fff; + color: #059669; + border: 1rpx solid #a7f3d0; +} + +.report-btn.primary { + background: #059669; + color: #fff; +} diff --git a/miniprogram/utils/request.js b/miniprogram/utils/request.js index aa4b49d..cce2633 100644 --- a/miniprogram/utils/request.js +++ b/miniprogram/utils/request.js @@ -532,6 +532,14 @@ function completeInspection(payload) { }); } +/** 订单入库:批量上传批次报告(图/PDF 已上传对象路径)→ 返回 OCR 提取的品名与生产日期 */ +function createInspectionBatchReports(payload) { + return request('/mobile/inspection/batch-reports', { + method: 'POST', + data: payload, + }); +} + function uploadInspectionPhoto(payload) { return request('/mobile/inspection/photo', { method: 'POST', @@ -1361,6 +1369,7 @@ module.exports = { submitSupplierSubstitution, fetchInspectionTasks, completeInspection, + createInspectionBatchReports, uploadInspectionPhoto, deleteInspectionPhoto, analyzeInspectionQuality, diff --git a/server/src/routes/mobile/mobileWarehouseRoutes.ts b/server/src/routes/mobile/mobileWarehouseRoutes.ts index 8ef554e..2b23e8b 100644 --- a/server/src/routes/mobile/mobileWarehouseRoutes.ts +++ b/server/src/routes/mobile/mobileWarehouseRoutes.ts @@ -31,6 +31,7 @@ import { isPickingBarcodeEnabled } from '../../services/pickingBarcodeService'; import { isPickingScaleRequired } from '../../services/pickingScaleService'; import { recognizeProductionDateFromImage } from '../../services/pickingBatchDateService'; import { isIndependentInboundDetails } from '../../services/independentInboundService'; +import { createInventoryBatchReports } from '../../services/inventoryBatchReportService'; import { getWeighStationToleranceConfig } from '../../services/weighStationConfigService'; import { resolveWeighStationLabelPrintFlags } from '../../services/weighStationLabelPrintConfigService'; import { @@ -217,6 +218,9 @@ router.post('/inspection/complete', authMiddleware, async (req: AuthRequest, res production_date_month: req.body?.production_date_month ? String(req.body.production_date_month) : null, + // 逐行生产日期(批次报告提取、人工确认)与批次报告 id(入库后关联到新批次) + production_date: req.body?.production_date ? String(req.body.production_date) : null, + batch_report_id: req.body?.batch_report_id ? String(req.body.batch_report_id) : null, confirm_over_qty: parseConfirmOverQty(req.body), reject_fulfillment: parseRejectFulfillment(req.body), }, @@ -294,6 +298,43 @@ router.post('/inspection/complete-merge', authMiddleware, async (req: AuthReques } }); +/** + * 订单入库:批量上传批次报告(图/PDF)→ OCR 提取「品名 + 生产日期」。 + * 复用 Web 侧既有实现(只读 inventory 做匹配、不写 inventory、不碰 quality_reports); + * 本端只做上传+解析+留档,前端拿结果按商品名匹配待验收行,入库时再落生产日期与关联。 + * 设计 docs/design/20261016-订单入库批量上传批次报告并落生产日期.md + */ +router.post('/inspection/batch-reports', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + await requireInspectionManageRole(req); + const ctx = await loadTenantContext(req.userId); + const branchCode = ctx?.branchCode || ''; + if (!branchCode) { + return res.status(400).json({ error: 'branch_required', error_description: '缺少分公司上下文' }); + } + const files = Array.isArray(req.body?.files) ? req.body.files.map((f: unknown) => String(f)) : []; + if (!files.length) { + return res.status(400).json({ error: 'invalid_request', error_description: '请先上传批次报告' }); + } + const data = await createInventoryBatchReports({ + files, + branchCode, + uploadedBy: req.userId || null, + reportNo: req.body?.report_no ? String(req.body.report_no) : null, + }); + return res.json({ data }); + } catch (error: any) { + console.error( + `[mobile/inspection] batch-reports 失败 user=${req.userId || '-'} code=${error?.code || '-'}:`, + error + ); + return res.status(500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '上传批次报告失败', + }); + } +}); + router.get('/inspection/weigh-station/pending', authMiddleware, async (req: AuthRequest, res: Response) => { try { await requireInspectionManageRole(req); diff --git a/server/src/services/inspectionComplianceService.ts b/server/src/services/inspectionComplianceService.ts index cf9bf26..2104a26 100644 --- a/server/src/services/inspectionComplianceService.ts +++ b/server/src/services/inspectionComplianceService.ts @@ -73,6 +73,11 @@ export interface InspectionComplianceInput { watermark_meta?: Record | null; location?: string | null; production_date_month?: string | null; + /** 逐行生产日期(`YYYY-MM-DD`):来自批次报告提取、人工确认;**优先于** `production_date_month`。 + * 设计 docs/design/20261016-订单入库批量上传批次报告并落生产日期.md */ + production_date?: string | null; + /** 批次报告 id:本次入库成功后把该报告关联到新建的库存批次(落 `inventory_batch_report_matches`) */ + batch_report_id?: string | null; /** 入库后存放区域(批次级 `inventory.storage_zone`,自由文本;不填写 NULL)。独立进货与普通验收共用 */ storage_zone?: string | null; /** 过手超量二次确认 */ @@ -1611,9 +1616,11 @@ export async function submitInspectionCompliance( const inspectionSku = String(row.sku_code || '').trim(); row.sku_code = inboundSku; const productionDate = - String(input.production_date_month || '').trim().match(/^(\d{4})-(\d{2})$/) - ? `${String(input.production_date_month).trim()}-01` - : null; + /^\d{4}-\d{2}-\d{2}$/.test(String(input.production_date || '').trim()) + ? String(input.production_date).trim() + : String(input.production_date_month || '').trim().match(/^(\d{4})-(\d{2})$/) + ? `${String(input.production_date_month).trim()}-01` + : null; // 过手订单履约:记流水但不增减可用库存;合单从单:跳过入库。 // 独立入库无订单,目的就是落库存,不能因鲜品默认过手而跳过(否则 SPI 一直待入库)。 @@ -2001,6 +2008,23 @@ export async function submitInspectionCompliance( } } + // 批次报告关联:本次入库的生产日期来自批次报告(前端上传时 OCR 提取、人工确认)⇒ + // 把该报告挂到新建的库存批次上(入库已 COMMIT,此处失败不阻断:日期已在库存,仅少一条关联)。 + // 设计 docs/design/20261016-订单入库批量上传批次报告并落生产日期.md + if (!isRejected && inboundInventoryId && input.batch_report_id) { + try { + const { confirmInventoryBatchReportMatches } = await import('./inventoryBatchReportService'); + await confirmInventoryBatchReportMatches({ + reportId: String(input.batch_report_id), + branchCode, + operatorId: input.inspector_id || null, + matches: [{ inventoryId: inboundInventoryId }], + }); + } catch (err) { + console.error(`[inspection] 验收 ${input.id} 入库后关联批次报告失败:`, err); + } + } + let advanceResult: { advanced: boolean; pickCode?: string; pickCreated?: boolean } | null = null; let orderAdvancePending = false; // 入库已 COMMIT 是既成事实:后置的订单推进准备(查关联采购单/同步备货状态/取验收态)任一步失败, diff --git a/server/tests/inspectionBatchReportProductionDate.test.ts b/server/tests/inspectionBatchReportProductionDate.test.ts new file mode 100644 index 0000000..62d1e7b --- /dev/null +++ b/server/tests/inspectionBatchReportProductionDate.test.ts @@ -0,0 +1,130 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +/** + * 订单入库「一键上传批次报告 → 提取生产日期 → 随入库落库」(2026-10-16 开发者需求/批准)。 + * 设计 docs/design/20261016-订单入库批量上传批次报告并落生产日期.md。 + * + * 只钉**接线与优先级**(真实 OCR 与入库往返需真库,见设计 §6): + * ① 验收入参新增逐行 `production_date`(**优先于** 预包装 `production_date_month`)与 `batch_report_id`; + * ② 入库 COMMIT **之后**把报告关联到新建库存批次(best-effort,失败不阻断); + * ③ 移动端映射两个字段 + 新增 `POST /mobile/inspection/batch-reports`(复用既有 OCR 服务); + * ④ 小程序:按钮 + 核对表 + 两个提交路径都带上这两个字段。 + */ +const readServer = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8'); +const readMp = (rel: string) => + readFileSync(new URL(`../../miniprogram/${rel}`, import.meta.url), 'utf8'); + +const svc = readServer('src/services/inspectionComplianceService.ts'); +const mobileRoutes = readServer('src/routes/mobile/mobileWarehouseRoutes.ts'); +const mpPanelJs = readMp('components/inspection-panel/index.js'); +const mpPanelWxml = readMp('components/inspection-panel/index.wxml'); +const mpRequest = readMp('utils/request.js'); + +describe('验收:逐行生产日期优先(不改 INSERT,只改取值)', () => { + it('入参新增 production_date / batch_report_id', () => { + expect(svc).toContain('production_date?: string | null;'); + expect(svc).toContain('batch_report_id?: string | null;'); + }); + + it('取值:逐行 production_date > 预包装 production_date_month > null(仍兜底今天)', () => { + const start = svc.indexOf('const productionDate ='); + expect(start).toBeGreaterThanOrEqual(0); + const block = svc.slice(start, start + 320); + expect(block).toContain('input.production_date'); + expect(block).toContain('input.production_date_month'); + expect(block.indexOf('input.production_date')).toBeLessThan( + block.indexOf('input.production_date_month') + ); + // 仍是「YYYY-MM」→「-01」的既有预包装口径 + expect(block).toContain('-01'); + }); + + it('INSERT 的列与 COALESCE 兜底未被改(不新增列、不改写入方)', () => { + expect(svc).toContain("COALESCE($8::date, (NOW() AT TIME ZONE 'Asia/Shanghai')::date)"); + }); +}); + +describe('验收:入库成功后把批次报告关联到新建库存批次(best-effort)', () => { + it('调用既有 confirmInventoryBatchReportMatches,且以 inboundInventoryId 为主键', () => { + expect(svc).toContain("await import('./inventoryBatchReportService')"); + expect(svc).toContain('confirmInventoryBatchReportMatches({'); + expect(svc).toMatch(/matches: \[\{ inventoryId: inboundInventoryId \}\]/); + expect(svc).toMatch(/if \(!isRejected && inboundInventoryId && input\.batch_report_id\)/); + }); + + it('放在 COMMIT 之后、失败只记日志不抛(日期已入库,不因关联失败回滚)', () => { + const linkIdx = svc.indexOf('confirmInventoryBatchReportMatches({'); + expect(linkIdx).toBeGreaterThanOrEqual(0); + // 取该关联点**之前**最近的一次 COMMIT:两者很近 ⇒ 确实在提交后的收尾段 + const commitIdx = svc.slice(0, linkIdx).lastIndexOf("await client.query('COMMIT')"); + expect(commitIdx).toBeGreaterThanOrEqual(0); + expect(linkIdx - commitIdx).toBeLessThan(3000); + const tail = svc.slice(linkIdx, linkIdx + 700); + expect(tail).toContain('catch (err)'); + expect(tail).toContain('console.error'); + }); +}); + +describe('移动端路由', () => { + it('complete 映射 production_date / batch_report_id', () => { + expect(mobileRoutes).toMatch( + /production_date: req\.body\?\.production_date \? String\(req\.body\.production_date\) : null/ + ); + expect(mobileRoutes).toMatch( + /batch_report_id: req\.body\?\.batch_report_id \? String\(req\.body\.batch_report_id\) : null/ + ); + }); + + it('新增 POST /mobile/inspection/batch-reports 且复用既有 OCR 服务', () => { + expect(mobileRoutes).toContain("router.post('/inspection/batch-reports'"); + expect(mobileRoutes).toContain('createInventoryBatchReports({'); + expect(mobileRoutes).toContain("from '../../services/inventoryBatchReportService'"); + expect(mobileRoutes).toContain('requireInspectionManageRole'); + }); + + it('后端不新增表/不碰 quality_reports(复用既有独立表与服务)', () => { + expect(mobileRoutes).toContain('createInventoryBatchReports'); + // 端点内只上调服务,不直接写 inventory + const start = mobileRoutes.indexOf("router.post('/inspection/batch-reports'"); + const block = mobileRoutes.slice(start, start + 1400); + expect(block).not.toContain('INSERT INTO inventory'); + }); +}); + +describe('小程序:按钮 / 核对表 / 两个提交路径都带上字段', () => { + it('request 有 createInspectionBatchReports(复用 quality-reports 桶上传)', () => { + expect(mpRequest).toContain('function createInspectionBatchReports('); + expect(mpRequest).toContain("'/mobile/inspection/batch-reports'"); + expect(mpRequest).toContain('createInspectionBatchReports,'); + expect(mpPanelJs).toContain('uploadQualityReportStorageFile'); + }); + + it('按钮在「一键全部合格入库」下方,且核对表存在', () => { + const iBulk = mpPanelWxml.indexOf('一键全部合格入库'); + const iReport = mpPanelWxml.indexOf('一键上传批次报告'); + expect(iBulk).toBeGreaterThanOrEqual(0); + expect(iReport).toBeGreaterThan(iBulk); + expect(mpPanelWxml).toContain('bindtap="onUploadBatchReports"'); + expect(mpPanelWxml).toContain('wx:if="{{reportReview}}"'); + expect(mpPanelWxml).toContain('catchtap="onReportConfirm"'); + expect(mpPanelWxml).toContain('bindchange="onReportDateChange"'); + }); + + it('核对表:按商品名匹配 + 日期可改 + 确定才写入行', () => { + expect(mpPanelJs).toContain('buildReportReview(reports)'); + expect(mpPanelJs).toContain('match_label'); + expect(mpPanelJs).toContain('onReportDateChange(e)'); + expect(mpPanelJs).toMatch(/onReportConfirm\(\)[\s\S]{0,600}this\.patchRow\(item\.row_id, patch\)/); + }); + + it('逐行入库与一键入库都带 production_date / batch_report_id', () => { + const occurrences = mpPanelJs.match(/batch_report_id: String\(row/g) || []; + expect(occurrences.length).toBeGreaterThanOrEqual(2); + }); + + it('刷新不丢:loadRows 从 prev 保留 production_date / batch_report_id', () => { + expect(mpPanelJs).toContain('prev.production_date !== undefined'); + expect(mpPanelJs).toContain('prev.batch_report_id !== undefined'); + }); +});