Web验收拍照识别 + 修上传失败
① Web 验收拍照/拖入后自动 AI 识别(复用库存入库识别,预填 规格/生产日期/保质期/产地,只补空、切单丢弃过期响应,零新增文案)。 ② 修「拍照后上传失败」:根因是照片 dataURL 内联在提交体,而全局 express.json 仅 2mb 且照片不降尺寸/质量 0.92 ⇒ 大图必 413。 甲:照片先降尺寸再画水印(≤1600px / q0.8,对齐小程序); 丙:仅把 /api/workflow/inspection/submit 体上限放宽到 20mb。 ③ 小程序逐张上传单张失败不中断整批 + 汇总提示。 新增契约测试;门禁与全量回归对基线。
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
# Web 验收拍照:加 AI 识别 + 修「拍照后上传失败」
|
||||
|
||||
> 2026-10-16 · 开发者指令:「(Web)可以」+「但是无论是 web 还是小程序你都需要注意 别出现拍照后无法上传图片
|
||||
> 上传失败的情况」。采用**推荐方案 甲 + 丙**(+ Web 拍照识别 + 小程序上传容错)。
|
||||
> 关联:[20261016-订单入库拍照多图识别.md](./20261016-订单入库拍照多图识别.md)(小程序侧多拍识别)、
|
||||
> [20260921-quality-report-upload-multer-channel.md](./20260921-quality-report-upload-multer-channel.md)(**同族**:base64 塞 JSON body 撞 2mb 全局上限 ⇒ 413)、
|
||||
> [20261016-订单入库补规格生产日期保质期产地.md](./20261016-订单入库补规格生产日期保质期产地.md)(Web 验收的 4 字段来源)。
|
||||
|
||||
## 0. 一句话
|
||||
|
||||
① Web 验收弹窗拍照/拖入后**自动 AI 识别**(与小程序同款,预填 规格/生产日期/保质期/产地,只补空);
|
||||
② 修 Web 验收「拍照后上传失败」——根因是**照片 dataURL 内联在提交体里**,而全局 `express.json` 上限 **2mb**,
|
||||
且照片**不降尺寸**、质量 0.92 ⇒ 大图必 413。做法:**甲** 照片先降尺寸到 ≤1600px、质量 0.8(对齐小程序);
|
||||
**丙** 仅把 `/api/workflow/inspection/submit` 请求体上限放宽到 20mb。③ 顺带让小程序逐张上传**一只失败不中断整批**。
|
||||
|
||||
## 1. 改前实测(根因)
|
||||
|
||||
| # | 事实 | 证据 |
|
||||
|---|---|---|
|
||||
| F1 | **Web 验收把照片作为 dataURL 内联在提交体**:提交 `POST /api/workflow/inspection/submit`,请求体带 `inspection_photos: photos`(dataURL 数组) | `src/pages/inspection/InspectionManagement.tsx` `submitInspection`;`src/utils/inspectionCompliance.ts` → `workflowApi.submitInspectionComplianceApi('/inspection/submit')` |
|
||||
| F2 | **全局 JSON 体上限 2mb**;只有 `/api/workflow|mobile/inventory/recognize-lines` 放宽到 20mb | `server/src/index.ts`:`app.use(express.json({ limit: '2mb' }))` |
|
||||
| F3 | Web 验收照片 `renderInspectionPhotoWithWatermark` **不降尺寸**、JPEG **0.92** ⇒ 一张 5MB 原图 → dataURL ~4~6MB | `src/utils/imageFileLimits.ts` |
|
||||
| F4 | 小程序**逐张上传** `/api/mobile/inspection/photo`,且先压缩到 **≤1600px / 质量 80** ⇒ 每张 100~400KB,提交体很小 | `miniprogram/utils/orderImage.js` `prepareOrderImageBase64`;`inspection-panel` `uploadPhoto` |
|
||||
| F5 | 小程序上传循环**一张抛错即中断整批**(`for` 里直接 `await`,异常跳到 `catch`) | `inspection-panel` `choosePhoto` |
|
||||
| F6 | Web 验收**没有任何 AI 识别**(`InspectionManagement.tsx` 零 `recognizeInventoryLinesApi`);workflow 识别接口权限含 `inspection_manage` | 本会话 grep;`server/src/modules/workflow/routes/inventoryRoutes.ts` |
|
||||
| F7 | 同族先例:检验报告曾把 base64 塞 JSON body 撞 2mb ⇒ 改 multer 通道 | `docs/design/20260921-quality-report-upload-multer-channel.md` |
|
||||
|
||||
⇒ F2+F3 叠加:**Web 验收照片一大就 413「上传失败」**(一张 5MB 原图即可能爆,6 张必爆);小程序因 F4 基本不失败。
|
||||
|
||||
## 2. 目标 / 非目标
|
||||
|
||||
**目标**
|
||||
|
||||
- Web 验收:拍照/拖入后自动 AI 识别,预填 4 字段(**只补空**、失败不阻断)。
|
||||
- 消除 Web 验收照片**体积型**上传失败:甲(照片压缩降尺寸,对齐小程序)+ 丙(该路由体上限放宽)。
|
||||
- 小程序:逐张上传**单张失败不中断**,最后汇总提示。
|
||||
|
||||
**非目标**
|
||||
|
||||
- 不改验收门槛(`inspection_photo_required`)、损耗、拒收回退、入库写路径。
|
||||
- 不改 Web 验收照片**张数上限**(仍 6)与交互;不改 `loadOrientedCanvasFromFile`(发票/其它共用)。
|
||||
- 不改小程序「须/免拍照」判定与识别口径(多拍识别已在前一提交完成)。
|
||||
- 不动全局 `express.json({ limit: '2mb' })`(只放这一个路由)。
|
||||
|
||||
## 3. 设计
|
||||
|
||||
### 3.1 甲:Web 验收照片「先降尺寸、再画水印」
|
||||
|
||||
- `renderInspectionPhotoWithWatermark`:新增 `INSPECTION_PHOTO_MAX_DIMENSION = 1600`;先按最长边 ≤1600px 画进新画布,**再**在缩后的画布上画水印,最后 `toDataURL('image/jpeg', 0.8)`(原 0.92)。
|
||||
- ⚠️ 顺序不可颠倒:先画水印再缩,水印字会被一起缩小到不可读。
|
||||
- 口径与小程序 `utils/orderImage.js`(1600 / 80)**一致**,不是新取舍。
|
||||
|
||||
### 3.2 丙:仅放宽验收提交体上限
|
||||
|
||||
```ts
|
||||
app.use('/api/workflow/inspection/submit', express.json({ limit: '20mb' }));
|
||||
```
|
||||
|
||||
放在全局 `express.json({ limit: '2mb' })` **之前**;与 recognize-lines 同例。甲控体积、丙给余量(6 张 × base64 膨胀可能贴近 2mb)。
|
||||
|
||||
### 3.3 Web 拍照识别(复用库存入库那套)
|
||||
|
||||
- `ingestPhotoFiles` 成功落地照片后调 `runRecognizeFromPhotos(added)`:dataURL 去前缀 → `recognizeInventoryLinesApi({ images_base64, operatingBranchCode })`(多张**一次**提交)。
|
||||
- 结果**跨项取第一个非空**:规格/产地/生产日期;保质期 `composeShelfLifeText → parseShelfLife` 归一为「数值 + 年/月/日」(与 Web 验收的保质期控件同形)。
|
||||
- **只补空**(各字段已有值不动);程序化预填**不置** `specEdited`/`originEdited`(不触发档案回写)。
|
||||
- generation 守卫:切单(`handleStartInspection`)+1,过期响应丢弃,不得写新单表单。
|
||||
- 失败不阻断(toast 后仍可人工填)。**零新增文案**:复用 `inventory.stockIn.filled`(已回填识别到的空字段,其余请手补)/ `inventory.stockIn.recognizeFail`(识别失败)。
|
||||
|
||||
### 3.4 小程序:上传容错
|
||||
|
||||
`choosePhoto` 的逐张循环改 `try/catch`:单张失败 `failed += 1` 后**继续**下一张;**全部失败**则提示「照片上传失败,请重试」并中止;**部分失败**在流程末尾补一条「N 张未上传,请重试」(覆盖上一条 toast)。
|
||||
|
||||
## 4. 验收标准
|
||||
|
||||
1. Web 验收选/拖入 1~6 张 → 成功入列,**提交不再 413**;照片最长边 ≤1600px、体积明显下降、水印仍在。
|
||||
2. 拍照后 4 字段**被预填**(只补空;已填不动),提示「已回填识别到的空字段,其余请手补」;识别失败提示「识别失败」且不影响提交。
|
||||
3. 切单时在途识别响应**不写入**新单表单。
|
||||
4. 小程序:一批里某张失败,其余照常上传,末尾提示「N 张未上传,请重试」;全失败则提示后中止。
|
||||
5. `node --check` / `npm run typecheck` 通过;相关契约测试全绿;8 道快档门禁 RC=0(`check-ai-cost` 保持既定红)。
|
||||
6. 既有基线不回归(全量 vitest 失败数 == 基线)。
|
||||
|
||||
## 5. 影响面与回滚
|
||||
|
||||
- 改:`src/utils/imageFileLimits.ts`(照片压缩)、`src/pages/inspection/InspectionManagement.tsx`(拍照识别接线)、
|
||||
`server/src/index.ts`(一行体上限)、`miniprogram/components/inspection-panel/index.js`(上传容错)+ 新增 1 个契约测试。
|
||||
- **无迁移、无新表、无新文案、无权限变更**;识别接口复用既有(不新增 AI 功能,仅调用面增加)。
|
||||
- ⚠️ **存档照片分辨率下降**(≤1600px)——与小程序**同口径**,属对齐而非新取舍;影响面=Web 验收照片清晰度。
|
||||
- ⚠️ 丙放宽了该**鉴权路由**的请求体面(`inspection_manage`);全局与其它路由不变。
|
||||
- 回滚:`git revert` 本提交(前端/小程序需重新发布)。**重活验证**:需在真实浏览器点一次拍照+提交确认无 413。
|
||||
|
||||
## 6. 冻结面自查
|
||||
|
||||
| 冻结面 | 是否触碰 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 验收与加工(`inspection-processing-freeze`) | **仅照片体积/识别预填** | 不改入库门槛、损耗、拒收回退、`inspection_photo_required`;照片落点/归档/签名链路未动 |
|
||||
| 库存管理(`inventory-freeze`) | 否 | 入库写路径未动 |
|
||||
| 前端文案(`frontend-copy-changes`) | **Web 零新增**(复用既有键);小程序新增 2 条失败提示文案(已获「可以」) | 见 §3.4 |
|
||||
| AI 门槛登记 | 否(非新功能) | 同一识别接口,Web 侧新增调用点;调用量变化已记 §3.3 |
|
||||
| 订单状态链 / 财务 / 商品主数据 | 否 | 未碰 |
|
||||
|
||||
## 7. 修订记录
|
||||
|
||||
| 版本 | 日期 | 变更 |
|
||||
| --- | --- | --- |
|
||||
| v1 | 2026-10-16 | Web 验收加拍照 AI 识别(只补空、零新增文案)+ 甲(照片 ≤1600px/q0.8)+ 丙(submit 体上限 20mb)+ 小程序上传单张容错 |
|
||||
@@ -104,6 +104,7 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、
|
||||
**Web 库存入库面板保质期改为「数值 + 年/月/日」**:三处保质期输入形态统一的**最后一块**(小程序订单入库、Web 验收弹窗早已是「数值 + 年/月/日」)——`StockInboundPanel.tsx` 的保质期格由**纯文本**改为**数值框 + 年/月/日下拉**,两控件改动即时经 `composeShelfLifeText` 组回**原文**写进 `shelf_life`(**落库口径与提交/预填路径一字未动**,`inventory.shelf_life` 仍存原文、有效期仍由服务端 `deriveExpiryDate` 推算);预填/AI/多图合并后由面板层 helper `withShelfLifeFields`(`parseShelfLife`,**只补空**)把原文拆回两控件,**不改 `applyInboundBackfill` 预填规则**;同格内联不破 `grid-cols-5`;**零新增文案**(复用 `phShelf` 与 `inspection.qc.shelf*`),见 [20261016-Web库存入库保质期数值与单位.md](./20261016-Web库存入库保质期数值与单位.md)。
|
||||
订单详情「**选择抵扣的库存商品**」弹窗(`OrderItemCoverSkuModal`)候选行新增展示**规格 / 是否有批次报告 / 生产日期**(2026-10-16 开发者)——全走**读侧**(`skus.spec` + `EXISTS(inventory_batch_report_matches)`(口径同库存列表)+ 可扣批次的 `inventory.production_date`,多批给「最早 ~ 最晚」);**零新增文案**(复用 `orders.detail.colSpec`/`inventory.col.prodDate`/`inventory.col.batchReport`+`present|missing`);**不改抵扣口径与写路径、不做按批次选**(弹窗仍 SKU 级、FIFO 取批),见 [20261016-选择抵扣库存商品展示规格批次报告与生产日期.md](./20261016-选择抵扣库存商品展示规格批次报告与生产日期.md)。
|
||||
订单入库**「拍照」支持多拍(一次 AI 识别全部照片)**(2026-10-16 开发者)——小程序 `inspection-panel` 的拍照原用 `chooseImage count:3` 可多选,但 `uploadPhoto` 每张都**覆盖**单一缓存、识别只发**最后一张**(信息分散在不同角度照片时其余白拍);现改为**本批全部照片一次提交**(`images_base64: [...]`),结果**跨行按字段合并**(规格/产地/生产日期取第一个非空、保质期取第一个能解析的)后仍**只补空**;不改上传/门槛/入库写路径/文案;**免拍照行同样触发识别**(触发条件由 `photoRequired` 改为「只要本行有照片」)+ **每批张数 3 → 9**(2026-10-16 开发者「可以」),见 [20261016-订单入库拍照多图识别.md](./20261016-订单入库拍照多图识别.md)。
|
||||
**Web 验收拍照:加 AI 识别 + 修「拍照后上传失败」**(2026-10-16 开发者)——① Web 验收拍照/拖入后自动 AI 识别(复用库存入库识别,预填 规格/生产日期/保质期/产地,**只补空**、切单丢弃过期响应、**零新增文案**(复用 `inventory.stockIn.*`));② 修「上传失败」:根因是 Web 把照片 **dataURL 内联**在提交体而全局 `express.json` 仅 **2mb** 且照片**不降尺寸**/质量 0.92 ⇒ 大图必 413(同族先例 20260921 检验报告)——**甲** 照片先降尺寸再画水印(≤1600px / q0.8,**对齐小程序**)+ **丙** 仅把 `/api/workflow/inspection/submit` 体上限放宽到 20mb;③ 小程序逐张上传**单张失败不中断整批**+汇总提示,见 [20261016-Web验收拍照识别与上传失败修复.md](./20261016-Web验收拍照识别与上传失败修复.md)。
|
||||
**隐藏「竞价管理」菜单项**:「竞价管理」一直出现在**导航菜单配置页**,根因是**菜单可见项来自前端静态目录**(`MENU_CATALOG`)而**功能开关**(`bid_settings`,默认关且已列入退役键)**与它没有联动** —— 截图里那条带"隐藏"图标说明该分公司菜单行已隐藏(侧边栏看不到),配置页列的是内置目录全集。按「隐藏市场价格监控」先例**摘菜单项、保留能力面**:去掉目录项 + 默认布局占位 + 模块注册表 menuKeys,**保留**权限码 `bid_manage`/页面 `BidManagement.tsx`/三语 i18n/`bids` 路由(直接访问仍可用);存量布局无需清库(归一化丢弃目录外 menuKey)。数据实证:生产与本地 `bid_settings.enabled=false`、三租户 `bid_rounds/bid_quotes` 全 0,见 [20261015-隐藏竞价管理菜单项(功能已关三租户0使用).md](./20261015-隐藏竞价管理菜单项(功能已关三租户0使用).md)。
|
||||
**导航菜单配置页「长按拖动排序」修复**(开发者报障:松手仍"按中"、位置交换错乱、拖动卡):①长按计时器只在**行元素**上挂 pointerup ⇒ 行外松手不触发元素事件,450ms 后凭空进入拖拽并卡住 ⇒ 改为**窗口级兜底取消**(并 `detach` 解绑);②悬停下标内联实现**把被拖行自身当边界**,与"其余行各让一个槽位"的视觉位移错开一位 ⇒ 抽纯算法 `resolveRowDropIndex`(**排除被拖行**,插入槽位即最终下标,与 `reorderGroupMenuItems` 先删后插语义一致);③每个 pointermove 直接两次 setState(近 1300 行页面整页重渲染)⇒ 改 **requestAnimationFrame 合并**并跳过值未变提交;纯算法 7 例 + 接线契约 5 例钉住(整页 jsdom 挂载会让 worker 退出,观感仍需人眼确认),见 [20261015-导航菜单拖动排序修复(松手仍按中与位置交换错乱).md](./20261015-导航菜单拖动排序修复(松手仍按中与位置交换错乱).md)。
|
||||
**订单详情补回「收货地址」编辑入口(自建单)**:开发者报障「本地这单地址无法点击编辑」——实测两条路都不通:列表行内地址编辑要求 `is_main_system_order === true`(**只给主系统分配单**),而详情里那条地址行又跟着 `SHOW_ORDER_DETAIL_SHEET_HEADER = false`(常量,有契约测试)的送货单表头**整块被关掉**,`canEditAddress`/`addressEditing`/`onHeaderChange(delivery_address)` 全成死代码 ⇒ Web 上无处改自建单地址(只有录单时能填;小程序详情可改)。按裁决**方案甲**:把地址这一行抽成 `OrderDeliveryAddressEditor`(三态与文案原样复用、不新增文案)**在关闭块之外**渲染,其余表头字段仍隐藏;页面零改动(props 早已传入);状态门槛不变(`PATCH /orders/:code/delivery-address` 窗口为未发车 `<60`),见 [20261015-订单详情补回收货地址编辑入口(自建单).md](./20261015-订单详情补回收货地址编辑入口(自建单).md)。
|
||||
|
||||
@@ -932,8 +932,18 @@ Component({
|
||||
wx.showLoading({ title: '上传中…', mask: true });
|
||||
try {
|
||||
let latestScan = null;
|
||||
// 单张失败不中断其余(弱网常见):继续传下一张,最后汇总提示
|
||||
let failed = 0;
|
||||
for (const filePath of paths) {
|
||||
latestScan = await this.uploadPhoto(id, filePath);
|
||||
try {
|
||||
latestScan = await this.uploadPhoto(id, filePath);
|
||||
} catch (err) {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
if (failed && failed === paths.length) {
|
||||
wx.showToast({ title: '照片上传失败,请重试', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
if (latestScan && latestScan.label_matched === false) {
|
||||
const hints = [];
|
||||
@@ -958,6 +968,10 @@ Component({
|
||||
} else if (!(latestScan && latestScan.label_matched === false)) {
|
||||
wx.showToast({ title: '拍照验收已上传', icon: 'success' });
|
||||
}
|
||||
// 有失败张:最后再提示一次(覆盖上一条 toast,失败更该被看见)
|
||||
if (failed) {
|
||||
wx.showToast({ title: `${failed} 张未上传,请重试`, icon: 'none', duration: 3000 });
|
||||
}
|
||||
} catch (err) {
|
||||
wx.showToast({ title: err.message || '上传失败', icon: 'none' });
|
||||
} finally {
|
||||
|
||||
@@ -75,6 +75,9 @@ app.use('/api/integration/main-system/webhook', express.raw({ type: '*/*', limit
|
||||
// 库存入库·多商品识别:一次可上传多张图片(base64),仅这两个路由放宽 body 上限;其余仍 2mb
|
||||
app.use('/api/workflow/inventory/recognize-lines', express.json({ limit: '20mb' }));
|
||||
app.use('/api/mobile/inventory/recognize-lines', express.json({ limit: '20mb' }));
|
||||
// 验收提交:**Web 端**把验收照片作为 dataURL **内联**在请求体里(小程序走逐张上传、不受影响);
|
||||
// 上限 6 张 × base64 膨胀可能超 2mb ⇒ 仅该路由放宽(同 recognize-lines 先例)
|
||||
app.use('/api/workflow/inspection/submit', express.json({ limit: '20mb' }));
|
||||
app.use(express.json({ limit: '2mb' }));
|
||||
|
||||
function loginKeyGenerator(req: {
|
||||
|
||||
@@ -55,9 +55,9 @@ import {
|
||||
} from '../../utils/datetime';
|
||||
import { useFetchGeneration } from '../../hooks/useFetchGeneration';
|
||||
import { submitInspectionCompliance } from '../../utils/inspectionCompliance';
|
||||
import { listInspectionsManagementApi, fetchInboundLabelPrintApi, setInboundLabelPrintApi, fetchIndependentInboundFlowApi, setIndependentInboundFlowApi, amendInspectionInboundApi, listInventoryStorageZonesApi } from '../../utils/workflowApi';
|
||||
import { listInspectionsManagementApi, fetchInboundLabelPrintApi, setInboundLabelPrintApi, fetchIndependentInboundFlowApi, setIndependentInboundFlowApi, amendInspectionInboundApi, listInventoryStorageZonesApi, recognizeInventoryLinesApi } from '../../utils/workflowApi';
|
||||
import { buildBatchRowArchive } from '../../utils/inboundArchiveBatch';
|
||||
import { composeShelfLifeText } from '../../utils/shelfLife';
|
||||
import { composeShelfLifeText, parseShelfLife } from '../../utils/shelfLife';
|
||||
import {
|
||||
validateGeneralImageFile,
|
||||
isGeneralImageFile,
|
||||
@@ -763,9 +763,84 @@ export const InspectionManagement: React.FC = () => {
|
||||
/** 搜索命中只落在另一个状态 Tab 时自动切过去,避免「顶部有数、列表为空」 */
|
||||
const autoSwitchedSearchRef = useRef('');
|
||||
const inspectionPhotoDropRef = useRef<HTMLDivElement>(null);
|
||||
/** 拍照识别的 generation:过期响应不得写入表单(切单/重拍都会 +1) */
|
||||
const recognizeGenRef = useRef(0);
|
||||
|
||||
/**
|
||||
* 拍照后「识别商品信息」(2026-10-16,与小程序同款):
|
||||
* 把 规格/生产日期/保质期/产地 **只补空** 预填到验收表单(不覆盖人工已填)。
|
||||
* 复用库存入库那套识别(`/inventory/recognize-lines`,权限含 `inspection_manage`):多张**一次**提交,
|
||||
* 结果跨项取第一个非空。失败不阻断(可人工填)。**零新增文案**(复用 `inventory.stockIn.*`)。
|
||||
*/
|
||||
const runRecognizeFromPhotos = async (dataUrls: string[]) => {
|
||||
const images = dataUrls
|
||||
.map((url) => {
|
||||
const at = url.indexOf(',');
|
||||
return at >= 0 ? url.slice(at + 1) : url;
|
||||
})
|
||||
.filter(Boolean);
|
||||
if (!images.length) return;
|
||||
const gen = ++recognizeGenRef.current;
|
||||
try {
|
||||
const result = await recognizeInventoryLinesApi({
|
||||
images_base64: images,
|
||||
operatingBranchCode: effectiveBranchCode,
|
||||
});
|
||||
if (gen !== recognizeGenRef.current) return;
|
||||
const items = Array.isArray(result?.items) ? result.items : [];
|
||||
if (!items.length) return;
|
||||
let spec = '';
|
||||
let origin = '';
|
||||
let production = '';
|
||||
let shelfValue = '';
|
||||
let shelfUnit = '';
|
||||
for (const item of items) {
|
||||
if (!item) continue;
|
||||
if (!spec) spec = String(item.spec || '').trim();
|
||||
if (!origin) origin = String(item.origin || '').trim();
|
||||
if (!production) production = String(item.production_date || '').trim().slice(0, 10);
|
||||
if (!shelfValue && !shelfUnit) {
|
||||
const text =
|
||||
composeShelfLifeText(item.shelf_life_value, item.shelf_life_unit) ||
|
||||
String(item.shelf_life || '').trim();
|
||||
const parsed = parseShelfLife(text);
|
||||
if (parsed) {
|
||||
shelfValue = String(parsed.n);
|
||||
shelfUnit = parsed.unit === 'day' ? '日' : parsed.unit === 'month' ? '月' : '年';
|
||||
} else if (/^\d+$/.test(text)) {
|
||||
shelfValue = text;
|
||||
}
|
||||
}
|
||||
}
|
||||
let touched = false;
|
||||
if (spec && !specInput.trim()) {
|
||||
setSpecInput(spec);
|
||||
touched = true;
|
||||
}
|
||||
if (origin && !originInput.trim()) {
|
||||
setOriginInput(origin);
|
||||
touched = true;
|
||||
}
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(production) && !productionDate.trim()) {
|
||||
setProductionDate(production);
|
||||
touched = true;
|
||||
}
|
||||
if ((shelfValue || shelfUnit) && !shelfLifeValue.trim() && !shelfLifeUnit) {
|
||||
setShelfLifeValue(shelfValue);
|
||||
setShelfLifeUnit(shelfUnit);
|
||||
touched = true;
|
||||
}
|
||||
// 识别结果是**程序化预填**(不算人工改过,不回写商品档案)
|
||||
if (touched) notify.success(t('inventory.stockIn.filled'));
|
||||
} catch {
|
||||
if (gen !== recognizeGenRef.current) return;
|
||||
notify.error(t('inventory.stockIn.recognizeFail'));
|
||||
}
|
||||
};
|
||||
|
||||
const ingestPhotoFiles = async (files: File[]) => {
|
||||
const candidates = files.slice(0, Math.max(0, 6 - photos.length));
|
||||
const added: string[] = [];
|
||||
for (const file of candidates) {
|
||||
const validationError = validateGeneralImageFile(file);
|
||||
if (validationError) {
|
||||
@@ -777,11 +852,14 @@ export const InspectionManagement: React.FC = () => {
|
||||
orderCode: selectedTask?.order_code || '',
|
||||
branchName: profile?.branch_name || t('inspection.branchFallback'),
|
||||
});
|
||||
added.push(dataUrl);
|
||||
setPhotos((prev) => [...prev, dataUrl]);
|
||||
} catch {
|
||||
notify(t('inspection.toast.imageReadFail', { name: file.name }));
|
||||
}
|
||||
}
|
||||
// 拍照 / 拖入后自动识别(只在本批真有照片落地时;失败不阻断)
|
||||
if (added.length) void runRecognizeFromPhotos(added);
|
||||
};
|
||||
|
||||
const { isDropZoneActive: isPhotoDropActive, clickGuardRef: photoDropClickGuardRef } = useFileDropUpload(
|
||||
@@ -922,6 +1000,8 @@ export const InspectionManagement: React.FC = () => {
|
||||
const handleStartInspection = (task: InspectionTask) => {
|
||||
const done = isInspectionCompleted(task);
|
||||
setSelectedTask(task);
|
||||
// 换单:作废在途的拍照识别响应,防止写入新单表单
|
||||
recognizeGenRef.current += 1;
|
||||
setShowInspectionModal(true);
|
||||
setInspectionStep(done ? 4 : resolveInitialInspectionStep(buildInspectionStepContext(task)));
|
||||
const existingPhotos = Array.isArray(task.inspection_photos)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* Web 验收弹窗「拍照 → AI 识别」+ 拍照上传可靠性(2026-10-16 开发者:
|
||||
* 「web 也补上同款拍照识别;无论 web 还是小程序,别出现拍照后无法上传 / 上传失败」)。
|
||||
*
|
||||
* 设计 docs/design/20261016-验收拍照上传可靠性(Web照片压缩与提交体上限)与Web拍照识别.md。
|
||||
*/
|
||||
const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
|
||||
|
||||
const page = read('./InspectionManagement.tsx');
|
||||
const limits = read('../../utils/imageFileLimits.ts');
|
||||
const serverIndex = read('../../../server/src/index.ts');
|
||||
const mpPanel = read('../../../miniprogram/components/inspection-panel/index.js');
|
||||
|
||||
describe('Web 验收照片:先降尺寸再画水印(避免提交体超限)', () => {
|
||||
it('上限与质量对齐小程序(1600 / 0.8),且不再用 0.92 原尺寸', () => {
|
||||
expect(limits).toContain('export const INSPECTION_PHOTO_MAX_DIMENSION = 1600;');
|
||||
expect(limits).toContain('const INSPECTION_PHOTO_JPEG_QUALITY = 0.8;');
|
||||
expect(limits).not.toContain('INSPECTION_PHOTO_JPEG_QUALITY = 0.92');
|
||||
});
|
||||
|
||||
it('顺序必须是「先缩尺寸、再画水印」(否则水印字被一起缩小)', () => {
|
||||
const resizeAt = limits.indexOf('resizedContext.drawImage(source, 0, 0, resized.width, resized.height);');
|
||||
const watermarkAt = limits.indexOf('context.fillText(`验收拍照');
|
||||
expect(resizeAt).toBeGreaterThan(-1);
|
||||
expect(watermarkAt).toBeGreaterThan(-1);
|
||||
expect(resizeAt).toBeLessThan(watermarkAt);
|
||||
});
|
||||
});
|
||||
|
||||
describe('服务端:验收提交体上限放宽(同 recognize-lines 先例)', () => {
|
||||
it("仅放宽 /api/workflow/inspection/submit,全局仍 2mb", () => {
|
||||
expect(serverIndex).toContain(
|
||||
"app.use('/api/workflow/inspection/submit', express.json({ limit: '20mb' }));"
|
||||
);
|
||||
expect(serverIndex).toContain("app.use(express.json({ limit: '2mb' }));");
|
||||
// 放宽那行必须在全局 2mb 之前
|
||||
expect(serverIndex.indexOf("'/api/workflow/inspection/submit', express.json({ limit: '20mb' })")).toBeLessThan(
|
||||
serverIndex.indexOf('app.use(express.json({ limit: \'2mb\' }))')
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Web 验收:拍照后自动 AI 识别(只补空,复用既有文案)', () => {
|
||||
it('复用库存入库识别接口,多张一次提交', () => {
|
||||
expect(page).toContain('recognizeInventoryLinesApi');
|
||||
expect(page).toContain('const runRecognizeFromPhotos = async (dataUrls: string[]) => {');
|
||||
expect(page).toContain('images_base64: images,');
|
||||
// dataURL 去前缀取 base64
|
||||
expect(page).toContain("const at = url.indexOf(',');");
|
||||
});
|
||||
|
||||
it('只补空、不覆盖人工已填', () => {
|
||||
expect(page).toContain('if (spec && !specInput.trim()) {');
|
||||
expect(page).toContain('if (origin && !originInput.trim()) {');
|
||||
expect(page).toContain('if ((shelfValue || shelfUnit) && !shelfLifeValue.trim() && !shelfLifeUnit) {');
|
||||
});
|
||||
|
||||
it('拍照/拖入后触发;过期响应丢弃(generation)', () => {
|
||||
expect(page).toContain('if (added.length) void runRecognizeFromPhotos(added);');
|
||||
expect(page).toContain('const recognizeGenRef = useRef(0);');
|
||||
expect(page).toContain('if (gen !== recognizeGenRef.current) return;');
|
||||
});
|
||||
|
||||
it('零新增文案:复用 inventory.stockIn.filled / recognizeFail', () => {
|
||||
expect(page).toContain("t('inventory.stockIn.filled')");
|
||||
expect(page).toContain("t('inventory.stockIn.recognizeFail')");
|
||||
});
|
||||
});
|
||||
|
||||
describe('小程序:拍照上传单张失败不中断其余', () => {
|
||||
it('逐张容错 + 全失败中止 + 汇总提示', () => {
|
||||
expect(mpPanel).toContain('let failed = 0;');
|
||||
expect(mpPanel).toContain('failed += 1;');
|
||||
expect(mpPanel).toContain('if (failed && failed === paths.length) {');
|
||||
expect(mpPanel).toContain('张未上传,请重试');
|
||||
});
|
||||
});
|
||||
@@ -62,7 +62,16 @@ function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
const INSPECTION_PHOTO_JPEG_QUALITY = 0.92;
|
||||
/**
|
||||
* 验收存档照片上限:最长边 ≤1600px、JPEG 质量 0.8 —— 与小程序 `utils/orderImage.js`
|
||||
* (`MAX_DIMENSION = 1600` / `COMPRESS_QUALITY = 80`)**同口径**。
|
||||
*
|
||||
* 为什么必须降尺寸:Web 验收把照片作为 **dataURL 内联**在提交体里(`POST /inspection/submit`),
|
||||
* 而全局 `express.json({ limit: '2mb' })` ⇒ 原图不缩 + 质量 0.92 时,一张 5MB 原图可达 4~6MB,
|
||||
* 直接 413「上传失败」(同族先例见 docs/design/20260921-quality-report-upload-multer-channel.md)。
|
||||
*/
|
||||
export const INSPECTION_PHOTO_MAX_DIMENSION = 1600;
|
||||
const INSPECTION_PHOTO_JPEG_QUALITY = 0.8;
|
||||
|
||||
export async function loadOrientedCanvasFromFile(file: File): Promise<HTMLCanvasElement> {
|
||||
if (typeof createImageBitmap === 'function') {
|
||||
@@ -101,7 +110,26 @@ export async function renderInspectionPhotoWithWatermark(
|
||||
file: File,
|
||||
meta: { orderCode?: string; branchName?: string }
|
||||
): Promise<string> {
|
||||
const canvas = await loadOrientedCanvasFromFile(file);
|
||||
const source = await loadOrientedCanvasFromFile(file);
|
||||
/**
|
||||
* ⚠️ 顺序:**先降尺寸、再画水印**。
|
||||
* 若先画水印再缩,水印字会被一起缩小到不可读;降尺寸后画,水印相对更清晰。
|
||||
*/
|
||||
const maxSide = Math.max(source.width, source.height);
|
||||
const scale =
|
||||
maxSide > INSPECTION_PHOTO_MAX_DIMENSION ? INSPECTION_PHOTO_MAX_DIMENSION / maxSide : 1;
|
||||
let canvas = source;
|
||||
if (scale < 1) {
|
||||
const resized = document.createElement('canvas');
|
||||
resized.width = Math.max(1, Math.round(source.width * scale));
|
||||
resized.height = Math.max(1, Math.round(source.height * scale));
|
||||
const resizedContext = resized.getContext('2d');
|
||||
if (!resizedContext) {
|
||||
throw new Error('浏览器不支持图片处理');
|
||||
}
|
||||
resizedContext.drawImage(source, 0, 0, resized.width, resized.height);
|
||||
canvas = resized;
|
||||
}
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) {
|
||||
throw new Error('浏览器不支持图片处理');
|
||||
|
||||
Reference in New Issue
Block a user