feat(库存): 批次报告上传匹配 + 库存修改扩展 + 入库收尾
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

入库批次报告(独立表,隔离于 quality_reports):
- 上传图/PDF → OCR → 按「商品名 + 生产日期」匹配入库批次 → 人工确认落关联
- 库存列表加「批次报告」列,缺报告时标红商品名;未命中可手动选批次

库存管理「修改」扩展:批次属性加「生产日期」;区域/有效期/成本价 +
商品档案(分类/规格/单位/产地)

独立入库:备注区分 Web/小程序;生产日期多格式容错;/units 空时回退模板字典

修复:
- 库存列表日期差一天(date 出参统一 YYYY-MM-DD,避免回写日期逐次前移)
- OCR 提示词不再把检验项目当品名
This commit is contained in:
雨天
2026-10-11 12:50:30 +08:00
parent 07503b2658
commit 71dfe78f2a
20 changed files with 2776 additions and 29 deletions
@@ -12,7 +12,7 @@
> `assistantSessionStore`、`llmTypes` …被 `parse`/`invoice` 等关键词误捞);
> · **真正调用 LLM 出口的文件 = 11 个**(`grep -rlE "from '(./|\.\./mcp/)(llmService|arkService|llmChatWithTools)'" --include=*.ts server/src/services/`);
> · `server/src/services/` 全部 `.ts` = **326 个**。
> ⇒ **引用时必须带口径**。本表登记的 23 个 AI 功能,是按"用户可见能力"归并后的结果(一个服务可承载多个功能)。
> ⇒ **引用时必须带口径**。本表登记的 29 个 AI 功能,是按"用户可见能力"归并后的结果(一个服务可承载多个功能)。
>
> 另有
> `grep -rln "goldenSet\|golden_set\|金标\|评测集\|benchmark"` **零命中**。
@@ -79,6 +79,7 @@
| AI-26 | 其他成本付款凭证 OCR(支付金额/付款人) | `POST /cost/free-cost/payment-vouchers/extract` | `server/src/services/freeCostPaymentVoucherService.ts` | 待补(金额命中率:AI 金额与人工确认金额一致率) | 待补(分母 = 财务实际上传的付款凭证张数) | 待补 + 负责人 | 识别失败/无金额 → 标「需手填金额」由人工补,不阻断同批其它张 | **不存在**(解析出口暂未记录 usage) |
| AI-27 | 小程序拍照入库:识别商品的型号规格/厂家/品牌(提交时经 `archive` 回写档案) | `POST /mobile/inventory/stock-in`;识别入口 `POST /mobile/inventory/recognize-catalog` | `server/src/services/weighStationService.ts` | 待补(字段命中率:人工确认后提交的 `spec`/`brand`/`manufacturer` 与识别原值一致率) | 待补(分母 = 本流程实际发生的识别调用次数,即 `weigh.recognize.catalog_inbound` 出口调用数) | 待补 + 负责人 | 识别失败或未配置多模态 → 返回 `match=none`,表单转全手填(品名/规格/品牌/厂家/数量/成本价均可输入);识别成功也不覆盖人工已填值 | **不存在**(解析出口暂未记录 usage;本功能只回写**人工编辑过**的字段,未编辑的识别值不落库) |
| AI-28 | 多商品入库识别(送货单 / 实物堆,一次多行 → 人工审核 → 批量入库;含**单位/分类** AI 预填) | `POST /mobile/inventory/recognize-lines` | `server/src/services/stockInboundBatchService.ts` | 待补(品名命中率:人工确认后的行品名与识别原值一致率;分类命中率:人工保留的 AI 分类占已预填行比例) | 待补(分母 = 本流程实际发生的识别次数以及识别出的商品**行数**) | 待补 + 负责人 | 识别失败或未配置多模态 → 返回空行,界面转全手工(手动加行,品名/数量/成本价/分类均可手填;分类可在行内选择器新建);AI 分类只从已有分类列表选、服务端按列表校验,自造编码丢弃 | **不存在**(解析出口暂未记录 usage) |
| AI-29 | 入库批次报告 OCR 解析(仓库上传图/PDF → 商品名/生产日期 → 匹配入库批次;独立于 quality_reports) | `POST /api/workflow/inventory/batch-reports` | `server/src/services/inventoryBatchReportService.ts` | 待补(品名/生产日期命中率:人工确认的入库批次与报告识别原值一致率) | 待补(分母 = 仓库实际上传的批次报告份数 × 每份识别出的商品行数;负责人:待定) | 待补 + 负责人 | 识别失败或未配置多模态 → 只存文件、状态「待确认」,界面转人工手选入库批次(可多选),不阻断;匹配仅给建议,未经人工确认不落关联行 | **不存在**(复用 `quality.report.meta` 解析出口,暂未记录 usage) |
> **AI-19 是这张表里唯一填得出来的行** —— 而它是 R5 逼出来的(原文写「比对人工录单准确率」,无阈值、无法判 go/no-go)。
> 其余 18 行的"待补"就是本表要暴露的事实:**存量 AI 全部无门槛**。
@@ -90,6 +90,7 @@
3. 汇总为 `bulkStockInbound` 的 `rows`(F2),一次调用;
4. 返回逐行结果(`ok / new_batch / accumulated / failed + error`)。
- **校验**:`qty > 0` 缺失行**不允许提交**(前端标红拦;服务端同样拒);成本价可空(转 `null` → 写 0,F6)。
- **库存流水备注按入口区分**(`bulkStockInbound` 新增可选 `remark`,缺省为 Excel 文案):小程序批量写 `独立入库(小程序)`、Web 批量写 `独立入库(Web)`、Excel 批量导入仍为 `Excel 批量导入库存`。
### 3.4 成本价与数量(口径⑤)+ 生产日期/保质期
@@ -0,0 +1,84 @@
# 库存管理「修改」弹窗:扩展批次属性与商品档案编辑
> 立项 2026-10-28。开发者当轮口径:库存列表行内「修改」**不止能设可用库存**,还要能编辑
> **区域编号 / 分类 / 产地 / 规格 / 保质期 / 成本价 / 单位**。「地址」经确认指**商品产地**。
>
> 追加 2026-10-29:批次属性**增加「生产日期」`production_date`**(与有效期同类,批次级)。
## 1. 目标 / 非目标
- 目标:`库存管理` 页行内「修改」由「只改可用数量」扩展为**一处改完**:批次属性 + 商品档案字段。
- 非目标:不改动 `POST /inventory/adjust` 的既有冻结语义(双日志、备注必填、预留释放回补、「已拣未出库允许调高」)。
## 2. 改前实测事实
| # | 事实 | 证据 |
|---|---|---|
| F1 | 现「修改」= **库存调整**,只改 `available_qty`(+备注必填) | `src/pages/inventory/InventoryManagement.tsx` `openAdjustModal`;`adjustInventoryAvailableQty` |
| F2 | `inventory` 行是**批次级**:含 `storage_zone` / `expiry_date` / `cost_price` | `information_schema.columns` |
| F3 | 分类/规格/单位 在**商品真源 `product_catalog`**;单向触发器 `trg_sync_product_catalog_to_legacy` 同步 `skus` | `20260920-product-freeze.md` §9 |
| F4 | **`product_catalog` 无 `origin` 列**;`origin` 只在 `skus` | `information_schema.columns`;`20261012-拍照入库…档案回写.md` §2.1 |
| F5 | 列表接口未回 `sk.spec/unit/origin`,前端拿不到商品现值 | `inventoryQueryService.listInventoryForManagement` |
## 3. 设计
### 3.1 字段分层
| 字段 | 层级 | 写入 |
|---|---|---|
| 可用数量 | 批次 | `POST /inventory/adjust`(不动) |
| 区域编号 `storage_zone` | 批次 | `inventory.storage_zone` |
| 有效期 `expiry_date` | 批次 | `inventory.expiry_date` |
| 生产日期 `production_date` | 批次 | `inventory.production_date` |
| 成本价 `cost_price` | 批次 | `inventory.cost_price` |
| 分类 `category_code` | 商品 | `product_catalog.parent_code` + `skus.category_code` |
| 规格 `spec` | 商品 | `product_catalog.spec` + `skus.spec` |
| 单位 `unit` | 商品 | `product_catalog.unit` + `skus.unit` |
| 产地 `origin` | 商品 | **仅** `skus.origin`(`product_catalog` 无该列) |
- 商品级字段写**商品真源 `product_catalog`**(触发同步 `skus`);`origin` 直写 `skus`(先例 `skuProvisioningService`)。
- 商品级字段改的是**商品本身**,会作用于该商品**所有批次**(前端明示提示)。
### 3.2 成本价口径(开发者选 A)
**只改 `inventory.cost_price`,不回冲已入账的持有成本流水**——之后的货值/新批次用新成本,历史持有成本保持原样。
### 3.3 接口
`POST /api/workflow/inventory/batch-update`
- 入参:`{ inventory_id, remark, operating_branch_code?, storage_zone?, expiry_date?, cost_price?, production_date?, category_code?, spec?, unit?, origin? }`(只传要改的字段)。
- 权限:批次字段需 `inventory_adjust`;**含商品字段时另需 `product_manage`**。
- 行为:`FOR UPDATE` 锁行(校验分公司)→ 只改发生变化的字段 → 写审计 `operation_logs`(`operation_type=inventory_batch_edit`,`actionCategory=inventory`)。
- **不写 `inventory_logs`**(那是「数量流水」;属性编辑走审计,避免 0 变动的假流水,也避免新增类型动到前端三语文案)。
- 有效期格式 `YYYY-MM-DD`,空串 → `NULL`。**生产日期同格式、同口径**(批次级元数据,不参与 FIFO/成本/预留计算)。
### 3.5 日期列出参口径(修复:生产日期显示差一天)
- 现象:把生产日期设为 `2026-05-01`,列表与修改弹窗都显示 `2026-04-30`。
- 根因:pg 的 `date` 列返回**本地午夜** JS `Date`,经 `res.json`(`toISOString()`)变成 UTC ISO
(+08:00 下为前一天 16:00Z);前端 `.slice(0,10)` 取到 **前一天**。
更严重的是弹窗回显也走同一 `.slice(0,10)`,**每次保存再写回会把日期逐次前移**。
- 实测:库内 `production_date::text = '2026-05-01'`(**写入本就是对的**)。
- 修复(后端为源):`listInventoryForManagement` 行映射把 `production_date` / `expiry_date`
统一出 **`YYYY-MM-DD`**(本地日历日);前端 `.slice(0,10)` 变为无操作。
同步修正 `inventoryBatchEditService` 变更比对里 `String(Date).slice(0,10)` 的错误格式化。
- 影响面:同一接口的效期显示/「剩 N 天」一并变准(`getExpiryDays` 本就按 `YYYY-MM-DD` 解析)。
## 4. 迁移清单
- **无数据库迁移**:不新增表/列。
## 5. 验收标准
- 只改数量:与改前行为一致(走 `adjust`,双日志、备注必填、预留释放照旧)。
- 只改批次属性(区域/生产日期/有效期/成本价):`inventory` 行更新,`operation_logs` 留痕;**不动任何持有成本流水**。
- 改商品字段(分类/规格/单位/产地):`product_catalog`/`skus` 更新,该商品所有批次视图同步。
- 无改动保存 → 提示「没有改动」,不发请求。
- 缺 `product_manage` 的账号改商品字段 → 403。
## 6. 风险 / 冻结口径
- **库存管理冻结**:未改 `adjust` 语义;新增的是独立的属性编辑通道,仅写审计、不写数量流水。
- **商品主数据冻结**:以 `product_catalog` 为写入源,未加反向触发器;`origin` 因列不在真源而直写 `skus`(与既有档案回写先例一致)。
- **财务冻结**:成本价按 A 口径——**不触账**;如需回冲需另立财务流程。
@@ -0,0 +1,142 @@
# 入库批次报告:上传 → 解析 → 按「商品名 + 生产日期」匹配入库批次
> 立项 2026-10-29。开发者需求:仓库管理加「上传批次报告」按钮,上传**图片/PDF** 解析内容,
> 按**商品名 + 生产日期**匹配我们的**入库批次**;该报告**后续要交给主系统**。
>
> **本轮先出设计、不写代码**(设计先行)。核心原则:**隔离**——不碰 `quality_reports`、不写 `inventory`、
> 不进验收闸门、暂不推主系统。风险初评见 §6。
## 1. 目标 / 非目标
- 目标:仓库管理可上传批次报告(图/PDF)→ 解析 → **给出**与入库批次的匹配**建议** → 人工确认 → 落库留档。
- 非目标(本期**不做**):
1. 不改 `quality_reports` 的既有语义与其**验收报告硬闸**;
2. **不写 `inventory`**(只读用于匹配);
3. **不自动推主系统**(契约未定,另立批次);
4. 不做"报告不齐则拦发车/入库"之类新闸门。
## 2. 改前实测事实(先立事实)
| # | 事实 | 证据 |
|---|---|---|
| F1 | 已有 `quality_reports` 表(36 列),含 `batch_no` / `sku_code` / `product_name` / **`produced_at`(生产日期)** / `testing_org` / `valid_from/to` / `ai_raw` / `linked_sku_codes` / `share_mode` / `share_key` | `information_schema.columns`(`tenant_sup35143228`) |
| F2 | 已有报告 OCR(图 + PDF):提示词 `quality.report.meta` 抽 `product_names` / `product_name` / **`produced_at`** / `testing_org` / `valid_from/to`;`quality.report.dates` 抽日期 | `server/src/prompts/defaults.ts`(L281/L293);`qualityReportService.ts`(`callWithImage`/`callWithFile`) |
| F3 | **验收有「报告齐全」硬闸**:`assertQualityReportHardGate` 在验收入库时调用;覆盖按 `share_mode`/`share_key` + sku/分类算;`shareModeForReportType('batch')` = `leaf_category`;**独立入库豁免该闸** | `inspectionComplianceService.ts:1348`;`qualityReportService.ts:60` |
| F4 | 报告覆盖/分享口径是**商品冻结**里点名的权威(`quality_reports.share_mode`/`share_key`) | `.cursor/rules/product-freeze.mdc` §口径 |
| F5 | `inventory.production_date` **不是每批都有**(只有"独立批量入库"链路写);同一 SKU + 生产日期可能对应**多批次** | `stockInboundService.ts` 写 `production_date`;`inventory` 唯一键是 `(sku_code, batch_no)` |
| F6 | **主系统对接清单里没有"报告/批次"任何需求** | `docs/给主系统AI的对接改造清单.md`(无匹配) |
| F7 | 【平台冻结】新业务表**必须**写进 `public.tenant_business_tables()`,迁移期有断言守卫 | `.cursor/rules/platform-freeze.mdc` |
| F8 | 报告文件走对象存储,既有目录 `quality-reports/` | `ARCHITECTURE.md` 存储桶清单 |
## 3. 设计(隔离版)
### 3.1 数据(**新建独立表,不碰 `quality_reports`**)
- `inventory_batch_reports`:一份报告一行
- `id`、`branch_code`、`report_no`(报告编号,可空)、`report_type`(本表自有枚举,如 `batch`)、
- `file_paths text[]`、`source_party`(上传方=仓库)、
- OCR:`ai_raw jsonb`、`ai_parsed_at`、`product_names text[]`、`testing_org`、`produced_at date`(报告级生产日期,可空)、
- `status smallint`(10 待确认 / 30 已确认)、`uploaded_by`、`uploaded_at`。
- `inventory_batch_report_matches`:报告 ↔ 入库批次 的**确认后**关联行
- `id`、`report_id`、`inventory_id`、`sku_code`、`batch_no`、`production_date`、`match_source`(`auto`/`manual`)、`confirmed_by`、`confirmed_at`。
- **导入即隔离**:以上两表**不参与** `quality_reports` 的覆盖/分享计算,**不影响验收闸门**。
### 3.2 上传与解析
- 入口:仓库管理(`/inventory`)页头加「**上传批次报告**」→ 选图片或 PDF(复用现有存储上传 `quality-reports/` 桶)。
- 解析:**复用** `quality.report.meta` OCR(已登记 AI 门槛),抽 品名一览 + 生产日期 + 检测机构(+ 报告号)。
- 图片走 `callWithImage`,PDF 走 `callWithFile`(既有能力)。
- OCR 结果**先落 `ai_raw` 与解析字段**,供人工校对;**解析失败可只存文件**(降级不阻断)。
- **提示词强化(2026-10-30)**:`quality.report.meta`(`server/src/prompts/defaults.ts`)明确
**不得把检验/检测项目、指标名称当成品名**(色泽/滋味/气味/状态/二氧化硫残留量/铝的残留量/柠檬黄…),
`product_names` 只填被检商品;只有检验项目时填空数组。
实测同一份「豆腐皮」PDF:改前抽出 7 个检验项目 + 豆腐皮(共 8),改后只出 `["豆腐皮"]`。
(该提示词为 `version=1 / published` → `ensureDefaultsSeeded` 会把代码默认值同步进租户库。)
### 3.3 匹配(**建议 + 人工确认**,不自动定案)
- 匹配键:**商品名 + 生产日期**。
- 商品名:优先 `skus.sku_name` 精确(去空格);未命中再走别名/包含(**标为"疑似"**,需人工确认)。
- 生产日期:`inventory.production_date` = 报告 `produced_at`。
- 结果三态展示:**唯一命中 / 多命中(给候选让人选)/ 未命中**。
- **未命中可手选**:每个品名旁提供「**手动选择批次**」——按商品名/批次号搜索本分公司入库批次(走 `listInventoryManagementApi`,防抖)并勾选;也可用于改选自动匹配的批次。
- **只有人工确认后**才写 `inventory_batch_report_matches`;确认动作写审计。
### 3.4 与既有链路的边界(**本期硬边界**)
- **不改 `inventory` 任何写入**(`inventory` 只读参与匹配)→ 不触【库存管理冻结】。
- **不改 `quality_reports` 的写入/覆盖/闸门**→ 不触【商品主数据冻结】的分享口径、不影响验收。
- **不推主系统**(F6)。
### 3.5 权限 / 归属
- 上传/确认需 `inventory_manage`(或既有仓管角色);文件与记录按 `branch_code` 隔离(RLS)。
- 写 `operation_logs` 审计(上传、确认匹配)。
### 3.6 错误与降级
| 情形 | 处理 |
|---|---|
| OCR 未配置/失败 | 只存文件、状态"待人工补录",不阻断 |
| 报告无 `produced_at` | 只能按商品名给"疑似"候选,必须人工确认 |
| 同键多批次 | 列全部候选,人工勾选(可多选) |
| 商品名对不上 | 明确展示"未命中",允许人工手选批次 |
### 3.7 库存列表标注「缺少批次报告」
- 仓库管理「库存查询」列表:
- **商品名标红**(与"预留超过可用"同色系);
- 新增一列「**批次报告**」:已有确认关联 → `已有`;否则 → 红色 `缺少批次报告`。
- 判据:该 `inventory` 行是否存在 `inventory_batch_report_matches` 行(即**已人工确认**的报告关联)。
- 实现:列表查询(`inventoryQueryService.listInventoryForManagement`)加一个只读列
`EXISTS (SELECT 1 FROM inventory_batch_report_matches m WHERE m.inventory_id = inv.id) AS has_batch_report`,
走 `idx_inventory_batch_report_matches_inv`。**不改任何写入**。
- 列可排序性:不参与排序(与"预留/可调配"同款非排序列)。
## 4. 迁移清单
- 新增两表 `inventory_batch_reports` / `inventory_batch_report_matches`(含索引、RLS)。
- **同提交**把两张表写进 `public.tenant_business_tables()`(F7,否则迁移断言中断)。
- 迁移编号先 `ls migrations/ | sort` 取空号(远端与他人提交频繁,防撞号)。
## 5. 验收标准
- 仓库管理能上传图/PDF 并解析出 品名 + 生产日期(失败可只存文件)。
- 匹配按「商品名 + 生产日期」给出 唯一/多/未命中 三态;**未经人工确认不落关联**。
- **`inventory` 行、`quality_reports` 行在全程不被本功能写入**(可用 DB 触发/日志核验)。
- 验收报告硬闸行为与改前**逐字一致**(回归:有订单验收入库仍按旧口径判定)。
- 新表已进 `tenant_business_tables()`;跨分公司不可见。
- **库存查询列表**:缺报告的行商品名标红,且「批次报告」列显示 `缺少批次报告`;已有确认关联的显示 `已有`。
## 6. 风险与冻结口径(初评)
| # | 风险 | 级别 | 本设计的规避 |
|---|---|---|---|
| A | 影响验收报告闸门 | 中→高 | **不复用 `quality_reports`**,独立表、不进覆盖计算 |
| B | 触库存冻结 | 中 | **不写 `inventory`**,只读匹配 |
| C | 匹配不准 | 中 | **建议 + 人工确认**;三态展示;多命中给候选 |
| D | 主系统对接 | 高 | **本期不推**;契约另立(§7) |
| E | 新表漏登记 | 中 | 同提交进 `tenant_business_tables()` |
| F | AI 计量 | 低 | **复用**已登记的 `quality.report.meta`,不新增提示词 |
## 7. 给主系统(后续批次,**契约待定**)
- 本期**不实现**。待与主系统约定:推送**通道**(复用既有 webhook?新接口?)、**事件名与字段**、
**幂等键**(建议 `report_no` 或 `batch_no+sku`)、**失败重试与开关(默认关)**、以及"报告是否要落主系统某表"。
- 契约敲定后**另开一批**,并同步更新 `docs/给主系统AI的对接改造清单.md`。
## 8. 验证(实现后回填)
- **后端 tsc**:`server && npx tsc --noEmit -p tsconfig.json` ✅ 通过。
- **Web**:`npm run typecheck` ✅;`npm run build` ✅(仅既有体积告警)。
- **迁移**:`npm run db:migrate` 应用 `20261033_inventory_batch_reports.sql` ✅;
两表落在 `tenant_template` / `tenant_br001` / `tenant_br002` / `tenant_sup35143228` / `tenant_sup37831443` / `legacy_public`;
`public.tenant_business_tables()` 已含两表,`assert_tenant_template_matches_business_tables()` 未中断。
- **真库往返(租户 `tenant_sup35143228`)**:直插一份报告 → `getInventoryBatchReport` 给出候选(同一品名 + 生产日期命中 **4 条** → 状态 `multi`,印证 §6 风险的「多命中」)
→ `confirmInventoryBatchReportMatches` 写入 1 条关联、报告置 `status=30` → `listInventoryBatchReports` 可见。测试数据已清理。
- **门禁九闸**:`check-structure` / `check.py`(155/155) / `check-refs` / `check-migrations`(348 迁移 0 断裂) /
`check-self-test`(30/30) / `check-ai-exits` / `check-env-coverage` ✅;
`check-ai-thresholds` 首次 **红**(新消费方 `inventoryBatchReportService.ts` 未登记)→ 已补 **AI-29** 后转 ✅。
- **AI 登记**:§2 说「复用 `quality.report.meta`、不新增提示词」——仍成立;但**新增消费方文件**按闸门口径补了一行 **AI-29**
(见 `docs/design/20260929-AI门槛与计量登记表.md`)。`check-ai-cost.py` 保持库内既有红(未修)。
- **未做的验证**:真实图片/PDF 的 OCR 全链路(需经 UI 走 `/storage/quality-reports/upload` 上传真实文件),留待人工点测。
@@ -0,0 +1,257 @@
-- 入库批次报告:仓库上传(图片/PDF)→ OCR 解析 → 按「商品名 + 生产日期」匹配入库批次
-- 设计:docs/design/20261029-入库批次报告上传与匹配.md
--
-- 隔离边界(勿破):
-- 1) **不复用 `quality_reports`**:避免进入验收「报告齐全」硬闸的覆盖计算
-- (见 .cursor/rules/product-freeze.mdc 的分享口径);
-- 2) **不写 `inventory`**:库存管理冻结;本功能只读 `inventory` 做匹配;
-- 3) 本期**不推主系统**(对接契约未定)。
--
-- 两张表:
-- inventory_batch_reports 一份报告一行(文件 + OCR 结果)
-- inventory_batch_report_matches 报告 ↔ 入库批次 的「确认后」关联行
--
-- 新增业务表四步(见 docs/design/20260915-tenant-table-list-guard.md):
-- ① 建表(tenant_template + 各租户 schema,本文件 DO 块)
-- ② 同步名单 public.tenant_business_tables()(本文件尾部)
-- ③ ensure_tenant_schemas_match_template() 给已有分公司补建
-- ④ assert_tenant_template_matches_business_tables() 断言(漏登记即中断迁移)
DO $$
DECLARE
sch text;
BEGIN
FOR sch IN
SELECT nspname
FROM pg_namespace
WHERE nspname IN ('public', 'legacy_public', 'tenant_template')
OR nspname LIKE 'tenant_%'
LOOP
-- 只在「真实租户业务 schema」建表(锚点 = inventory),与 20261008 同口径
IF to_regclass(format('%I.inventory', sch)) IS NULL THEN
CONTINUE;
END IF;
EXECUTE format(
'CREATE TABLE IF NOT EXISTS %I.inventory_batch_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
branch_code VARCHAR(50) NOT NULL,
report_no VARCHAR(100),
report_type VARCHAR(32) NOT NULL DEFAULT ''batch'',
file_paths TEXT[] NOT NULL DEFAULT ''{}''::text[],
source_party VARCHAR(20) NOT NULL DEFAULT ''warehouse'',
product_names TEXT[] NOT NULL DEFAULT ''{}''::text[],
produced_at DATE,
testing_org TEXT,
ai_raw JSONB,
ai_parsed_at TIMESTAMPTZ,
status SMALLINT NOT NULL DEFAULT 10,
uploaded_by UUID,
uploaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT inventory_batch_reports_status_chk
CHECK (status IN (10, 30))
)',
sch
);
EXECUTE format(
'COMMENT ON TABLE %I.inventory_batch_reports IS %L',
sch,
'入库批次报告(仓库上传图/PDF,OCR 解析;隔离于 quality_reports)'
);
EXECUTE format(
'CREATE INDEX IF NOT EXISTS idx_inventory_batch_reports_branch
ON %I.inventory_batch_reports (branch_code, uploaded_at DESC)',
sch
);
-- 同分公司内报告编号唯一(编号可空,空值不参与唯一)
EXECUTE format(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_inventory_batch_reports_no_uq
ON %I.inventory_batch_reports (branch_code, report_no)
WHERE report_no IS NOT NULL',
sch
);
EXECUTE format(
'CREATE TABLE IF NOT EXISTS %I.inventory_batch_report_matches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
report_id UUID NOT NULL,
inventory_id UUID NOT NULL,
sku_code VARCHAR(64),
product_name TEXT,
batch_no VARCHAR(100),
production_date DATE,
match_source VARCHAR(10) NOT NULL DEFAULT ''auto'',
confirmed_by UUID,
confirmed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT inventory_batch_report_matches_source_chk
CHECK (match_source IN (''auto'', ''manual''))
)',
sch
);
EXECUTE format(
'COMMENT ON TABLE %I.inventory_batch_report_matches IS %L',
sch,
'报告 ↔ 入库批次 确认后的关联行(人工确认才写)'
);
EXECUTE format(
'CREATE INDEX IF NOT EXISTS idx_inventory_batch_report_matches_report
ON %I.inventory_batch_report_matches (report_id)',
sch
);
EXECUTE format(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_inventory_batch_report_matches_uq
ON %I.inventory_batch_report_matches (report_id, inventory_id)',
sch
);
EXECUTE format(
'CREATE INDEX IF NOT EXISTS idx_inventory_batch_report_matches_inv
ON %I.inventory_batch_report_matches (inventory_id)',
sch
);
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN
BEGIN
EXECUTE format(
'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.inventory_batch_reports TO canteen_app_rls',
sch
);
EXECUTE format(
'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.inventory_batch_report_matches TO canteen_app_rls',
sch
);
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'skip grant on %.inventory_batch_reports*: %', sch, SQLERRM;
END;
END IF;
END LOOP;
END $$;
CREATE OR REPLACE FUNCTION public.tenant_business_tables()
RETURNS TEXT[]
LANGUAGE sql
IMMUTABLE
AS $$
SELECT ARRAY[
'after_sale_returns',
'after_sales',
'ai_prompt_overrides',
'ai_prompt_revisions',
'ai_prompt_templates',
'alias_recognition_logs',
'allocation_tasks',
'assistant_conversations',
'assistant_messages',
'assistant_turns',
'bid_awards',
'bid_invitations',
'bid_prices',
'bid_quotes',
'bid_round_items',
'bid_rounds',
'categories',
'cost_adjustments',
'cost_details',
'customer_alias_stats',
'customer_delivery_assignments',
'customer_portal_users',
'customer_processing_aliases',
'customer_quote_sheet_customers',
'customer_quote_sheet_items',
'customer_quote_sheets',
'customer_quote_versions',
'customer_recipients',
'customer_sku_aliases',
'customer_sku_remarks',
'customer_skus',
'customer_statements',
'customers',
'delivery_location_history',
'delivery_person_locations',
'delivery_person_users',
'delivery_persons',
'delivery_schedules',
'delivery_signatures',
'delivery_tasks',
'exception_tickets',
'fixed_costs',
'free_cost_invoice_links',
'free_cost_invoices',
'free_cost_payment_vouchers',
'import_mapping_memories',
'inspection_loss_confirmations',
'inspection_photo_archive_entries',
'inspection_photo_archives',
'inspection_returns',
'inspection_review_logs',
'inspections',
'inventory',
'inventory_batch_report_matches',
'inventory_batch_reports',
'inventory_logs',
'inventory_reservations',
'invoice_statement_links',
'invoices',
'market_compare_exclusions',
'market_external_catalog',
'market_price_history',
'market_price_indices',
'market_prices',
'market_sku_external_bindings',
'notifications',
'operation_logs',
'order_allocation_batches',
'order_item_fulfillments',
'order_item_returns',
'order_items',
'orders',
'parse_session_items',
'parse_sessions',
'picking_assign_rules',
'picking_containers',
'picking_items',
'picking_scan_logs',
'picking_tasks',
'price_invert_events',
'print_jobs',
'processing_demand_items',
'processing_demand_picks',
'processing_logs',
'processing_tasks',
'product_catalog',
'product_substitutions',
'purchase_orders',
'purchaser_users',
'quality_report_prep_links',
'quality_reports',
'seasonal_recommendations',
'self_purchase_stock_inbounds',
'sign_records',
'sku_direct_delivery_customers',
'sku_suppliers',
'skus',
'smart_classification_rules',
'statement_disputes',
'statement_lines',
'statement_payments',
'supplier_categories',
'supplier_prep_amend_requests',
'supplier_preparations',
'supplier_price_agreements',
'supplier_rating_snapshots',
'supplier_statements',
'supplier_users',
'suppliers',
'system_configs',
'unit_conversions',
'user_preferences',
'voice_recognition_logs',
'warehouse_locations',
'warehouses',
'weigh_devices'
]
$$;
SELECT public.ensure_tenant_schemas_match_template();
SELECT public.assert_tenant_template_matches_business_tables();
@@ -11,6 +11,12 @@ import {
setStockCoverFromInventoryConfig,
} from '../../../services/inventoryOps';
import { adjustInventoryAvailableQty } from '../../../services/inventoryAdjustService';
import {
createInventoryBatchReports,
listInventoryBatchReports,
getInventoryBatchReport,
confirmInventoryBatchReportMatches,
} from '../../../services/inventoryBatchReportService';
function requireInventoryConfigAccess(ctx: Awaited<ReturnType<typeof getWorkflowCtx>>) {
requireWorkflowPermission(ctx, ['inventory_manage']);
@@ -351,6 +357,7 @@ export function mountInventoryWorkflowRoutes(router: Router): void {
branchCode,
operatorId: req.userId || null,
rows: Array.isArray(req.body?.rows) ? req.body.rows : [],
remark: '独立入库(Web)',
});
return res.json({ success: true, data });
} catch (error: any) {
@@ -361,6 +368,157 @@ export function mountInventoryWorkflowRoutes(router: Router): void {
}
});
/**
* 库存管理「修改」——批次属性(区域/保质期/成本价)+ 商品档案(分类/规格/单位/产地)。
* 批次字段需 inventory_adjust;含商品字段时另需 product_manage。数量仍走 /inventory/adjust。
*/
router.post('/inventory/batch-update', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['inventory_adjust']);
const body = req.body || {};
const hasProductField = ['category_code', 'spec', 'unit', 'origin'].some(
(k) => body[k] !== undefined
);
if (hasProductField) requireWorkflowPermission(ctx, ['product_manage']);
const branchCode = resolveBranch(req, ctx!, body.operating_branch_code);
const { updateInventoryBatchAttributes } = await import(
'../../../services/inventoryBatchEditService'
);
const data = await updateInventoryBatchAttributes({
inventoryId: String(body.inventory_id || ''),
branchCode,
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,
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,
spec: 'spec' in body ? body.spec : undefined,
unit: 'unit' in body ? body.unit : undefined,
origin: 'origin' in body ? body.origin : undefined,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '修改库存批次失败',
});
}
});
/**
* 上传批次报告(图/PDF):解析内容并按「商品名 + 生产日期」给出匹配建议。
* 独立于 quality_reports;不写 inventory。需 inventory_manage。
*/
router.post('/inventory/batch-reports', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['inventory_manage']);
const branchCode = resolveBranch(req, ctx!, req.body?.operating_branch_code);
const files = Array.isArray(req.body?.files)
? req.body.files.map(String)
: req.body?.file
? [String(req.body.file)]
: [];
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) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '上传批次报告失败',
});
}
});
/** 批次报告列表(含已确认关联,不含候选) */
router.get('/inventory/batch-reports', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['inventory_manage']);
const queryBranch = req.query?.operating_branch_code;
const branchCode = resolveBranch(
req,
ctx!,
typeof queryBranch === 'string' ? queryBranch : undefined
);
const data = await listInventoryBatchReports({
branchCode,
limit: Number(req.query?.limit) || 50,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '加载批次报告失败',
});
}
});
/** 单份批次报告(带匹配候选,供人工确认) */
router.get('/inventory/batch-reports/:id', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['inventory_manage']);
const queryBranch = req.query?.operating_branch_code;
const branchCode = resolveBranch(
req,
ctx!,
typeof queryBranch === 'string' ? queryBranch : undefined
);
const data = await getInventoryBatchReport({
reportId: String(req.params.id || ''),
branchCode,
});
if (!data) {
return res.status(404).json({ error: 'not_found', error_description: '报告不存在' });
}
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '加载批次报告失败',
});
}
});
/** 人工确认批次报告的匹配(替换关联行并置为已确认) */
router.post(
'/inventory/batch-reports/:id/confirm',
authMiddleware,
async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['inventory_manage']);
const branchCode = resolveBranch(req, ctx!, req.body?.operating_branch_code);
const matches = Array.isArray(req.body?.matches)
? req.body.matches.map((m: any) => ({
inventoryId: String(m?.inventory_id || ''),
productName: m?.product_name ? String(m.product_name) : null,
}))
: [];
const data = await confirmInventoryBatchReportMatches({
reportId: String(req.params.id || ''),
branchCode,
operatorId: req.userId || null,
matches,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '确认批次报告失败',
});
}
}
);
/** 按批次调整可用库存(需 inventory_adjust) */
router.post('/inventory/adjust', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
@@ -9,6 +9,7 @@ import {
listUnitConversions,
updateUnitConversion,
} from '../../../services/unitOps';
import { listUnitConversionsForMobile } from '../../../services/unitDictionaryService';
function requireUnitManageAccess(ctx: Awaited<ReturnType<typeof getWorkflowCtx>>) {
requireWorkflowPermission(ctx, ['sku_manage', 'product_manage']);
@@ -30,7 +31,9 @@ export function mountUnitWorkflowRoutes(router: Router): void {
'inventory_manage',
'inspection_manage',
]);
const data = await listUnitConversions({ activeOnly });
let data = await listUnitConversions({ activeOnly });
// 本租户单位表为空时,回退模板/预置字典(与小程序单位字典同款回退),避免下拉全空
if (!data.length) data = await listUnitConversionsForMobile();
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
+2 -2
View File
@@ -298,7 +298,7 @@ damage_types 只能从:挤压、腐烂、规格不符、污染、其他 中选
systemTemplate: `你是食品检验/检疫/农残报告 OCR 助手。只根据图中可见文字抄录,禁止猜测或编造 SKU 编码。
核心优先抽:
1) tested_at:检验/检测/出证日期(YYYY-MM-DD)。表头「检测日期」优先于「配送日期」。
2) product_names:报告中出现的全部样品/品名(农残表左右两列都要抄;去序号、去「合格/不合格」)。没有列表则只填一个品名或空数组。
2) product_names:**只填被检的商品/样品名称**(如「豆腐皮」「土豆」)。**绝不把检验/检测项目、指标名称当成品名** —— 包括但不限于:色泽、滋味、气味、状态、组织形态、水分、灰分、酸价、过氧化值、二氧化硫残留量、铅、砷、汞、镉、铝的残留量、菌落总数、大肠菌群、沙门氏菌、柠檬黄及其铝色淀、日落黄、糖精钠、山梨酸、苯甲酸等。农残表左右两列都要抄;去序号、去「合格/不合格」。没有列表则只填一个品名或空数组;**若只有检验项目、找不到商品名,则填空数组 []**。
其它字段:
- product_name:主样品名;有列表时用第一个品名
- produced_at:生产日期(YYYY-MM-DD;仅有年月则填该月1日)
@@ -308,7 +308,7 @@ damage_types 只能从:挤压、腐烂、规格不符、污染、其他 中选
- valid_from / valid_to:有效期起止;若写「有效期N天」则填 valid_days
只输出裸 JSON:
{"product_names":[],"product_name":null|"文本","produced_at":null|"YYYY-MM-DD","testing_org":null|"文本","inspected_org":null|"文本","specification":null|"文本","tested_at":null|"YYYY-MM-DD","valid_from":null|"YYYY-MM-DD","valid_to":null|"YYYY-MM-DD","valid_days":null|数字}
看不清或没有的字段必须为 null;product_names 没有则 []。不要输出抑制率、结论等非核心列。`,
看不清或没有的字段必须为 null;product_names 没有则 []。不要输出抑制率、结论、检验/检测项目等非核心列。`,
variablesSchema: [],
},
{
@@ -235,6 +235,7 @@ router.post('/inventory/stock-in-batch', authMiddleware, async (req: AuthRequest
operatorId: req.userId || null,
rows: Array.isArray(req.body?.rows) ? req.body.rows : [],
common: req.body?.common || null,
remark: '独立入库(小程序)',
});
return res.json({ success: true, data });
} catch (error: any) {
@@ -0,0 +1,293 @@
/**
* 库存管理「修改」——批次属性 + 商品档案字段编辑。
*
* 设计:docs/design/20261028-库存管理修改弹窗扩展批次与商品属性.md
*
* 口径:
* - **批次级**(只影响这一批):`storage_zone` / `expiry_date` / `cost_price`(写 `inventory`)。
* - **商品级**(影响该商品所有批次):`category_code`/`spec`/`unit` 写 **商品真源 `product_catalog`**,
* 由既有单向触发器同步到 `skus`;**`origin` 不在 `product_catalog`**(实测无该列),故直写 `skus.origin`
* (先例:`skuProvisioningService` 的档案回写)。
* - **数量不在此接口**:可用数量仍走 `adjustInventoryAvailableQty`(双日志/预留释放等冻结语义不动)。
* - 成本价按开发者口径 **只改批次成本,不回冲已入账的持有成本流水**。
* - 留痕:写 `operation_logs`(跳 `inventory_logs`,避免与「数量流水」混淆)。
*/
import { pool } from '../db';
import { writeAuditLog } from './auditService';
function trimText(v: unknown): string {
return String(v ?? '').trim();
}
/** pg 的 `date` 返回本地午夜 Date;统一成 'YYYY-MM-DD'(否则变更比对会被 `String(Date)` 弄乱) */
function toDateOnly(v: unknown): string | null {
if (v == null) return null;
if (v instanceof Date) {
if (Number.isNaN(v.getTime())) return null;
const y = v.getFullYear();
const m = String(v.getMonth() + 1).padStart(2, '0');
const d = String(v.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
const s = String(v).trim();
return s ? s.slice(0, 10) : null;
}
/** 'YYYY-MM-DD' → 原样;空串/null → null;其它 → 抛错 */
function normalizeDateOrNull(v: unknown): string | null {
const t = trimText(v);
if (!t) return null;
const m = t.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/);
if (!m) {
throw Object.assign(new Error('日期格式应为 YYYY-MM-DD'), { status: 400, code: 'invalid_date' });
}
return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`;
}
export interface UpdateInventoryBatchInput {
inventoryId: string;
branchCode: string;
operatorId?: string | null;
remark: string;
/** 批次级;`undefined` = 不改 */
storageZone?: string | null;
/** 批次级:'YYYY-MM-DD' 或 ''(清空) */
expiryDate?: string | null;
/** 批次级:'YYYY-MM-DD' 或 ''(清空);不参与 FIFO/成本/预留 */
productionDate?: string | null;
/** 批次级:数字或 null(清空) */
costPrice?: number | null;
/** 商品级;`undefined` = 不改 */
categoryCode?: string | null;
spec?: string | null;
unit?: string | null;
origin?: string | null;
}
export interface UpdateInventoryBatchResult {
id: string;
batch_no: string;
sku_code: string;
changed: string[];
}
export async function updateInventoryBatchAttributes(
input: UpdateInventoryBatchInput
): Promise<UpdateInventoryBatchResult> {
const inventoryId = trimText(input.inventoryId);
const branchCode = trimText(input.branchCode);
const remark = trimText(input.remark);
if (!inventoryId) {
throw Object.assign(new Error('缺少库存记录'), { status: 400, code: 'invalid_request' });
}
if (!branchCode) {
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
}
if (!remark) {
throw Object.assign(new Error('请填写修改备注'), { status: 400, code: 'invalid_request' });
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const locked = await client.query(
`SELECT id, batch_no, sku_code, storage_zone, expiry_date, production_date, cost_price
FROM inventory
WHERE id = $1::uuid AND branch_code = $2
FOR UPDATE`,
[inventoryId, branchCode]
);
if (!locked.rowCount) {
throw Object.assign(new Error('库存记录不存在或不属于当前分公司'), {
status: 404,
code: 'not_found',
});
}
const row = locked.rows[0];
const skuCode = trimText(row.sku_code);
const beforeBatch = {
storage_zone: row.storage_zone == null ? null : String(row.storage_zone),
expiry_date: toDateOnly(row.expiry_date),
production_date: toDateOnly(row.production_date),
cost_price: row.cost_price == null ? null : Number(row.cost_price),
};
const changed: string[] = [];
// ── 批次级 ──────────────────────────────────────────────
const batchSets: string[] = [];
const batchParams: unknown[] = [];
if (input.storageZone !== undefined) {
const next = trimText(input.storageZone) || null;
if ((beforeBatch.storage_zone || null) !== next) {
batchParams.push(next);
batchSets.push(`storage_zone = $${batchParams.length}`);
changed.push('storage_zone');
}
}
if (input.expiryDate !== undefined) {
const next = normalizeDateOrNull(input.expiryDate);
if ((beforeBatch.expiry_date || null) !== next) {
batchParams.push(next);
batchSets.push(`expiry_date = $${batchParams.length}::date`);
changed.push('expiry_date');
}
}
if (input.productionDate !== undefined) {
const next = normalizeDateOrNull(input.productionDate);
if ((beforeBatch.production_date || null) !== next) {
batchParams.push(next);
batchSets.push(`production_date = $${batchParams.length}::date`);
changed.push('production_date');
}
}
if (input.costPrice !== undefined) {
const raw = input.costPrice;
const next = raw == null || trimText(raw) === '' ? null : Number(raw);
if (next != null && (!Number.isFinite(next) || next < 0)) {
throw Object.assign(new Error('成本价须为不小于 0 的数字'), {
status: 400,
code: 'invalid_cost',
});
}
if ((beforeBatch.cost_price ?? null) !== (next ?? null)) {
batchParams.push(next);
batchSets.push(`cost_price = $${batchParams.length}::numeric`);
changed.push('cost_price');
}
}
if (batchSets.length) {
batchParams.push(inventoryId);
await client.query(
`UPDATE inventory SET ${batchSets.join(', ')} WHERE id = $${batchParams.length}::uuid`,
batchParams
);
}
// ── 商品级 ──────────────────────────────────────────────
const productTouched =
input.categoryCode !== undefined ||
input.spec !== undefined ||
input.unit !== undefined ||
input.origin !== undefined;
if (productTouched) {
if (!skuCode) {
throw Object.assign(new Error('该库存批次没有商品编码,无法改商品档案'), {
status: 400,
code: 'no_sku',
});
}
const skuRow = await client.query(
`SELECT sku_name, category_code, spec, unit, origin FROM skus WHERE sku_code = $1 LIMIT 1`,
[skuCode]
);
const sku = skuRow.rows[0] || {};
const beforeProduct = {
category_code: sku.category_code == null ? null : String(sku.category_code),
spec: sku.spec == null ? null : String(sku.spec),
unit: sku.unit == null ? null : String(sku.unit),
origin: sku.origin == null ? null : String(sku.origin),
};
// 分类 / 规格 / 单位 → 写商品真源 product_catalog(触发器同步 skus)
const pcSets: string[] = [];
const pcParams: unknown[] = [];
const skuSets: string[] = [];
const skuParams: unknown[] = [];
if (input.categoryCode !== undefined) {
const next = trimText(input.categoryCode) || null;
if ((beforeProduct.category_code || null) !== next) {
pcParams.push(next);
pcSets.push(`parent_code = $${pcParams.length}`);
skuParams.push(next);
skuSets.push(`category_code = $${skuParams.length}`);
changed.push('category_code');
}
}
if (input.spec !== undefined) {
const next = trimText(input.spec) || null;
if ((beforeProduct.spec || null) !== next) {
pcParams.push(next);
pcSets.push(`spec = $${pcParams.length}`);
skuParams.push(next);
skuSets.push(`spec = $${skuParams.length}`);
changed.push('spec');
}
}
if (input.unit !== undefined) {
const next = trimText(input.unit) || null;
if ((beforeProduct.unit || null) !== next) {
pcParams.push(next);
pcSets.push(`unit = $${pcParams.length}`);
skuParams.push(next);
skuSets.push(`unit = $${skuParams.length}`);
changed.push('unit');
}
}
// origin 仅存在于 skus(product_catalog 无该列)
if (input.origin !== undefined) {
const next = trimText(input.origin) || null;
if ((beforeProduct.origin || null) !== next) {
skuParams.push(next);
skuSets.push(`origin = $${skuParams.length}`);
changed.push('origin');
}
}
if (pcSets.length) {
pcParams.push(skuCode, branchCode);
await client.query(
`UPDATE product_catalog
SET ${pcSets.join(', ')}
WHERE item_type = 'product'
AND code = $${pcParams.length - 1}
AND (branch_code = $${pcParams.length} OR branch_code IS NULL)`,
pcParams
);
}
if (skuSets.length) {
skuParams.push(skuCode);
await client.query(
`UPDATE skus SET ${skuSets.join(', ')} WHERE sku_code = $${skuParams.length}`,
skuParams
);
}
}
await client.query('COMMIT');
const result: UpdateInventoryBatchResult = {
id: String(row.id),
batch_no: String(row.batch_no),
sku_code: skuCode,
changed,
};
// 审计(提交后写,失败不回滚主流程)
try {
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'inventory_batch_edit',
targetTable: 'inventory',
targetId: result.id,
oldValue: { ...beforeBatch },
newValue: { ...input, changed },
branchCode,
actionCategory: 'inventory',
});
} catch (auditError) {
console.error('[inventoryBatchEdit] writeAuditLog failed:', auditError);
}
return result;
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
@@ -0,0 +1,630 @@
/**
* 入库批次报告:仓库上传(图片 / PDF)→ OCR 解析 → 按「商品名 + 生产日期」匹配入库批次。
*
* 设计:docs/design/20261029-入库批次报告上传与匹配.md
*
* 硬边界(勿破):
* - **不复用 `quality_reports`**:那会进入验收「报告齐全」硬闸的覆盖计算
* (见 .cursor/rules/product-freeze.mdc)。本功能用独立表;
* - **不写 `inventory`**:库存管理冻结,本服务只**读** `inventory` 做匹配;
* - **本期不推主系统**(对接契约未定);
* - OCR **复用**已登记提示词 `quality.report.meta`(不新增 AI 功能 / 提示词 / 计量点)。
*
* 匹配键 = 商品名 + 生产日期;结果三态(唯一 / 多命中 / 未命中)+ **人工确认**才落关联。
*/
import { pool } from '../db';
import { writeAuditLog } from './auditService';
import { getStorageProvider } from './storageProvider';
import { safeStorageFileName } from './storageBucketConfig';
import { buildSignedStoragePath } from './storageSignedUrl';
import { resolvePrompt } from './promptRegistryService';
import { callWithImage, callWithFile, hasRuntimeConfig } from './llmService';
import { extractAiProductNames, productNamesMatch } from './qualityReportService';
const REPORT_BUCKET = 'quality-reports';
const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif']);
const STATUS_PENDING = 10;
const STATUS_CONFIRMED = 30;
/** 单次匹配扫描上限(按分公司 + 生产日期收窄,再在内存里做商品名模糊匹配) */
const CANDIDATE_SCAN_LIMIT = 2000;
function trimText(v: unknown): string {
return String(v ?? '').trim();
}
/** '2026/10/9' / '2026年10月9日' / '20261009' / Date → 'YYYY-MM-DD';认不出→null */
function toDateOnly(v: unknown): string | null {
if (v instanceof Date && !Number.isNaN(v.getTime())) {
const y = v.getFullYear();
const m = String(v.getMonth() + 1).padStart(2, '0');
const d = String(v.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
const t = trimText(v);
if (!t) return null;
const m = t.match(/^(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})/);
if (m) return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`;
const compact = t.match(/^(\d{4})(\d{2})(\d{2})$/);
if (compact) return `${compact[1]}-${compact[2]}-${compact[3]}`;
return null;
}
function normalizeName(v: unknown): string {
return trimText(v)
.toLowerCase()
.replace(/[\s\u3000]+/g, '')
.replace(/[()()【】\[\]「」『』《》<>]/g, '')
.replace(/[·•..]/g, '');
}
type ParsedMeta = {
product_names: string[];
produced_at: string | null;
testing_org: string | null;
ai_raw: Record<string, unknown> | null;
};
function emptyMeta(): ParsedMeta {
return { product_names: [], produced_at: null, testing_org: null, ai_raw: null };
}
/**
* OCR 一份报告内容:图走视觉;PDF 走方舟文档理解。失败留空(降级不阻断,人工可手选批次)。
* 提示词沿用 `quality.report.meta`(已登记 AI 门槛)。
*/
async function ocrReportContent(
contentBase64: string,
ext: string,
branchCode: string
): Promise<ParsedMeta> {
const empty = emptyMeta();
const lower = ext.toLowerCase();
if (!IMAGE_EXTS.has(lower) && lower !== 'pdf') return empty;
if (!contentBase64 || !(await hasRuntimeConfig({ branchCode }))) return empty;
try {
const prompt = await resolvePrompt('quality.report.meta', { branchCode });
let text: string | null = null;
if (IMAGE_EXTS.has(lower)) {
text = await callWithImage(prompt.systemPrompt, contentBase64, { branchCode });
} else {
const dataUrl = contentBase64.startsWith('data:')
? contentBase64
: `data:application/pdf;base64,${contentBase64}`;
text = await callWithFile(prompt.systemPrompt, dataUrl, {
branchCode,
filename: 'batch-report.pdf',
mime: 'application/pdf',
});
}
if (!text) return empty;
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (!jsonMatch) return empty;
const raw = JSON.parse(jsonMatch[0]) as Record<string, unknown>;
return {
product_names: extractAiProductNames(raw),
produced_at: toDateOnly(raw.produced_at),
testing_org: trimText(raw.testing_org) || trimText(raw.inspected_org) || null,
ai_raw: raw,
};
} catch (error) {
console.warn(
'[inventory-batch-report] OCR failed:',
error instanceof Error ? error.message : error
);
return empty;
}
}
/** 从 `quality-reports` 桶读回上传对象(先经 multer 通道落存储)。 */
async function loadUploadedObject(
path: string
): Promise<{ base64: string; ext: string } | null> {
let safe: string;
try {
safe = safeStorageFileName(trimText(path));
} catch {
return null;
}
if (!safe) return null;
const obj = await getStorageProvider().getObject(REPORT_BUCKET, safe);
if (!obj?.buffer?.length) return null;
const ext = (safe.split('.').pop() || 'jpg').toLowerCase();
return { base64: obj.buffer.toString('base64'), ext };
}
export interface BatchReportCandidate {
inventory_id: string;
sku_code: string | null;
sku_name: string | null;
batch_no: string | null;
production_date: string | null;
available_qty: number | null;
unit: string | null;
spec: string | null;
storage_zone: string | null;
/** exact = 商品名/编码全等;fuzzy = 包含命中(「疑似」) */
match_kind: 'exact' | 'fuzzy';
}
export interface BatchReportProductMatch {
product_name: string;
status: 'unique' | 'multi' | 'none';
candidates: BatchReportCandidate[];
}
export interface BatchReportConfirmedMatch {
id: string;
inventory_id: string;
sku_code: string | null;
product_name: string | null;
batch_no: string | null;
production_date: string | null;
match_source: 'auto' | 'manual';
confirmed_at: string | null;
}
export interface InventoryBatchReportDto {
id: string;
report_no: string | null;
report_type: string;
file_paths: string[];
file_urls: string[];
product_names: string[];
produced_at: string | null;
testing_org: string | null;
status: number;
ai_parsed: boolean;
uploaded_at: string | null;
confirmed: BatchReportConfirmedMatch[];
/** 候选只在「创建 / 取单条」时返回 */
matches?: BatchReportProductMatch[];
}
type CandidateRow = {
inventory_id: string;
sku_code: string | null;
sku_name: string | null;
batch_no: string | null;
production_date: string | null;
available_qty: number | null;
unit: string | null;
spec: string | null;
storage_zone: string | null;
};
async function loadCandidateRows(
branchCode: string,
producedAt: string | null
): Promise<CandidateRow[]> {
const params: unknown[] = [branchCode];
let dateFilter = '';
if (producedAt) {
params.push(producedAt);
dateFilter = ` AND i.production_date = $2::date`;
}
const result = await pool.query(
`SELECT i.id AS inventory_id, i.sku_code, i.batch_no, i.production_date,
i.available_qty, i.storage_zone,
s.sku_name, s.unit, s.spec
FROM inventory i
LEFT JOIN skus s ON s.sku_code = i.sku_code
WHERE i.branch_code = $1${dateFilter}
ORDER BY i.available_qty DESC NULLS LAST, i.created_at DESC
LIMIT ${CANDIDATE_SCAN_LIMIT}`,
params
);
return (result.rows as Record<string, unknown>[]).map((row) => ({
inventory_id: String(row.inventory_id),
sku_code: row.sku_code == null ? null : String(row.sku_code),
sku_name: row.sku_name == null ? null : String(row.sku_name),
batch_no: row.batch_no == null ? null : String(row.batch_no),
production_date: toDateOnly(row.production_date),
available_qty: row.available_qty == null ? null : Number(row.available_qty),
unit: row.unit == null ? null : String(row.unit),
spec: row.spec == null ? null : String(row.spec),
storage_zone: row.storage_zone == null ? null : String(row.storage_zone),
}));
}
/** 按「商品名 + 生产日期」给出每个品名的匹配建议(三态) */
function buildProductMatches(
productNames: string[],
producedAt: string | null,
rows: CandidateRow[]
): BatchReportProductMatch[] {
return productNames.map((name) => {
const normalized = normalizeName(name);
const hits = rows.filter(
(row) =>
productNamesMatch(name, row.sku_name) || productNamesMatch(name, row.sku_code)
);
const candidates: BatchReportCandidate[] = hits.map((row) => {
const exact =
normalized.length > 0 &&
(normalizeName(row.sku_name) === normalized || normalizeName(row.sku_code) === normalized);
return { ...row, match_kind: exact ? 'exact' : 'fuzzy' };
});
return {
product_name: name,
status: candidates.length === 0 ? 'none' : candidates.length === 1 ? 'unique' : 'multi',
candidates,
};
});
}
function mapReportRow(
raw: Record<string, unknown>,
confirmed: BatchReportConfirmedMatch[]
): InventoryBatchReportDto {
const paths = Array.isArray(raw.file_paths) ? raw.file_paths.map((p) => String(p)) : [];
const fileUrls = paths.map((p) => {
try {
return buildSignedStoragePath(REPORT_BUCKET, safeStorageFileName(p));
} catch {
return p;
}
});
return {
id: String(raw.id),
report_no: raw.report_no == null ? null : String(raw.report_no),
report_type: raw.report_type == null ? 'batch' : String(raw.report_type),
file_paths: paths,
file_urls: fileUrls,
product_names: Array.isArray(raw.product_names)
? raw.product_names.map((n) => String(n))
: [],
produced_at: toDateOnly(raw.produced_at),
testing_org: raw.testing_org == null ? null : String(raw.testing_org),
status: Number(raw.status ?? STATUS_PENDING),
ai_parsed: raw.ai_raw != null,
uploaded_at: raw.uploaded_at ? String(raw.uploaded_at) : null,
confirmed,
};
}
function mapConfirmedRows(rows: Record<string, unknown>[]): BatchReportConfirmedMatch[] {
return rows.map((row) => ({
id: String(row.id),
inventory_id: String(row.inventory_id),
sku_code: row.sku_code == null ? null : String(row.sku_code),
product_name: row.product_name == null ? null : String(row.product_name),
batch_no: row.batch_no == null ? null : String(row.batch_no),
production_date: toDateOnly(row.production_date),
match_source: row.match_source === 'manual' ? 'manual' : 'auto',
confirmed_at: row.confirmed_at ? String(row.confirmed_at) : null,
}));
}
async function loadConfirmedMatches(reportId: string): Promise<BatchReportConfirmedMatch[]> {
const result = await pool.query(
`SELECT id, inventory_id, sku_code, product_name, batch_no, production_date,
match_source, confirmed_at
FROM inventory_batch_report_matches
WHERE report_id = $1::uuid
ORDER BY confirmed_at ASC`,
[reportId]
);
return mapConfirmedRows(result.rows as Record<string, unknown>[]);
}
/**
* 上传并解析:每个文件 → 一份报告(OCR + 匹配候选)。文件须先经存储通道上传到
* `quality-reports` 桶(前端 `uploadQualityReportFileApi`)。
*/
export async function createInventoryBatchReports(input: {
files: string[];
branchCode: string;
uploadedBy?: string | null;
reportNo?: string | null;
}): Promise<InventoryBatchReportDto[]> {
const branchCode = trimText(input.branchCode);
if (!branchCode) {
throw Object.assign(new Error('请选择当前操作分公司'), {
status: 400,
code: 'branch_required',
});
}
const files = (input.files || []).map((f) => trimText(f)).filter(Boolean);
if (!files.length) {
throw Object.assign(new Error('请先上传报告文件'), { status: 400, code: 'invalid_request' });
}
const reportNo = trimText(input.reportNo) || null;
// 1) 落存储对象读回 + OCR(在事务外做,避免长时间占用连接)
const parsed: Array<{ path: string; meta: ParsedMeta }> = [];
for (const path of files) {
const obj = await loadUploadedObject(path);
if (!obj) continue;
const meta = await ocrReportContent(obj.base64, obj.ext, branchCode);
let storedPath = path;
try {
storedPath = safeStorageFileName(path);
} catch {
/* 保留原值 */
}
parsed.push({ path: storedPath, meta });
}
if (!parsed.length) {
throw Object.assign(new Error('报告文件读取失败,请重新上传'), {
status: 400,
code: 'file_unreadable',
});
}
// 2) 落库(一份文件一行)
const client = await pool.connect();
const createdIds: string[] = [];
try {
await client.query('BEGIN');
for (let i = 0; i < parsed.length; i += 1) {
const { path, meta } = parsed[i];
const rno = reportNo ? (parsed.length > 1 ? `${reportNo}-${i + 1}` : reportNo) : null;
if (rno) {
// 同分公司内报告编号唯一:提前拦下,给友好 400(否则撞唯一索引变 500)
const dup = await client.query(
`SELECT 1 FROM inventory_batch_reports WHERE branch_code = $1 AND report_no = $2 LIMIT 1`,
[branchCode, rno]
);
if (dup.rowCount) {
throw Object.assign(new Error(`报告编号「${rno}」已存在,请换一个或留空`), {
status: 400,
code: 'report_no_exists',
});
}
}
const inserted = await client.query(
`INSERT INTO inventory_batch_reports
(branch_code, report_no, report_type, file_paths, source_party,
product_names, produced_at, testing_org, ai_raw, ai_parsed_at,
status, uploaded_by)
VALUES ($1, $2, 'batch', ARRAY[$3]::text[], 'warehouse',
$4::text[], $5::date, $6, $7::jsonb, $8, $9, $10::uuid)
RETURNING id`,
[
branchCode,
rno,
path,
meta.product_names,
meta.produced_at,
meta.testing_org,
meta.ai_raw ? JSON.stringify(meta.ai_raw) : null,
meta.ai_raw ? new Date().toISOString() : null,
STATUS_PENDING,
input.uploadedBy || null,
]
);
createdIds.push(String(inserted.rows[0].id));
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
try {
await writeAuditLog({
operatorId: input.uploadedBy || null,
operationType: 'inventory_batch_report_upload',
targetTable: 'inventory_batch_reports',
targetId: createdIds[0] || undefined,
oldValue: null,
newValue: { count: createdIds.length, files: parsed.map((p) => p.path) },
branchCode,
actionCategory: 'inventory',
});
} catch (auditError) {
console.error('[inventoryBatchReport] writeAuditLog(upload) failed:', auditError);
}
// 3) 组装返回(带匹配候选)
const out: InventoryBatchReportDto[] = [];
for (const id of createdIds) {
const row = await pool.query(
`SELECT id, report_no, report_type, file_paths, product_names, produced_at,
testing_org, ai_raw, status, uploaded_at
FROM inventory_batch_reports WHERE id = $1::uuid`,
[id]
);
if (!row.rows[0]) continue;
const report = mapReportRow(row.rows[0] as Record<string, unknown>, []);
const candidates = await loadCandidateRows(branchCode, report.produced_at);
report.matches = buildProductMatches(report.product_names, report.produced_at, candidates);
out.push(report);
}
return out;
}
export async function listInventoryBatchReports(input: {
branchCode: string;
limit?: number;
}): Promise<InventoryBatchReportDto[]> {
const branchCode = trimText(input.branchCode);
if (!branchCode) {
throw Object.assign(new Error('请选择当前操作分公司'), {
status: 400,
code: 'branch_required',
});
}
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
const result = await pool.query(
`SELECT id, report_no, report_type, file_paths, product_names, produced_at,
testing_org, ai_raw, status, uploaded_at
FROM inventory_batch_reports
WHERE branch_code = $1
ORDER BY uploaded_at DESC
LIMIT $2`,
[branchCode, limit]
);
const rows = result.rows as Record<string, unknown>[];
const out: InventoryBatchReportDto[] = [];
for (const row of rows) {
const report = mapReportRow(row, []);
report.confirmed = await loadConfirmedMatches(report.id);
out.push(report);
}
return out;
}
export async function getInventoryBatchReport(input: {
reportId: string;
branchCode: string;
}): Promise<InventoryBatchReportDto | null> {
const reportId = trimText(input.reportId);
const branchCode = trimText(input.branchCode);
const result = await pool.query(
`SELECT id, report_no, report_type, file_paths, product_names, produced_at,
testing_org, ai_raw, status, uploaded_at
FROM inventory_batch_reports
WHERE id = $1::uuid AND branch_code = $2`,
[reportId, branchCode]
);
if (!result.rows[0]) return null;
const report = mapReportRow(result.rows[0] as Record<string, unknown>, []);
report.confirmed = await loadConfirmedMatches(report.id);
const candidates = await loadCandidateRows(branchCode, report.produced_at);
report.matches = buildProductMatches(report.product_names, report.produced_at, candidates);
return report;
}
/**
* 人工确认匹配:**替换**该报告已有的关联行,并置为已确认。每条关联须落在本分公司的 `inventory` 上。
*/
export async function confirmInventoryBatchReportMatches(input: {
reportId: string;
branchCode: string;
operatorId?: string | null;
matches: Array<{ inventoryId: string; productName?: string | null }>;
}): Promise<{ report_id: string; confirmed: BatchReportConfirmedMatch[] }> {
const reportId = trimText(input.reportId);
const branchCode = trimText(input.branchCode);
if (!reportId) {
throw Object.assign(new Error('缺少报告'), { status: 400, code: 'invalid_request' });
}
if (!branchCode) {
throw Object.assign(new Error('请选择当前操作分公司'), {
status: 400,
code: 'branch_required',
});
}
const wanted = (input.matches || [])
.map((m) => ({ inventoryId: trimText(m.inventoryId), productName: trimText(m.productName) || null }))
.filter((m) => m.inventoryId);
if (!wanted.length) {
throw Object.assign(new Error('请至少选择一条入库批次'), {
status: 400,
code: 'invalid_request',
});
}
const client = await pool.connect();
try {
await client.query('BEGIN');
const report = await client.query(
`SELECT id, status FROM inventory_batch_reports
WHERE id = $1::uuid AND branch_code = $2
FOR UPDATE`,
[reportId, branchCode]
);
if (!report.rowCount) {
throw Object.assign(new Error('报告不存在或不属于当前分公司'), {
status: 404,
code: 'not_found',
});
}
// 去重并校验每个库存批次属于本分公司
const seen = new Set<string>();
const rowsToInsert: Array<{
inventoryId: string;
skuCode: string | null;
batchNo: string | null;
productionDate: string | null;
productName: string | null;
}> = [];
for (const item of wanted) {
if (seen.has(item.inventoryId)) continue;
seen.add(item.inventoryId);
const inv = await client.query(
`SELECT id, sku_code, batch_no, production_date FROM inventory
WHERE id = $1::uuid AND branch_code = $2`,
[item.inventoryId, branchCode]
);
if (!inv.rowCount) {
throw Object.assign(new Error('所选入库批次不存在或不属于当前分公司'), {
status: 400,
code: 'invalid_inventory',
});
}
const row = inv.rows[0];
rowsToInsert.push({
inventoryId: item.inventoryId,
skuCode: row.sku_code == null ? null : String(row.sku_code),
batchNo: row.batch_no == null ? null : String(row.batch_no),
productionDate: toDateOnly(row.production_date),
productName: item.productName,
});
}
// 替换语义:先清掉本次未勾选的旧关联,再写入本次选择
await client.query(
`DELETE FROM inventory_batch_report_matches
WHERE report_id = $1::uuid AND NOT (inventory_id = ANY($2::uuid[]))`,
[reportId, rowsToInsert.map((r) => r.inventoryId)]
);
for (const r of rowsToInsert) {
await client.query(
`INSERT INTO inventory_batch_report_matches
(report_id, inventory_id, sku_code, product_name, batch_no, production_date,
match_source, confirmed_by)
VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6::date, 'manual', $7::uuid)
ON CONFLICT (report_id, inventory_id) DO UPDATE SET
product_name = EXCLUDED.product_name,
confirmed_by = EXCLUDED.confirmed_by,
confirmed_at = NOW()`,
[
reportId,
r.inventoryId,
r.skuCode,
r.productName,
r.batchNo,
r.productionDate,
input.operatorId || null,
]
);
}
await client.query(
`UPDATE inventory_batch_reports SET status = $2 WHERE id = $1::uuid`,
[reportId, STATUS_CONFIRMED]
);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
const confirmed = await loadConfirmedMatches(reportId);
try {
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'inventory_batch_report_confirm',
targetTable: 'inventory_batch_reports',
targetId: reportId,
oldValue: null,
newValue: { matches: confirmed.length },
branchCode,
actionCategory: 'inventory',
});
} catch (auditError) {
console.error('[inventoryBatchReport] writeAuditLog(confirm) failed:', auditError);
}
return { report_id: reportId, confirmed };
}
+30 -1
View File
@@ -4,6 +4,24 @@ import { listBranchReservationSummaries } from './inventoryStockCoverService';
import { clampManagementPage } from './purchaseOrderQueryService';
import { lowStockAlertSkuSql } from './lowStockAlertSql';
/**
* pg 的 `date` 列(OID 1082)返回**本地午夜**的 JS Date;直接 JSON 化会被 `toISOString()`
* 转成 UTC ISO(+08:00 下差一天)→ 前端 `.slice(0,10)` 得到前一天,且回写会造成日期逐次前移。
* 统一成中国时区的 'YYYY-MM-DD'。
*/
function toDateOnlyText(v: unknown): string | null {
if (v == null) return null;
if (v instanceof Date) {
if (Number.isNaN(v.getTime())) return null;
const y = v.getFullYear();
const m = String(v.getMonth() + 1).padStart(2, '0');
const d = String(v.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
const s = String(v).trim();
return s ? s.slice(0, 10) : null;
}
export interface ListInventoryForManagementInput {
page?: number;
pageSize?: number;
@@ -184,8 +202,14 @@ export async function listInventoryForManagement(
`SELECT inv.*,
sk.sku_name,
sk.category_code,
sk.spec,
sk.unit,
sk.origin,
cat.category_name,
sup.company_name AS supplier_name
sup.company_name AS supplier_name,
EXISTS (
SELECT 1 FROM inventory_batch_report_matches m WHERE m.inventory_id = inv.id
) AS has_batch_report
${fromSql}
WHERE ${whereSql}
ORDER BY inv.${sortField} ${sortOrder} NULLS LAST, inv.id DESC
@@ -229,6 +253,11 @@ export async function listInventoryForManagement(
sku_name: item.sku_name || item.sku_code,
category_name: item.category_name || null,
supplier_name: item.supplier_name || null,
/** 日期列统一出 'YYYY-MM-DD':pg 的 date 返回本地午夜 Date,直接 JSON 化会差一天 */
production_date: toDateOnlyText(item.production_date),
expiry_date: toDateOnlyText(item.expiry_date),
/** 是否存在已确认的入库批次报告关联(供列表标注「缺少批次报告」) */
has_batch_report: item.has_batch_report === true,
};
});
@@ -540,6 +540,8 @@ export async function batchStockInboundRows(input: {
operatorId?: string | null;
rows: BatchInboundRowInput[];
common?: BatchInboundCommon | null;
/** 库存流水备注(区分 Web / 小程序入口) */
remark?: string | null;
}): Promise<BatchStockInboundRowsResult> {
const branchCode = trimText(input.branchCode);
if (!branchCode) {
@@ -640,6 +642,7 @@ export async function batchStockInboundRows(input: {
branchCode,
operatorId: input.operatorId,
rows: bulkRows,
remark: input.remark,
})
: { results: [], ok_count: 0, failed_count: 0, new_batch_count: 0, accumulated_count: 0 };
+47 -6
View File
@@ -38,12 +38,44 @@ function newStockBatchNo(): string {
return `STK${ymd}${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
}
/** YYYY-MM / YYYY-MM-DD / Date → date string or null */
/**
* 归一为 YYYY-MM-DD。兼容 Excel/手填常见写法:
* 2026-10-09 / 2026/10/9 / 2026.10.9 / 2026年10月9日 / 2026-10(补 01)/ 20261009;无法识别返回 null。
*/
function normalizeProductionDate(raw: unknown): string | null {
const s = trimText(raw);
let s = trimText(raw);
if (!s) return null;
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
if (/^\d{4}-\d{2}$/.test(s)) return `${s}-01`;
s = s
.replace(/[年月]/g, '-')
.replace(/日/g, '')
.replace(/[./]/g, '-')
.replace(/\s+/g, '')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '');
const full = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
if (full) {
const mm = Number(full[2]);
const dd = Number(full[3]);
if (mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31) {
return `${full[1]}-${full[2].padStart(2, '0')}-${full[3].padStart(2, '0')}`;
}
return null;
}
const ym = s.match(/^(\d{4})-(\d{1,2})$/);
if (ym) {
const mm = Number(ym[2]);
if (mm >= 1 && mm <= 12) return `${ym[1]}-${ym[2].padStart(2, '0')}-01`;
return null;
}
const compact = s.match(/^(\d{4})(\d{2})(\d{2})$/);
if (compact) {
const mm = Number(compact[2]);
const dd = Number(compact[3]);
if (mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31) {
return `${compact[1]}-${compact[2]}-${compact[3]}`;
}
return null;
}
return null;
}
@@ -386,6 +418,8 @@ export async function bulkStockInbound(input: {
operatorId?: string | null;
rows: StockImportRowInput[];
chunkSize?: number;
/** 库存流水备注;不传则用 Excel 导入默认文案 */
remark?: string | null;
}): Promise<BulkStockInboundResult> {
const branchCode = trimText(input.branchCode);
if (!branchCode) {
@@ -411,6 +445,7 @@ export async function bulkStockInbound(input: {
operatorId: input.operatorId,
rowNumber,
row,
remark: input.remark,
});
results.push(r);
await client.query('RELEASE SAVEPOINT sp_row');
@@ -453,7 +488,13 @@ export async function bulkStockInbound(input: {
async function writeStockImportRow(
db: Db,
args: { branchCode: string; operatorId?: string | null; rowNumber: number; row: StockImportRowInput }
args: {
branchCode: string;
operatorId?: string | null;
rowNumber: number;
row: StockImportRowInput;
remark?: string | null;
}
): Promise<StockImportRowResult> {
const { branchCode, operatorId, rowNumber, row } = args;
const skuCode = trimText(row.skuCode);
@@ -517,7 +558,7 @@ async function writeStockImportRow(
batch_no, sku_code, operation_type, quantity, before_qty, after_qty,
related_order_code, operator_id, remark
) VALUES ($1, $2, 'stock_in', $3, $4, $5, NULL, $6, $7)`,
[batchNo, skuCode, qty, beforeQty, afterQty, operatorId || null, 'Excel 批量导入库存']
[batchNo, skuCode, qty, beforeQty, afterQty, operatorId || null, trimText(args.remark) || 'Excel 批量导入库存']
);
if (unitCost > 0) {
@@ -0,0 +1,484 @@
import React, { useCallback, useEffect, useState } from 'react';
import { X, Upload, Loader2, AlertTriangle, CheckCircle2 } from 'lucide-react';
import { DialogOverlay } from '../ui/DialogOverlay';
import { notify } from '../../utils/notify';
import { useT } from '../../i18n';
import { useDebouncedValue } from '../../hooks/useDebouncedValue';
import { readOperatingBranchCode } from '../../utils/operatingBranch';
import {
uploadQualityReportFileApi,
createInventoryBatchReportsApi,
confirmInventoryBatchReportMatchesApi,
listInventoryManagementApi,
type InventoryBatchReport,
type InventoryBatchReportProductMatch,
} from '../../utils/workflowApi';
type Selection = { productName: string; reportId: string };
interface Props {
open: boolean;
onClose: () => void;
onDone?: () => void;
}
/**
* 上传批次报告(图片 / PDF)→ 解析 → 按「商品名 + 生产日期」给出匹配建议 → 人工确认。
* 独立于 quality_reports;不写 inventory;仅在本系统留档。
*/
export const BatchReportUploadModal: React.FC<Props> = ({ open, onClose, onDone }) => {
const t = useT();
const [files, setFiles] = useState<File[]>([]);
const [reportNo, setReportNo] = useState('');
const [busy, setBusy] = useState<'idle' | 'parsing' | 'confirming'>('idle');
const [reports, setReports] = useState<InventoryBatchReport[]>([]);
const [selected, setSelected] = useState<Map<string, Selection>>(new Map());
const operatingBranchCode = readOperatingBranchCode();
const reset = useCallback(() => {
setFiles([]);
setReportNo('');
setReports([]);
setSelected(new Map());
setBusy('idle');
}, []);
const close = useCallback(() => {
if (busy !== 'idle') return;
reset();
onClose();
}, [busy, reset, onClose]);
const startParse = async () => {
if (!files.length) {
notify.error(t('inventory.batchReport.needFile'));
return;
}
setBusy('parsing');
try {
const paths: string[] = [];
for (const file of files) {
paths.push(await uploadQualityReportFileApi(file));
}
const created = await createInventoryBatchReportsApi({
files: paths,
reportNo: reportNo.trim() || null,
operatingBranchCode,
});
setReports(created);
const next = new Map<string, Selection>();
for (const report of created) {
for (const pm of report.matches || []) {
if (pm.status === 'unique' && pm.candidates[0]) {
next.set(pm.candidates[0].inventory_id, {
productName: pm.product_name,
reportId: report.id,
});
}
}
}
setSelected(next);
} catch (err) {
notify.error(
err instanceof Error ? err.message : t('inventory.batchReport.parseFail')
);
} finally {
setBusy('idle');
}
};
const toggle = (reportId: string, productName: string, inventoryId: string) => {
setSelected((prev) => {
const next = new Map(prev);
if (next.has(inventoryId)) next.delete(inventoryId);
else next.set(inventoryId, { productName, reportId });
return next;
});
};
const confirm = async () => {
const withMatches = reports.filter((report) =>
[...selected.values()].some((s) => s.reportId === report.id)
);
if (!withMatches.length) {
notify.error(t('inventory.batchReport.needPick'));
return;
}
setBusy('confirming');
try {
for (const report of withMatches) {
const matches = [...selected.entries()]
.filter(([, s]) => s.reportId === report.id)
.map(([inventoryId, s]) => ({
inventory_id: inventoryId,
product_name: s.productName,
}));
await confirmInventoryBatchReportMatchesApi({
reportId: report.id,
matches,
operatingBranchCode,
});
}
notify.success(t('inventory.batchReport.done'));
onDone?.();
reset();
onClose();
} catch (err) {
notify.error(
err instanceof Error ? err.message : t('inventory.batchReport.confirmFail')
);
} finally {
setBusy('idle');
}
};
if (!open) return null;
const selectedCount = selected.size;
return (
<DialogOverlay onBackdropMouseDown={close}>
<div
className="app-surface rounded-xl shadow-xl w-full max-w-2xl p-5 max-h-[88vh] overflow-y-auto"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-black dark:text-slate-100">
{t('inventory.batchReport.title')}
</h3>
<button
type="button"
onClick={close}
disabled={busy !== 'idle'}
className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-slate-800 disabled:opacity-50"
aria-label={t('common.close')}
>
<X className="w-4 h-4" />
</button>
</div>
{reports.length === 0 ? (
<div>
<p className="text-sm app-foreground-muted mb-4">
{t('inventory.batchReport.hint')}
</p>
<label className="block mb-3">
<span className="block text-sm mb-1">{t('inventory.batchReport.reportNo')}</span>
<input
value={reportNo}
onChange={(e) => setReportNo(e.target.value)}
placeholder={t('inventory.batchReport.reportNoPh')}
className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</label>
<label className="flex items-center justify-center gap-2 px-3 py-8 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50">
<Upload className="w-5 h-5 text-gray-500" />
<span className="text-sm text-gray-700">
{files.length
? t('inventory.batchReport.selectedCount', { n: files.length })
: t('inventory.batchReport.pickFile')}
</span>
<input
type="file"
accept="image/*,application/pdf"
multiple
className="hidden"
onChange={(e) => setFiles(Array.from(e.target.files || []))}
/>
</label>
</div>
) : (
<div className="space-y-4">
{reports.map((report) => (
<ReportCard
key={report.id}
report={report}
selected={selected}
onToggle={toggle}
/>
))}
</div>
)}
<div className="flex gap-2 mt-5">
{reports.length === 0 ? (
<>
<button
type="button"
onClick={close}
disabled={busy !== 'idle'}
className="flex-1 py-2 border border-gray-200 rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50"
>
{t('common.cancel')}
</button>
<button
type="button"
onClick={() => void startParse()}
disabled={busy !== 'idle' || files.length === 0}
className="flex-1 py-2 bg-indigo-600 text-white rounded-lg text-sm hover:bg-indigo-700 disabled:opacity-50 flex items-center justify-center gap-2"
>
{busy === 'parsing' && <Loader2 className="w-4 h-4 animate-spin" />}
{busy === 'parsing'
? t('inventory.batchReport.parsing')
: t('inventory.batchReport.startParse')}
</button>
</>
) : (
<>
<button
type="button"
onClick={reset}
disabled={busy !== 'idle'}
className="flex-1 py-2 border border-gray-200 rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50"
>
{t('inventory.batchReport.rePick')}
</button>
<button
type="button"
onClick={() => void confirm()}
disabled={busy !== 'idle'}
className="flex-1 py-2 bg-indigo-600 text-white rounded-lg text-sm hover:bg-indigo-700 disabled:opacity-50 flex items-center justify-center gap-2"
>
{busy === 'confirming' && <Loader2 className="w-4 h-4 animate-spin" />}
{busy === 'confirming'
? t('inventory.batchReport.confirming')
: t('inventory.batchReport.confirm', { n: selectedCount })}
</button>
</>
)}
</div>
</div>
</DialogOverlay>
);
};
type ManualPickRow = {
id?: string;
batch_no?: string;
sku_code?: string;
sku_name?: string;
production_date?: string;
available_qty?: number;
unit?: string;
storage_zone?: string;
};
/** 手动选择入库批次:自动匹配未命中、或想改选时用。搜索走库存列表接口(防抖,商品名/批次号)。 */
const ManualBatchPicker: React.FC<{
reportId: string;
productName: string;
selected: Map<string, Selection>;
onToggle: (reportId: string, productName: string, inventoryId: string) => void;
}> = ({ reportId, productName, selected, onToggle }) => {
const t = useT();
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const debounced = useDebouncedValue(query, 400);
const [rows, setRows] = useState<ManualPickRow[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!open) return;
let cancelled = false;
setLoading(true);
listInventoryManagementApi({
page: 1,
page_size: 20,
search: debounced.trim(),
only_available: 'false',
})
.then((res) => {
if (!cancelled) setRows((res.data || []) as ManualPickRow[]);
})
.catch(() => {
if (!cancelled) setRows([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [open, debounced]);
return (
<div className="mt-1.5">
<button
type="button"
onClick={() => setOpen((v) => !v)}
className="text-xs text-indigo-600 hover:underline"
>
{open ? t('inventory.batchReport.manualHide') : t('inventory.batchReport.manualPick')}
</button>
{open && (
<div className="mt-1.5 border border-gray-200 rounded-lg p-2">
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('inventory.batchReport.manualSearchPh')}
className="w-full px-2 py-1.5 border border-gray-200 rounded text-xs mb-1.5 focus:ring-2 focus:ring-indigo-500 outline-none"
/>
<div className="max-h-56 overflow-y-auto space-y-1">
{loading ? (
<p className="text-xs app-foreground-muted px-1 py-1">
{t('inventory.batchReport.manualLoading')}
</p>
) : rows.length === 0 ? (
<p className="text-xs app-foreground-muted px-1 py-1">
{t('inventory.batchReport.manualEmpty')}
</p>
) : (
rows.map((r, idx) => {
const id = String(r.id || '');
if (!id) return null;
return (
<label
key={`${id}-${idx}`}
className="flex items-center gap-2 text-xs px-2 py-1.5 rounded border border-gray-200 hover:bg-gray-50 cursor-pointer"
>
<input
type="checkbox"
checked={selected.has(id)}
onChange={() => onToggle(reportId, productName, id)}
/>
<span className="font-medium">{r.sku_name || r.sku_code || '—'}</span>
<span className="app-foreground-muted">
{t('inventory.batchReport.candidateBatch')}: {r.batch_no || '—'}
</span>
<span className="app-foreground-muted">
{r.production_date ? String(r.production_date).slice(0, 10) : '—'}
</span>
<span className="app-foreground-muted">
{r.available_qty ?? '—'} {r.unit || ''}
</span>
</label>
);
})
)}
</div>
</div>
)}
</div>
);
};
const STATUS_STYLE: Record<InventoryBatchReportProductMatch['status'], string> = {
unique: 'bg-emerald-50 text-emerald-700 border-emerald-200',
multi: 'bg-amber-50 text-amber-700 border-amber-200',
none: 'bg-gray-50 text-gray-500 border-gray-200',
};
const ReportCard: React.FC<{
report: InventoryBatchReport;
selected: Map<string, Selection>;
onToggle: (reportId: string, productName: string, inventoryId: string) => void;
}> = ({ report, selected, onToggle }) => {
const t = useT();
const fileName = (report.file_paths[0] || '').split('/').pop() || report.file_paths[0] || '';
const matches = report.matches || [];
return (
<div className="app-border border rounded-lg p-3">
<div className="flex items-start justify-between gap-2 mb-2">
<div className="min-w-0">
<p className="text-sm font-medium truncate" title={fileName}>
{fileName}
</p>
<p className="text-xs app-foreground-muted mt-0.5">
{t('inventory.batchReport.producedAt')}: {report.produced_at || '—'}
{report.testing_org ? ` · ${report.testing_org}` : ''}
</p>
</div>
<span className="shrink-0 text-xs px-2 py-0.5 rounded border bg-gray-50 text-gray-600 border-gray-200">
{report.status === 30
? t('inventory.batchReport.statusConfirmed')
: t('inventory.batchReport.statusPending')}
</span>
</div>
{!report.ai_parsed && (
<p className="flex items-center gap-1.5 text-xs text-amber-600 mb-2">
<AlertTriangle className="w-3.5 h-3.5" />
{t('inventory.batchReport.parseEmpty')}
</p>
)}
{matches.length === 0 ? (
<p className="text-xs app-foreground-muted">
{t('inventory.batchReport.noProductNames')}
</p>
) : (
<div className="space-y-3">
{matches.map((pm) => (
<div key={pm.product_name}>
<div className="flex items-center gap-2 mb-1">
<span className="text-sm font-medium">{pm.product_name}</span>
<span
className={`text-xs px-1.5 py-0.5 rounded border ${STATUS_STYLE[pm.status]}`}
>
{pm.status === 'unique'
? t('inventory.batchReport.statusUnique')
: pm.status === 'multi'
? t('inventory.batchReport.statusMulti')
: t('inventory.batchReport.statusNone')}
</span>
</div>
{pm.candidates.length === 0 ? (
<p className="text-xs app-foreground-muted">
{t('inventory.batchReport.statusNoneHint')}
</p>
) : (
<div className="space-y-1">
{pm.candidates.map((c) => {
const checked = selected.has(c.inventory_id);
return (
<label
key={c.inventory_id}
className="flex items-center gap-2 text-xs px-2 py-1.5 rounded border border-gray-200 hover:bg-gray-50 cursor-pointer"
>
<input
type="checkbox"
checked={checked}
onChange={() => onToggle(report.id, pm.product_name, c.inventory_id)}
/>
<span className="font-medium">{c.sku_name || c.sku_code || '—'}</span>
<span className="app-foreground-muted">
{t('inventory.batchReport.candidateBatch')}: {c.batch_no || '—'}
</span>
<span className="app-foreground-muted">
{c.production_date || '—'}
</span>
<span className="app-foreground-muted">
{c.available_qty ?? '—'} {c.unit || ''}
</span>
{c.match_kind === 'fuzzy' && (
<span className="text-amber-600">
{t('inventory.batchReport.fuzzy')}
</span>
)}
</label>
);
})}
</div>
)}
<ManualBatchPicker
reportId={report.id}
productName={pm.product_name}
selected={selected}
onToggle={onToggle}
/>
</div>
))}
</div>
)}
{report.confirmed.length > 0 && (
<p className="flex items-center gap-1.5 text-xs text-emerald-600 mt-2">
<CheckCircle2 className="w-3.5 h-3.5" />
{t('inventory.batchReport.confirmedCount', { n: report.confirmed.length })}
</p>
)}
</div>
);
};
+66
View File
@@ -24,12 +24,17 @@ export const inventory: MessageDict = {
'col.product': 'Product',
'col.batch': 'Batch',
'col.batchReport': 'Batch report',
'col.available': 'Available',
'col.reserved': 'Reserved',
'col.claimable': 'Claimable',
'col.cost': 'Unit cost',
'col.expiry': 'Expiry',
'col.prodDate': 'Production date',
'col.zone': 'Zone',
'col.spec': 'Spec',
'col.unit': 'Unit',
'col.origin': 'Origin',
'zoneFilterPh': 'Zone',
'col.supplier': 'Supplier',
'col.actions': 'Actions',
@@ -140,6 +145,28 @@ export const inventory: MessageDict = {
'adjust.remarkPh': 'e.g. count variance, write-off, backfill',
'adjust.saving': 'Saving…',
'adjust.confirm': 'Confirm adjust',
'adjust.batchSection': 'Batch attributes (this batch only)',
'adjust.zone': 'Storage zone',
'adjust.zonePh': 'Pick or type a storage zone',
'adjust.zoneEmpty': 'Not set',
'adjust.zoneCreate': '+ Use this zone',
'adjust.zoneCreateNamed': '+ Use zone "{name}"',
'adjust.expiry': 'Expiry date',
'adjust.productionDate': 'Production date',
'adjust.cost': 'Cost price',
'adjust.productSection': 'Product profile (affects all batches of this product)',
'adjust.productHint': 'Category / spec / unit / origin edit the product itself and sync to all its batches.',
'adjust.category': 'Category',
'adjust.categoryPh': 'Pick a category',
'adjust.categoryEmpty': 'Uncategorized',
'adjust.spec': 'Spec',
'adjust.unit': 'Unit',
'adjust.unitPh': 'Pick or type a unit',
'adjust.unitEmpty': 'Not set',
'adjust.unitCreate': '+ Use this unit',
'adjust.unitCreateNamed': '+ Use unit "{name}"',
'adjust.origin': 'Origin',
'adjust.noChange': 'Nothing changed',
'toast.holdingLoadFail': 'Failed to load holding cost',
'toast.stockCoverOn': 'Surplus stock cover enabled',
@@ -331,4 +358,43 @@ export const inventory: MessageDict = {
'stockImport.templateHint': 'Download the template and fill it in; products are created if missing.',
'stockImport.infoAlert': 'Add only, never overwrite: same batch accumulates; duplicate name+spec keeps the first row; cost may be blank.',
'stockImport.done': 'Import completed',
// Upload batch report (independent of quality_reports)
'batchReport.button': 'Upload batch report',
'batchReport.title': 'Upload batch report',
'batchReport.hint':
'Upload a batch report (image or PDF). Product names and production dates are recognized and matched against stock-in batches; confirmed links are archived in this system only.',
'batchReport.reportNo': 'Report no.',
'batchReport.reportNoPh': 'Optional, e.g. 2026-001',
'batchReport.pickFile': 'Choose image or PDF',
'batchReport.selectedCount': '{n} file(s) selected',
'batchReport.startParse': 'Upload and parse',
'batchReport.parsing': 'Parsing…',
'batchReport.rePick': 'Choose again',
'batchReport.producedAt': 'Production date',
'batchReport.statusPending': 'Pending',
'batchReport.statusConfirmed': 'Confirmed',
'batchReport.parseEmpty': 'Nothing parsed — choose a batch manually',
'batchReport.noProductNames': 'No product recognized, so no match suggestion',
'batchReport.statusUnique': 'Unique match',
'batchReport.statusMulti': 'Multiple matches, please choose',
'batchReport.statusNone': 'No match',
'batchReport.statusNoneHint': 'No automatic match; select a batch manually below',
'batchReport.candidateBatch': 'Batch',
'batchReport.fuzzy': 'fuzzy',
'batchReport.confirmedCount': '{n} confirmed',
'batchReport.needFile': 'Choose a report file first',
'batchReport.needPick': 'Select at least one stock-in batch',
'batchReport.parseFail': 'Failed to parse batch report',
'batchReport.confirmFail': 'Failed to confirm match',
'batchReport.confirm': 'Confirm match ({n})',
'batchReport.confirming': 'Confirming…',
'batchReport.done': 'Batch report uploaded and confirmed',
'batchReport.present': 'Yes',
'batchReport.missing': 'Missing batch report',
'batchReport.manualPick': 'Select batch manually',
'batchReport.manualHide': 'Hide',
'batchReport.manualSearchPh': 'Search product or batch no.',
'batchReport.manualLoading': 'Loading…',
'batchReport.manualEmpty': 'No stock-in batch found',
};
+66
View File
@@ -24,12 +24,17 @@ export const inventory: MessageDict = {
'col.product': 'Produk',
'col.batch': 'Batch',
'col.batchReport': 'Laporan batch',
'col.available': 'Tersedia',
'col.reserved': 'Reservasi',
'col.claimable': 'Bisa dialokasi',
'col.cost': 'Harga biaya',
'col.expiry': 'Kedaluwarsa',
'col.prodDate': 'Tanggal produksi',
'col.zone': 'Zona',
'col.spec': 'Spesifikasi',
'col.unit': 'Satuan',
'col.origin': 'Asal',
'zoneFilterPh': 'Zona',
'col.supplier': 'Pemasok',
'col.actions': 'Aksi',
@@ -144,6 +149,28 @@ export const inventory: MessageDict = {
'adjust.remarkPh': 'mis. selisih stok opname, rusak, backfill',
'adjust.saving': 'Menyimpan…',
'adjust.confirm': 'Konfirmasi sesuaikan',
'adjust.batchSection': 'Atribut batch (hanya batch ini)',
'adjust.zone': 'Zona simpan',
'adjust.zonePh': 'Pilih atau ketik zona simpan',
'adjust.zoneEmpty': 'Belum diisi',
'adjust.zoneCreate': '+ Pakai zona ini',
'adjust.zoneCreateNamed': '+ Pakai zona "{name}"',
'adjust.expiry': 'Tanggal kedaluwarsa',
'adjust.productionDate': 'Tanggal produksi',
'adjust.cost': 'Harga pokok',
'adjust.productSection': 'Profil produk (berlaku semua batch produk ini)',
'adjust.productHint': 'Kategori / spesifikasi / satuan / asal mengubah produknya sendiri dan tersinkron ke semua batch-nya.',
'adjust.category': 'Kategori',
'adjust.categoryPh': 'Pilih kategori',
'adjust.categoryEmpty': 'Tanpa kategori',
'adjust.spec': 'Spesifikasi',
'adjust.unit': 'Satuan',
'adjust.unitPh': 'Pilih atau ketik satuan',
'adjust.unitEmpty': 'Belum diisi',
'adjust.unitCreate': '+ Pakai satuan ini',
'adjust.unitCreateNamed': '+ Pakai satuan "{name}"',
'adjust.origin': 'Asal',
'adjust.noChange': 'Tidak ada perubahan',
'toast.holdingLoadFail': 'Gagal memuat biaya holding',
'toast.stockCoverOn': 'Potong dari stok surplus diaktifkan',
@@ -338,4 +365,43 @@ export const inventory: MessageDict = {
'stockImport.templateHint': 'Unduh template dan isi; produk dibuat jika belum ada.',
'stockImport.infoAlert': 'Hanya menambah, tidak menimpa: batch sama diakumulasi; nama+spesifikasi duplikat menyimpan baris pertama; harga pokok boleh kosong.',
'stockImport.done': 'Impor selesai',
// Unggah laporan batch (independen dari quality_reports)
'batchReport.button': 'Unggah laporan batch',
'batchReport.title': 'Unggah laporan batch',
'batchReport.hint':
'Unggah laporan batch (gambar atau PDF). Nama produk dan tanggal produksi dikenali lalu dicocokkan dengan batch stok masuk; tautan terkonfirmasi hanya diarsipkan di sistem ini.',
'batchReport.reportNo': 'No. laporan',
'batchReport.reportNoPh': 'Opsional, mis. 2026-001',
'batchReport.pickFile': 'Pilih gambar atau PDF',
'batchReport.selectedCount': '{n} file dipilih',
'batchReport.startParse': 'Unggah dan uraikan',
'batchReport.parsing': 'Menguraikan…',
'batchReport.rePick': 'Pilih ulang',
'batchReport.producedAt': 'Tanggal produksi',
'batchReport.statusPending': 'Menunggu',
'batchReport.statusConfirmed': 'Terkonfirmasi',
'batchReport.parseEmpty': 'Tidak ada hasil uraian — pilih batch secara manual',
'batchReport.noProductNames': 'Produk tidak dikenali, tidak ada saran kecocokan',
'batchReport.statusUnique': 'Cocok tunggal',
'batchReport.statusMulti': 'Banyak kecocokan, silakan pilih',
'batchReport.statusNone': 'Tidak cocok',
'batchReport.statusNoneHint': 'Tidak ada kecocokan otomatis; pilih batch secara manual di bawah',
'batchReport.candidateBatch': 'Batch',
'batchReport.fuzzy': 'mirip',
'batchReport.confirmedCount': '{n} terkonfirmasi',
'batchReport.needFile': 'Pilih file laporan dulu',
'batchReport.needPick': 'Pilih minimal satu batch stok masuk',
'batchReport.parseFail': 'Gagal menguraikan laporan batch',
'batchReport.confirmFail': 'Gagal mengonfirmasi kecocokan',
'batchReport.confirm': 'Konfirmasi kecocokan ({n})',
'batchReport.confirming': 'Mengonfirmasi…',
'batchReport.done': 'Laporan batch diunggah dan dikonfirmasi',
'batchReport.present': 'Ada',
'batchReport.missing': 'Tidak ada laporan batch',
'batchReport.manualPick': 'Pilih batch manual',
'batchReport.manualHide': 'Tutup',
'batchReport.manualSearchPh': 'Cari nama produk / no. batch',
'batchReport.manualLoading': 'Memuat…',
'batchReport.manualEmpty': 'Batch stok masuk tidak ditemukan',
};
+67
View File
@@ -23,12 +23,17 @@ export const inventory: MessageDict = {
'col.product': '商品信息',
'col.batch': '批次',
'col.batchReport': '批次报告',
'col.available': '可用数量',
'col.reserved': '预留占用',
'col.claimable': '可调配',
'col.cost': '成本价',
'col.expiry': '效期',
'col.prodDate': '生产日期',
'col.zone': '区域编号',
'col.spec': '规格',
'col.unit': '单位',
'col.origin': '产地',
'zoneFilterPh': '区域编号',
'col.supplier': '供应商',
'col.actions': '操作',
@@ -139,6 +144,29 @@ export const inventory: MessageDict = {
'adjust.remarkPh': '如:盘点差异、报损、补录',
'adjust.saving': '保存中…',
'adjust.confirm': '确认调整',
'adjust.batchSection': '批次属性(仅影响本批次)',
'adjust.zone': '区域编号',
'adjust.zonePh': '选择或输入区域编号',
'adjust.zoneEmpty': '未设置',
'adjust.zoneCreate': '+ 使用该区域',
'adjust.zoneCreateNamed': '+ 使用区域「{name}」',
'adjust.expiry': '有效期',
'adjust.productionDate': '生产日期',
'adjust.cost': '成本价',
'adjust.productSection': '商品档案(影响该商品所有批次)',
'adjust.productHint':
'分类 / 规格 / 单位 / 产地改的是商品本身,会同步到该商品的所有批次。',
'adjust.category': '分类',
'adjust.categoryPh': '选择分类',
'adjust.categoryEmpty': '未分类',
'adjust.spec': '规格',
'adjust.unit': '单位',
'adjust.unitPh': '选择或输入单位',
'adjust.unitEmpty': '未设置',
'adjust.unitCreate': '+ 使用该单位',
'adjust.unitCreateNamed': '+ 使用单位「{name}」',
'adjust.origin': '产地',
'adjust.noChange': '没有改动,无需保存',
'toast.holdingLoadFail': '加载进仓持有成本失败',
'toast.stockCoverOn': '已开启多采库存抵扣',
@@ -330,4 +358,43 @@ export const inventory: MessageDict = {
'stockImport.templateHint': '请下载模板按示例填写;商品不存在会自动创建,分类不存在会按填写的分类建。',
'stockImport.infoAlert': '导入只增不覆盖:同批次号累加、不影响原有库存;商品名+规格重复只保留第一行;成本价可留空,事后可补。',
'stockImport.done': '导入完成',
// 上传批次报告(独立于 quality_reports)
'batchReport.button': '上传批次报告',
'batchReport.title': '上传批次报告',
'batchReport.hint':
'上传批次报告(图片或 PDF),自动识别商品名与生产日期并匹配入库批次;确认后仅在本系统留档。',
'batchReport.reportNo': '报告编号',
'batchReport.reportNoPh': '选填,如 2026-001',
'batchReport.pickFile': '选择图片或 PDF',
'batchReport.selectedCount': '已选 {n} 个文件',
'batchReport.startParse': '上传并解析',
'batchReport.parsing': '解析中…',
'batchReport.rePick': '重新选择',
'batchReport.producedAt': '生产日期',
'batchReport.statusPending': '待确认',
'batchReport.statusConfirmed': '已确认',
'batchReport.parseEmpty': '未解析到内容,可手工选择批次',
'batchReport.noProductNames': '未识别到商品,无法给出匹配建议',
'batchReport.statusUnique': '唯一命中',
'batchReport.statusMulti': '多命中,请选择',
'batchReport.statusNone': '未命中',
'batchReport.statusNoneHint': '没有自动匹配到入库批次,可在下方手动选择',
'batchReport.candidateBatch': '批次',
'batchReport.fuzzy': '疑似',
'batchReport.confirmedCount': '已确认 {n} 条',
'batchReport.needFile': '请先选择报告文件',
'batchReport.needPick': '请至少勾选一条入库批次',
'batchReport.parseFail': '解析批次报告失败',
'batchReport.confirmFail': '确认匹配失败',
'batchReport.confirm': '确认匹配({n})',
'batchReport.confirming': '确认中…',
'batchReport.done': '批次报告已上传并确认',
'batchReport.present': '已有',
'batchReport.missing': '缺少批次报告',
'batchReport.manualPick': '手动选择批次',
'batchReport.manualHide': '收起',
'batchReport.manualSearchPh': '搜索商品名 / 批次号',
'batchReport.manualLoading': '加载中…',
'batchReport.manualEmpty': '没有找到入库批次',
};
+298 -18
View File
@@ -18,6 +18,7 @@ import {
X,
PlusCircle,
Upload,
FileText,
} from 'lucide-react';
import { supabase } from '../../supabase/client';
import { DialogOverlay } from '../../components/ui/DialogOverlay';
@@ -27,6 +28,7 @@ import { notify } from '../../utils/notify';
import { SearchableSelect } from '../../components/ui/SearchableSelect';
import { DocumentExportButton } from '../../components/export/DocumentExportButton';
import { StockImportModal } from '../../components/inventory/StockImportModal';
import { BatchReportUploadModal } from '../../components/inventory/BatchReportUploadModal';
import { INVENTORY_COLUMNS, type InventoryExportRow } from '../../utils/exportColumnPresets';
import { ModuleTabLayout } from '../../components/ModuleTabLayout';
import { useTabChildSegment } from '../../hooks/useModuleTabRoute';
@@ -39,6 +41,9 @@ import { TablePaginationBar } from '../../components/ui/TablePaginationBar';
import { SortableThLabel } from '../../components/ui/SortableThLabel';
import {
adjustInventoryAvailableApi,
updateInventoryBatchApi,
type UpdateInventoryBatchPayload,
listUnitsApi,
getStockCoverFromInventoryConfigApi,
setStockCoverFromInventoryConfigApi,
listInventoryManagementApi,
@@ -62,11 +67,16 @@ import { useT } from '../../i18n';
type InventoryColumnId =
| 'product'
| 'batch'
| 'batchReport'
| 'zone'
| 'spec'
| 'unit'
| 'origin'
| 'available'
| 'reserved'
| 'claimable'
| 'cost'
| 'prodDate'
| 'expiry'
| 'supplier'
| 'actions';
@@ -83,11 +93,16 @@ type InventoryLogColumnId =
const INVENTORY_LIST_COLUMNS: Array<TableColumnDef<InventoryColumnId>> = [
{ id: 'product', label: 'col.product' },
{ id: 'batch', label: 'col.batch' },
{ id: 'batchReport', label: 'col.batchReport' },
{ id: 'zone', label: 'col.zone' },
{ id: 'spec', label: 'col.spec' },
{ id: 'unit', label: 'col.unit' },
{ id: 'origin', label: 'col.origin' },
{ id: 'available', label: 'col.available' },
{ id: 'reserved', label: 'col.reserved' },
{ id: 'claimable', label: 'col.claimable' },
{ id: 'cost', label: 'col.cost' },
{ id: 'prodDate', label: 'col.prodDate' },
{ id: 'expiry', label: 'col.expiry' },
{ id: 'supplier', label: 'col.supplier' },
{ id: 'actions', label: 'col.actions', fixed: true },
@@ -116,7 +131,11 @@ interface InventoryItem {
id: string;
sku_code: string;
sku_name?: string;
category_code?: string;
category_name?: string;
spec?: string;
unit?: string;
origin?: string;
batch_no: string;
quantity: number;
available_qty: number;
@@ -131,6 +150,8 @@ interface InventoryItem {
storage_zone?: string;
cost_price?: number;
status: number;
/** 是否有已确认的入库批次报告关联(缺则商品名标红 + 「批次报告」列提示) */
has_batch_report?: boolean;
}
interface InventoryLog {
@@ -191,11 +212,22 @@ export const InventoryManagement: React.FC = () => {
const [adjustQty, setAdjustQty] = useState('');
const [adjustRemark, setAdjustRemark] = useState('');
const [adjustSaving, setAdjustSaving] = useState(false);
const [adjustStorageZone, setAdjustStorageZone] = useState('');
const [adjustExpiry, setAdjustExpiry] = useState('');
const [adjustProductionDate, setAdjustProductionDate] = useState('');
const [adjustCost, setAdjustCost] = useState('');
const [adjustCategoryCode, setAdjustCategoryCode] = useState('');
const [adjustSpec, setAdjustSpec] = useState('');
const [adjustUnit, setAdjustUnit] = useState('');
const [adjustOrigin, setAdjustOrigin] = useState('');
const [categoryChoices, setCategoryChoices] = useState<Array<{ value: string; label: string }>>([]);
const [unitChoices, setUnitChoices] = useState<Array<{ value: string; label: string }>>([]);
const [voidTargets, setVoidTargets] = useState<InventoryItem[]>([]);
const [voidSaving, setVoidSaving] = useState(false);
const [voidProgress, setVoidProgress] = useState('');
const [stockCoverEnabled, setStockCoverEnabled] = useState(true);
const [stockImportOpen, setStockImportOpen] = useState(false);
const [batchReportOpen, setBatchReportOpen] = useState(false);
const [stockCoverSaving, setStockCoverSaving] = useState(false);
const [stockCoverLoaded, setStockCoverLoaded] = useState(false);
const inventoryColumns = useMemo(() => {
@@ -308,6 +340,14 @@ export const InventoryManagement: React.FC = () => {
setAdjustItem(item);
setAdjustQty(String(item.available_qty ?? 0));
setAdjustRemark('');
setAdjustStorageZone(item.storage_zone || '');
setAdjustExpiry(item.expiry_date ? String(item.expiry_date).slice(0, 10) : '');
setAdjustProductionDate(item.production_date ? String(item.production_date).slice(0, 10) : '');
setAdjustCost(item.cost_price != null ? String(item.cost_price) : '');
setAdjustCategoryCode(item.category_code || '');
setAdjustSpec(item.spec || '');
setAdjustUnit(item.unit || '');
setAdjustOrigin(item.origin || '');
};
const closeAdjustModal = () => {
@@ -315,8 +355,46 @@ export const InventoryManagement: React.FC = () => {
setAdjustItem(null);
setAdjustQty('');
setAdjustRemark('');
setAdjustProductionDate('');
};
// 分类 / 单位 选项(供修改弹窗选择)
useEffect(() => {
let cancelled = false;
void (async () => {
const { data } = await supabase
.from('categories')
.select('category_code, category_name')
.eq('status', 1)
.order('category_code')
.limit(500);
if (!cancelled) {
setCategoryChoices(
((data || []) as Array<{ category_code: string; category_name: string }>).map((c) => ({
value: c.category_code,
label: c.category_name || c.category_code,
}))
);
}
})();
void listUnitsApi({ activeOnly: true })
.then((res) => {
if (cancelled) return;
setUnitChoices(
(res.data || [])
.map((u) => String(u.unit_name || u.unit_code || '').trim())
.filter(Boolean)
.map((label) => ({ value: label, label }))
);
})
.catch(() => {
if (!cancelled) setUnitChoices([]);
});
return () => {
cancelled = true;
};
}, []);
const closeVoidModal = () => {
if (voidSaving) return;
setVoidTargets([]);
@@ -380,8 +458,9 @@ export const InventoryManagement: React.FC = () => {
const submitAdjust = async () => {
if (!adjustItem || adjustSaving) return;
const qty = Number(adjustQty);
if (!Number.isFinite(qty) || qty < 0) {
const qtyRaw = adjustQty.trim();
const qty = Number(qtyRaw);
if (qtyRaw === '' || !Number.isFinite(qty) || qty < 0) {
notify.error(t('inventory.toast.qtyInvalid'));
return;
}
@@ -389,17 +468,59 @@ export const InventoryManagement: React.FC = () => {
notify.error(t('inventory.toast.remarkRequired'));
return;
}
const branch = operatingBranchCode || readOperatingBranchCode();
const beforeZone = adjustItem.storage_zone || '';
const beforeExpiry = adjustItem.expiry_date ? String(adjustItem.expiry_date).slice(0, 10) : '';
const beforeProdDate = adjustItem.production_date
? String(adjustItem.production_date).slice(0, 10)
: '';
const beforeCost = adjustItem.cost_price != null ? String(adjustItem.cost_price) : '';
const beforeCategory = adjustItem.category_code || '';
const beforeSpec = adjustItem.spec || '';
const beforeUnit = adjustItem.unit || '';
const beforeOrigin = adjustItem.origin || '';
const payload: UpdateInventoryBatchPayload = {};
if (adjustStorageZone !== beforeZone) payload.storage_zone = adjustStorageZone;
if (adjustExpiry !== beforeExpiry) payload.expiry_date = adjustExpiry;
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;
if (adjustSpec !== beforeSpec) payload.spec = adjustSpec;
if (adjustUnit !== beforeUnit) payload.unit = adjustUnit;
if (adjustOrigin !== beforeOrigin) payload.origin = adjustOrigin;
const qtyChanged = Math.abs(qty - Number(adjustItem.available_qty ?? 0)) > 1e-9;
const hasAttrChange = Object.keys(payload).length > 0;
if (!qtyChanged && !hasAttrChange) {
notify.error(t('inventory.adjust.noChange'));
return;
}
setAdjustSaving(true);
try {
const adjusted = await adjustInventoryAvailableApi({
inventoryId: adjustItem.id,
availableQty: qty,
remark: adjustRemark.trim(),
operatingBranchCode: operatingBranchCode || readOperatingBranchCode(),
});
let replenishMsg = '';
if (qtyChanged) {
const adjusted = await adjustInventoryAvailableApi({
inventoryId: adjustItem.id,
availableQty: qty,
remark: adjustRemark.trim(),
operatingBranchCode: branch,
});
replenishMsg = adjusted?.replenish_message || '';
}
if (hasAttrChange) {
await updateInventoryBatchApi({
inventoryId: adjustItem.id,
remark: adjustRemark.trim(),
operatingBranchCode: branch,
...payload,
});
}
notify.success(
adjusted?.replenish_message
? t('inventory.toast.adjustedWithMsg', { msg: adjusted.replenish_message })
replenishMsg
? t('inventory.toast.adjustedWithMsg', { msg: replenishMsg })
: t('inventory.toast.adjusted')
);
setAdjustItem(null);
@@ -805,6 +926,16 @@ export const InventoryManagement: React.FC = () => {
{t('inventory.stockImport.button')}
</button>
)}
{activeTab === 'inventory' && (
<button
type="button"
onClick={() => setBatchReportOpen(true)}
className="app-button-secondary app-border flex items-center gap-2 px-3 py-1.5 border rounded-lg text-sm"
>
<FileText className="w-4 h-4 text-gray-600" />
{t('inventory.batchReport.button')}
</button>
)}
<button
type="button"
onClick={fetchInventory}
@@ -818,6 +949,11 @@ export const InventoryManagement: React.FC = () => {
onClose={() => setStockImportOpen(false)}
onDone={fetchInventory}
/>
<BatchReportUploadModal
open={batchReportOpen}
onClose={() => setBatchReportOpen(false)}
onDone={fetchInventory}
/>
<DocumentExportButton
title={t('inventory.export.title')}
filename="inventory_export"
@@ -961,6 +1097,7 @@ export const InventoryManagement: React.FC = () => {
const reservedQty = Number(item.reserved_qty) || 0;
const availableQty = Number(item.available_qty) || 0;
const reservationGap = reservedQty > availableQty + 1e-9;
const missingBatchReport = item.has_batch_report === false;
return (
<tr
key={item.id}
@@ -985,7 +1122,9 @@ export const InventoryManagement: React.FC = () => {
<td key={col.id} className="px-6 py-4">
<p
className={`app-product-name ${
reservationGap ? 'text-red-700 dark:text-red-300' : ''
reservationGap || missingBatchReport
? 'text-red-700 dark:text-red-300'
: ''
}`}
>
{item.sku_name}
@@ -1010,6 +1149,20 @@ export const InventoryManagement: React.FC = () => {
</Link>
</td>
);
case 'batchReport':
return (
<td key={col.id} className="px-6 py-4 text-sm">
{item.has_batch_report ? (
<span className="text-gray-400">
{t('inventory.batchReport.present')}
</span>
) : (
<span className="text-red-600 dark:text-red-400 font-medium">
{t('inventory.batchReport.missing')}
</span>
)}
</td>
);
case 'available':
return (
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
@@ -1074,6 +1227,12 @@ export const InventoryManagement: React.FC = () => {
</td>
);
}
case 'prodDate':
return (
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
{item.production_date ? String(item.production_date).slice(0, 10) : '-'}
</td>
);
case 'expiry':
return (
<td key={col.id} className="px-6 py-4">
@@ -1085,12 +1244,6 @@ export const InventoryManagement: React.FC = () => {
<span className="text-[11px] text-gray-400">
{String(item.expiry_date).slice(0, 10)}
</span>
) : item.production_date ? (
<span className="text-[11px] text-gray-400">
{t('inventory.inboundDate', {
date: String(item.production_date).slice(0, 10),
})}
</span>
) : null}
</div>
</td>
@@ -1101,6 +1254,24 @@ export const InventoryManagement: React.FC = () => {
{item.storage_zone || '-'}
</td>
);
case 'spec':
return (
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
{item.spec || '-'}
</td>
);
case 'unit':
return (
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
{item.unit || '-'}
</td>
);
case 'origin':
return (
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
{item.origin || '-'}
</td>
);
case 'supplier':
return (
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
@@ -1530,7 +1701,7 @@ export const InventoryManagement: React.FC = () => {
{adjustItem && (
<DialogOverlay onBackdropMouseDown={closeAdjustModal}>
<div
className="app-surface rounded-xl shadow-xl w-full max-w-md p-5"
className="app-surface rounded-xl shadow-xl w-full max-w-lg p-5 max-h-[88vh] overflow-y-auto"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between mb-4">
@@ -1575,6 +1746,115 @@ export const InventoryManagement: React.FC = () => {
{t('inventory.adjust.warn')}
</p>
</div>
{/* 批次属性(仅本批次) */}
<div className="border-t border-gray-100 pt-3">
<p className="text-gray-500 text-xs mb-2">{t('inventory.adjust.batchSection')}</p>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.zone')}</label>
<SearchableSelect
className="w-full"
value={adjustStorageZone}
onChange={setAdjustStorageZone}
options={zoneOptions.map((z) => ({ value: z, label: z }))}
placeholder={t('inventory.adjust.zonePh')}
allowEmpty
emptyLabel={t('inventory.adjust.zoneEmpty')}
allowCreateFromQuery
createFromQueryLabel={(q) => t('inventory.adjust.zoneCreateNamed', { name: q })}
onCreateFromQuery={(q) => setAdjustStorageZone(q.trim())}
hideSearchIcon
compact
/>
</div>
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.productionDate')}</label>
<input
type="date"
value={adjustProductionDate}
onChange={(e) => setAdjustProductionDate(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.expiry')}</label>
<input
type="date"
value={adjustExpiry}
onChange={(e) => setAdjustExpiry(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.cost')}</label>
<input
type="number"
min={0}
step="0.01"
value={adjustCost}
onChange={(e) => setAdjustCost(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
</div>
</div>
{/* 商品档案(影响该商品所有批次) */}
<div className="border-t border-gray-100 pt-3">
<p className="text-gray-500 text-xs mb-1">{t('inventory.adjust.productSection')}</p>
<p className="text-xs text-amber-600 mb-2">{t('inventory.adjust.productHint')}</p>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.category')}</label>
<SearchableSelect
className="w-full"
value={adjustCategoryCode}
onChange={setAdjustCategoryCode}
options={categoryChoices}
placeholder={t('inventory.adjust.categoryPh')}
allowEmpty
emptyLabel={t('inventory.adjust.categoryEmpty')}
hideSearchIcon
compact
/>
</div>
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.spec')}</label>
<input
value={adjustSpec}
onChange={(e) => setAdjustSpec(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.unit')}</label>
<SearchableSelect
className="w-full"
value={adjustUnit}
onChange={setAdjustUnit}
options={unitChoices}
placeholder={t('inventory.adjust.unitPh')}
allowEmpty
emptyLabel={t('inventory.adjust.unitEmpty')}
allowCreateFromQuery
createFromQueryLabel={(q) => t('inventory.adjust.unitCreateNamed', { name: q })}
onCreateFromQuery={(q) => setAdjustUnit(q.trim())}
hideSearchIcon
compact
/>
</div>
<div>
<label className="block text-gray-500 text-xs mb-1">{t('inventory.adjust.origin')}</label>
<input
value={adjustOrigin}
onChange={(e) => setAdjustOrigin(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
/>
</div>
</div>
</div>
<div>
<label className="block text-gray-500 text-xs mb-1">
{t('inventory.adjust.remark')} <span className="text-red-500">*</span>
+141
View File
@@ -3138,6 +3138,147 @@ export async function adjustInventoryAvailableApi(input: {
}).then((res) => res.data);
}
/** 库存管理「修改」:批次属性 + 商品档案字段(数量走 adjustInventoryAvailableApi) */
export interface UpdateInventoryBatchPayload {
storage_zone?: string;
expiry_date?: string;
production_date?: string;
cost_price?: number | null;
category_code?: string;
spec?: string;
unit?: string;
origin?: string;
}
export async function updateInventoryBatchApi(input: {
inventoryId: string;
remark: string;
operatingBranchCode?: string | null;
} & UpdateInventoryBatchPayload) {
return workflowFetch<{
data: { id: string; batch_no: string; sku_code: string; changed: string[] };
}>('/inventory/batch-update', {
method: 'POST',
body: JSON.stringify({
inventory_id: input.inventoryId,
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.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 } : {}),
...(input.spec !== undefined ? { spec: input.spec } : {}),
...(input.unit !== undefined ? { unit: input.unit } : {}),
...(input.origin !== undefined ? { origin: input.origin } : {}),
}),
}).then((res) => res.data);
}
// ── 入库批次报告:上传(图/PDF)→ 解析 → 按「商品名 + 生产日期」匹配 ──────────
// 独立于 quality_reports;匹配只给建议,人工确认才落关联。
export interface InventoryBatchReportCandidate {
inventory_id: string;
sku_code: string | null;
sku_name: string | null;
batch_no: string | null;
production_date: string | null;
available_qty: number | null;
unit: string | null;
spec: string | null;
storage_zone: string | null;
match_kind: 'exact' | 'fuzzy';
}
export interface InventoryBatchReportProductMatch {
product_name: string;
status: 'unique' | 'multi' | 'none';
candidates: InventoryBatchReportCandidate[];
}
export interface InventoryBatchReportConfirmedMatch {
id: string;
inventory_id: string;
sku_code: string | null;
product_name: string | null;
batch_no: string | null;
production_date: string | null;
match_source: 'auto' | 'manual';
confirmed_at: string | null;
}
export interface InventoryBatchReport {
id: string;
report_no: string | null;
report_type: string;
file_paths: string[];
file_urls: string[];
product_names: string[];
produced_at: string | null;
testing_org: string | null;
status: number;
ai_parsed: boolean;
uploaded_at: string | null;
confirmed: InventoryBatchReportConfirmedMatch[];
matches?: InventoryBatchReportProductMatch[];
}
export async function createInventoryBatchReportsApi(input: {
files: string[];
reportNo?: string | null;
operatingBranchCode?: string | null;
}): Promise<InventoryBatchReport[]> {
return workflowFetch<{ data: InventoryBatchReport[] }>('/inventory/batch-reports', {
method: 'POST',
body: JSON.stringify({
files: input.files,
report_no: input.reportNo || undefined,
operating_branch_code: input.operatingBranchCode || undefined,
}),
}).then((res) => res.data);
}
export async function listInventoryBatchReportsApi(params?: {
limit?: number;
operatingBranchCode?: string | null;
}): Promise<InventoryBatchReport[]> {
const query = new URLSearchParams();
if (params?.limit) query.set('limit', String(params.limit));
if (params?.operatingBranchCode) query.set('operating_branch_code', params.operatingBranchCode);
const suffix = query.toString() ? `?${query.toString()}` : '';
return workflowFetch<{ data: InventoryBatchReport[] }>(
`/inventory/batch-reports${suffix}`
).then((res) => res.data);
}
export async function getInventoryBatchReportApi(input: {
reportId: string;
operatingBranchCode?: string | null;
}): Promise<InventoryBatchReport> {
const query = new URLSearchParams();
if (input.operatingBranchCode) query.set('operating_branch_code', input.operatingBranchCode);
const suffix = query.toString() ? `?${query.toString()}` : '';
return workflowFetch<{ data: InventoryBatchReport }>(
`/inventory/batch-reports/${encodeURIComponent(input.reportId)}${suffix}`
).then((res) => res.data);
}
export async function confirmInventoryBatchReportMatchesApi(input: {
reportId: string;
matches: Array<{ inventory_id: string; product_name?: string | null }>;
operatingBranchCode?: string | null;
}): Promise<{ report_id: string; confirmed: InventoryBatchReportConfirmedMatch[] }> {
return workflowFetch<{
data: { report_id: string; confirmed: InventoryBatchReportConfirmedMatch[] };
}>(`/inventory/batch-reports/${encodeURIComponent(input.reportId)}/confirm`, {
method: 'POST',
body: JSON.stringify({
matches: input.matches,
operating_branch_code: input.operatingBranchCode || undefined,
}),
}).then((res) => res.data);
}
export async function getPrepMinSupplyRatioConfigApi(operatingBranchCode?: string | null) {
const qs = operatingBranchCode
? `?operating_branch_code=${encodeURIComponent(operatingBranchCode)}`