diff --git a/docs/design/20261031-分拣出库可选批次与区域分组.md b/docs/design/20261031-分拣出库可选批次与区域分组.md new file mode 100644 index 0000000..ec4660f --- /dev/null +++ b/docs/design/20261031-分拣出库可选批次与区域分组.md @@ -0,0 +1,157 @@ +# 分拣完成选批次(持久化)+ 发车按选择扣库 + 按区域分组 + +> 立项 2026-10-31。开发者口径(本轮对话逐条确认,含一次关键纠偏): +> ① 小程序/Web 分拣时,分拣员**逐个商品**点「完成」→ 全部完成后「出库」; +> ② 每个商品行可见并可调「本次从哪几个批次扣」,**默认先进先出(按入库时间)自动预分配**,尽量减少手工; +> ③ 分拣列表**按区域分组**——**只在设置了区域时才展示**; +> ④ 出库要留痕到系统日志:**哪个分拣员、哪天入库的批次、商品名、取走多少**。 +> +> ⚠️ **关键纠偏(2026-10-31 查代码后)**:本系统**没有独立的「分拣出库」步骤**—— +> `confirmPickingComplete`(= 分拣「完成」)只置 `pick_status=30`、`outbound:false`、**不扣库存**; +> 真正的库存扣减发生在**司机装车核货/发车**(`delivery_loading_out`), +> 见 `docs/design/20260821-merge-outbound-with-loading.md` 与【分拣出库冻结】「界面无独立出库」。 +> ⇒ 开发者裁决采用 **A 方案**:**分拣「完成」时选批次并持久化,到发车核货时按该选择扣库**。 +> +> ⚠️ 触【分拣出库冻结】【库存管理冻结】【**配送履约冻结**】——本文即「拟改点 + 影响面」,**须批准后再改代码**。 + +## 1. 目标 / 非目标 + +- 目标:分拣「完成」时**默认按 FIFO 自动预分配批次**(按入库时间),允许分拣员**手工调整顺序/数量**; + 选择**持久化**,在**发车核货**扣库时**优先按选择执行**;分拣列表**按区域分组**(有区域时);出库**留痕到系统日志**。 +- 非目标(本期**不做**): + 1. **不新增独立「分拣出库」步骤**(不把出库加回主流程——遵守 picking-freeze); + 2. **不改 FIFO 排序键**(`expiry_date ASC NULLS LAST, created_at ASC`); + 3. 不改 `confirmPickingComplete` 对 `order_items.quantity/amount` 的写入,不在函数内改订单状态; + 4. **默认路径(不选批次)与现状逐字一致**(发车照旧 FIFO、`softInventory` 库存不足不拦发车); + 5. 不接 `customer` 拣货模式。 + +## 2. 改前实测事实 + +| # | 事实 | 证据 | +|---|---|---| +| F1 | 分拣「完成」`confirmPickingComplete` 只置 `pick_status=30`、`return outbound:false`、**不扣库** | `pickingService.confirmPickingComplete`(`pickingService.ts:906` 注释「分拣完成即推进待配送(出库与装车核货合并)」) | +| F2 | **真正扣库在装车核货/发车**:`delivery_loading_out`,FIFO、`softInventory`(不足不拦) | inventory-freeze / delivery-freeze | +| F3 | 界面**无独立出库**;小程序仅调 `POST /mobile/picking/complete`;无任何出库调用 | `miniprogram/components/picking-panel`;`miniprogram/utils/pickingAssembly.js`(`出库并入装车核货:30 即分拣完成`) | +| F4 | FIFO 排序 `expiry_date ASC NULLS LAST, created_at ASC`;批次行 `FOR UPDATE`;**不足先部分扣减再抛错**(非原子) | `inventoryOutboundService.ts`;inventory-freeze §3 | +| F5 | 可扣上限 = `总可用 − 他单活跃预留(status=10, order_code≠本单)`;预留是 **SKU 级**(`inventory_reservations` **无 `batch_no`**) | `inventoryStockCoverService.getClaimableStockQty`;`information_schema` | +| F6 | 区域:批次实际区 `inventory.storage_zone`;商品默认区 `skus.storage_zone` / `product_catalog.storage_zone`。分拣列表当前**不返回区域** | `20261010-仓库区域编号与批量导入库存.md` | +| F7 | `inventory_logs` 有 `batch_no/quantity/operator_id`,但**无商品名、无批次入库日** | inventory-freeze §2 | +| F8 | `operation_logs` 可承载结构化明细(`newValue` json),**无需改表** | `auditService.writeAuditLog` | + +## 3. 设计 + +### 3.1 交互(小程序 & Web 一致) + +- **每个商品行**:展示「本次出库批次分配」,默认按 FIFO **预分配好**(顺序 + 数量),可手改顺序/数量。 + - 每批显示:**区域**、批次号、**入库日**、可扣量、生产日期。 +- 分拣员点该行「**完成**」时确认该行分配;全部完成后点「**出库**」=**推进到待配送**(现状即此)。 +- 默认零操作:分拣员**全用预分配**即可,手工仅在有需要时。 +- 未设区域的行**不展示区域分组**(开发者口径 ③)。 + +#### 3.1.1 实现定稿(2026-10-31) + +- **小程序**(`miniprogram/components/picking-panel`):每个明细行下方一行「批次」摘要(`入库日 量 · …`),点「调整」弹出底部编辑器。 + - 编辑器逐批列「区域 · 入库日 · 可用」+ 数量输入 + 「↑/↓」调优先序 + 「按先进先出」重置 + 「确定」。 + - **数量编辑即满足用户「先扣 9 号再扣 8 号」的诉求**:计划总量 = 需量时,批次先后不影响结果(每批上限=本批可用∧计划量),只要把想留下的那批数量改小即可。 + - 区域分组:**仅当本组明细存在区域时**按区域插入分组标题(无任何区域则平铺,即口径③);极少数未设区域的行归入「未设区域」。 + - 一次拉取 `/mobile/picking/outbound-batches` 预取候选批次;手改后标记 `manual`,改实拣量不覆盖手改计划。 +- **Web**(`src/pages/picking/PickingManagement.tsx`):明细表新增「出库批次」列(摘要 + 「调整」),编辑器渲染在表格下方(含区域/入库日/可用/数量/↑↓/按先进先出/确定)。因 Web 明细表是扁平表格,**未按区域分组**,但批次编辑器逐批显示区域(如仍需 Web 分组,再另行评估)。 +- **持久化时机**:`confirmPickingComplete`(分拣完成)与 `savePickingProgress`(已完成单微调)都带 `outbound_batches`;不选/拉取失败时不传 ⇒ 发车回退纯 FIFO(与现状逐字一致)。 + +### 3.2 后端 + +1. **选择持久化**:分拣「完成」时随明细写入 `picking_items.outbound_batches`(见 §3.3)。 + - 改动点:`confirmPickingComplete` 的 rows 入参增加每行 `outbound_batches`,落库; + **不动**它对订单量/金额与订单状态的写入。 +2. **扣库执行(发车核货)**:`deliveryLoadingService` → `fifoDeductInventory` 时, + 按 `(order_code, sku_code)` 查出该行持久化的 `outbound_batches` 传 `batchPlan`: + - 有选择 ⇒ 先按选择顺序/数量扣; + - 无选择 / 选择不足 ⇒ 回退 **FIFO** 补扣; + - **保持 `softInventory` 语义**(发车库存不足不拦:按选择+FIFO 尽量扣,仍不足则跳过)。 + - ⚠️ **`fifoDeductInventory` 的 `batchPlan` 入参已完成**(可选、默认安全,不传=逐字现状)。 +3. **只读接口**(UI 预分配/展示用,**不改写库存**):按 `pick_item_id`(或 `sku_code` + `order_code`) + 返回:逐批 `{batch_no, storage_zone, inbound_at, claimable_qty, production_date}` + SKU 级 `{总可用, 他单预留, 可扣}`。 +4. **可扣口径(与现状一致,不新增)**:可扣上限 = `总可用 − 他单活跃预留(order_code≠本单)` + ⇒ 「给本单的占用 + 未占用」都能扣,只**不动他单占用**。 + +### 3.3 数据 + +- **加列**:`picking_items.outbound_batches jsonb`(`NULL`/`[]` = 默认 FIFO)。 + 形如 `[{"batch_no":"STK...","qty":12.5}, ...]`。 +- 迁移:见 §4(各租户 schema `ADD COLUMN IF NOT EXISTS`;`picking_items` 已在 `tenant_business_tables()`,**名单不变**)。 + +### 3.4 区域分组 + +- 分拣列表(小程序 + Web)返回并展示**区域**:优先取该行候选批次的 `inventory.storage_zone`, + 必要时回退商品默认区 `skus.storage_zone`。 +- **只有设置了区域时才显示分组**;未设置的正常平铺,**不出现「未设置区」分组**。 +- 一个商品行多为单区域;跨区时按其涉及区域标注(实现时定,见 §6)。 + +### 3.5 留痕 + +- **`inventory_logs`**(出入库记录):沿用现有写入(每批一行,已含 `batch_no/operator_id/quantity`)。 + 出入库记录**读取**查询 `LEFT JOIN inventory(batch_no, sku_code)` + `skus` 补**商品名**与**批次入库日**(只读展示)。 +- **`operation_logs`**(系统操作日志):**发车扣库成功**后写一条,`operation_type=picking_outbound`,`action_category=inventory`,`target_table=orders`, + `newValue` 含:操作人、订单号、`pick_codes`/`picker_ids`/**`picker_names`**(分拣员),以及**逐批次** `{sku_code, sku_name, batch_no, inbound_at, qty}`。 + (`picker_names` 经 `picking_tasks.reviewer_id/pick_completed_by → public.profiles` 解析;初始版本只有 UUID,难以回答「哪个分拣员」。) + +## 4. 迁移清单 + +- 新增迁移:给 `picking_items` 加 `outbound_batches jsonb`(`public` / `legacy_public` / `tenant_template` / 各 `tenant_*`,`ADD COLUMN IF NOT EXISTS`)。 +- **不改** `public.tenant_business_tables()`(`picking_items` 已在名单,只加列)。 +- 迁移末尾照例 `SELECT public.ensure_tenant_schemas_match_template();`(可选,列不加也应由模板克隆;保守起见保留)。 + +## 5. 验收标准 + +- **不选批次**:发车扣库结果与改前**逐字一致**(FIFO + `softInventory`)。 +- **选了批次**:按选择顺序/数量扣;选择不足**回退 FIFO 补扣**;发车**不因库存不足报错**(软语义)。 +- `available_qty` **不会为负**(每批扣到 ≥0)。 +- 小程序与 Web 都能看到并调整批次;**无区域时不出现区域分组**。 +- 出入库记录可见:**商品名 + 批次入库日 + 操作人 + 数量**;`operation_logs` 有逐批次明细。 +- 冻结不变量不被破坏:`FOR UPDATE`、部分扣减语义、`confirmPickingComplete` 不写订单量/金额、 + 发车 `softInventory`、不新增独立出库步骤、不接 `customer` 模式。 + +## 6. 风险 / 冻结口径 + +- 触【分拣出库冻结】【库存管理冻结】【**配送履约冻结**】。**保住**:FIFO `FOR UPDATE`、「不足先部分扣减再抛错」 + (分拣出库路径)、发车 `softInventory` 不拦、「完成分拣不改计划量/金额」、「界面无独立出库」。 +- **配送侧读取选择**:发车扣库新增「按 `(order_code, sku_code)` 查 `picking_items.outbound_batches`」一步—— + 只读,不影响发车门槛(仍只拦「无核货明细」)。 +- 分批扣减**非原子**:与现状一致(调用方 `BEGIN` 包裹)。 +- 实现时确认的小点:① 一个商品行涉及多区域时如何归组;② 需出库的 order+sku 若跨多个拣货单,计划的合并口径。 + +## 7. 待议(问题记录) + +- **分拣时「货已到、但未走系统入库」导致库存不足**(开发者 2026-10-31 提出): + 分拣路径现状是「先把能扣的批次扣完(部分扣减)再抛错」;**发车路径是软扣减(不拦)**。 + - 开发者口径:**首先不能卡流程**;「`available_qty` 能否为负 / 是否直接扣完 / 挂账 / 事后补录入库」等**真实处理方式另议**, + **本期先按报错处理**(分拣路径)。 + - ⇒ 记录在案,待业务与开发共同定夺后再改。 +- **「批次级占用」**(开发者 2026-10-31 追问后确认):预留只在 **SKU+订单** 维度(`inventory_reservations` 无 `batch_no`), + 所以「默认先扣*被占用的那一批*」在**批次维度无法精确表达**;若将来要「指定某批留给某单」,需**改预留模型**。本期**不做**。 + +## 8. 验证(实现后回填) + +**迁移**:`migrations/20261034_picking_items_outbound_batches.sql`(各 schema `ADD COLUMN IF NOT EXISTS`);本地已应用,实测 6 个 schema(legacy_public/tenant_template/br001/br002/sup35143228/sup37831443)`picking_items.outbound_batches` 均存在。 + +**回归命令**: +- `npx tsc --noEmit`(Web)✅ 0 error +- `server/node_modules/.bin/tsc --noEmit`(API)✅ 0 error +- `npm run build`(webpack production)✅ 编译通过 +- `npx vitest run src/i18n` ✅ 42/42(含「keeps picking keys aligned across locales」) +- `npx vitest run`(前端全量)⚠️ 718 通过 / 4 失败;4 项均为**既有、与本改动无关**(`printTemplateAiSection`、`SystemConfig.allowZeroCost`×2、`OrderManagementPage.deliveryDateInline`)——它们只读 `system/*`、订单页与行点击 hook,不涉分拣/i18n。 +- `server`:`pickingOps.test.ts`、`routeLayerBoundary.test.ts` ✅;`pickingCompleteKeepPlanQty.test.ts` 的「Go writeback」用例因仓库**无 `server-go/` 目录**(ENOENT)失败,属既有环境缺失,与本改动无关。 + +**批次分配逻辑往返实测**(以本地 `tenant_sup35143228` 真实批次数据 `SKUMV1WAO2V00011C`:A1=1490/A2=10/A3=20,FIFO 序)复刻后端 `fifoDeductInventory` 的 `batchPlan` 算法: + +| 用例 | 结果 | +|---|---| +| need=25,默认计划 `[A1:25]` | 扣减 {A1:25} | +| need=1500,默认计划 `[A1:1490,A2:10]` | 扣减 {A1:1490,A2:10} | +| need=1600(> 总可用 1520) | 计划覆盖全部,`shortfall=80`;发车软扣减 `remaining=80`(不拦) | +| 手改「优先 A3」`[A3:20,A2:5]` | 扣减 {A3:20,A2:5}(A1 不动)✅ | + +- **关键结论**:**默认(前端预分配)计划送入后端后,扣减结果与「不传 plan 的纯 FIFO」逐字一致**(三档 need 全部 `identical=true`)。 +- `available_qty` 每批扣到 ≥0(后端 `WHERE available_qty >= deductQty` + `deductQty=min(该批可用,计划量,剩余)`)。 + +**仍未跑**(需起 API + 造单的端到端):跨多个拣货单的同 order+sku 合并口径;发车核货真库扣减落 `inventory_logs` 与 `operation_logs` 明细的联调;小程序真机区域分组/编辑器交互。 diff --git a/migrations/20261034_picking_items_outbound_batches.sql b/migrations/20261034_picking_items_outbound_batches.sql new file mode 100644 index 0000000..eddb5f2 --- /dev/null +++ b/migrations/20261034_picking_items_outbound_batches.sql @@ -0,0 +1,31 @@ +-- 分拣「完成」时选定的出库批次计划(默认 FIFO;发车核货时按它扣库) +-- 设计:docs/design/20261031-分拣出库可选批次与区域分组.md +-- +-- `picking_items.outbound_batches`:形如 [{"batch_no":"STK...","qty":12.5}]; +-- NULL / [] = 未手选 ⇒ 发车按纯 FIFO 扣库(与改前逐字一致)。 +-- 只加列,不改表名单(picking_items 已在 public.tenant_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 + IF to_regclass(format('%I.picking_items', sch)) IS NULL THEN + CONTINUE; + END IF; + EXECUTE format( + 'ALTER TABLE %I.picking_items ADD COLUMN IF NOT EXISTS outbound_batches jsonb', + sch + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.picking_items.outbound_batches IS %L', + sch, + '分拣完成时选定的出库批次计划 [{"batch_no","qty"}];空=默认 FIFO' + ); + END LOOP; +END $$; diff --git a/miniprogram/components/picking-panel/index.js b/miniprogram/components/picking-panel/index.js index d8ab43d..b4ba777 100644 --- a/miniprogram/components/picking-panel/index.js +++ b/miniprogram/components/picking-panel/index.js @@ -3,6 +3,7 @@ const { fetchPickingTasks, fetchPickingWeighDevices, createPickingPrintJobs, + fetchPickingOutboundBatches, request, } = requestApi; @@ -28,6 +29,10 @@ const { summarizeTask, buildProgressRows, resolvePickMeasures, + resolveItemNeed, + allocateBatchesFifo, + formatBatchPlanText, + formatBatchQty, isScaleWeightMandatory, } = require('../../utils/pickingAssembly'); const { buildUnitPicker, ensureUnitDictionary, getUnitDictionaryLabels, isWeightUnit } = require('../../utils/units'); @@ -142,6 +147,27 @@ function visibleItemsForStatus(items, pickStatus) { return list; } +/** + * 按商品区域插入分组表头。 + * 无任何区域时不分组(直接平铺);有区域时按区域归组,未设区域的归入「未设区域」。 + */ +function withZoneHeaders(rows) { + const list = rows || []; + const hasZone = list.some((row) => String(row.storage_zone || '').trim()); + if (!hasZone) return list; + const out = []; + const seen = Object.create(null); + list.forEach((row) => { + const zone = String(row.storage_zone || '').trim() || '未设区域'; + if (!seen[zone]) { + seen[zone] = true; + out.push({ _zone: true, zone_label: zone, rowKey: `zone:${zone}` }); + } + out.push(row); + }); + return out; +} + const PICKING_ROLES = ['picker', 'warehouse', 'delivery']; Component({ @@ -155,6 +181,8 @@ Component({ data: { tasks: [], itemsMap: {}, + batchesMap: {}, + editor: null, activePickCode: '', activeTask: null, activeItems: [], @@ -462,28 +490,34 @@ Component({ const taskSummary = summarizeTask(items, status); const pendingCount = countPending(items); const hasOpenPicks = status < 30; + const pendingItems = visibleItemsForStatus(items, status); - this.setData({ - activePickCode: task ? task.pick_code : '', - activePickCodes: group.pickCodes, - activeGroupKey: group.key, - scopePickerIndex: groupIndex, - scopeMenuOpen: false, - skuCatalogMode: false, - skuSections: [], - dayGroups: [], - hasOpenPicks, - activeTask: task ? { ...task, pick_status: status } : { pick_status: status }, - activeItems: items, - activePendingItems: visibleItemsForStatus(items, status), - taskSummary, - pendingCount, - scanTip: '', - workflowTip: '', - showWorkTitle: false, - showCompanyMeta: false, - showOrderCodesMeta: false, - }); + this.setData( + { + activePickCode: task ? task.pick_code : '', + activePickCodes: group.pickCodes, + activeGroupKey: group.key, + scopePickerIndex: groupIndex, + scopeMenuOpen: false, + skuCatalogMode: false, + skuSections: [], + dayGroups: [], + hasOpenPicks, + activeTask: task ? { ...task, pick_status: status } : { pick_status: status }, + activeItems: items, + activePendingItems: withZoneHeaders(pendingItems), + taskSummary, + pendingCount, + scanTip: '', + workflowTip: '', + showWorkTitle: false, + showCompanyMeta: false, + showOrderCodesMeta: false, + }, + () => { + this.loadBatchInfo(pendingItems); + } + ); this.emitProgress({ taskCount: (this.data.tasks || []).length, pickedCount: Number(taskSummary && taskSummary.pickedCount) || 0, @@ -491,6 +525,254 @@ Component({ }); }, + /** 按商品 id 在已加载明细中查找(itemsMap 是最新数据源) */ + findItemById(id) { + if (!id) return null; + const map = this.data.itemsMap || {}; + for (const key of Object.keys(map)) { + const found = (map[key] || []).find((item) => item.id === id); + if (found) return found; + } + return (this.data.activeItems || []).find((item) => item.id === id) || null; + }, + + /** 拉取每行候选批次并默认按先进先出预分配(只读,不扣库) */ + async loadBatchInfo(items) { + const targets = (items || []).filter( + (item) => + item && + item.id && + String(item.sku_code || '').trim() && + resolveItemNeed(item) > 0 && + !this.data.batchesMap[item.id] + ); + if (!targets.length) return; + targets.forEach((item) => { + this.setData({ + [`batchesMap.${item.id}`]: { loading: true, error: '', batches: [], plan: [] }, + }); + }); + await Promise.all( + targets.map(async (item) => { + try { + const payload = await fetchPickingOutboundBatches(item.id); + const data = payload && payload.data ? payload.data : payload || {}; + const batches = (data.batches || []).map((b) => ({ + batch_id: b.batch_id, + batch_no: String(b.batch_no), + available_qty: Number(b.available_qty) || 0, + storage_zone: b.storage_zone || '', + inbound_date: b.inbound_date || '', + production_date: b.production_date || '', + })); + const need = resolveItemNeed(item); + const serverPlan = Array.isArray(item.outbound_batches) + ? item.outbound_batches + .map((p) => ({ + batch_no: String((p && p.batch_no) || ''), + qty: Number(p && p.qty) || 0, + })) + .filter((p) => p.batch_no && p.qty > 0) + : []; + if (serverPlan.length) { + this.setData({ + [`batchesMap.${item.id}`]: { + loading: false, + error: '', + batches, + claimable: Number(data.claimable) || 0, + total_available: Number(data.total_available) || 0, + other_reserved: Number(data.other_reserved) || 0, + need, + plan: serverPlan, + manual: true, + shortfall: allocateBatchesFifo(batches, need).shortfall, + plan_text: formatBatchPlanText(serverPlan, batches), + }, + }); + return; + } + const { plan, shortfall } = allocateBatchesFifo(batches, need); + this.setData({ + [`batchesMap.${item.id}`]: { + loading: false, + error: '', + batches, + claimable: Number(data.claimable) || 0, + total_available: Number(data.total_available) || 0, + other_reserved: Number(data.other_reserved) || 0, + need, + plan, + manual: false, + shortfall, + plan_text: formatBatchPlanText(plan, batches), + }, + }); + } catch (err) { + this.setData({ + [`batchesMap.${item.id}`]: { + loading: false, + error: (err && err.message) || '批次加载失败', + batches: [], + plan: [], + }, + }); + } + }) + ); + }, + + /** 本行要提交的出库批次计划;无批次信息返回 null(= 服务端按 FIFO) */ + resolveItemPlan(item) { + if (!item || !item.id) return null; + const info = this.data.batchesMap[item.id]; + if (!info || !Array.isArray(info.batches) || !info.batches.length) return null; + if (info.manual && Array.isArray(info.plan) && info.plan.length) return info.plan; + const need = resolveItemNeed(item); + if (!(need > 0)) return null; + const plan = allocateBatchesFifo(info.batches, need).plan; + return plan.length ? plan : null; + }, + + /** 勾选/改量后,未手改过的行按新数量重算 FIFO 预分配 */ + refreshItemBatchPlan(id) { + const info = this.data.batchesMap[id]; + if (!info || info.manual || !Array.isArray(info.batches) || !info.batches.length) return; + const item = this.findItemById(id); + if (!item) return; + const need = resolveItemNeed(item); + const { plan, shortfall } = allocateBatchesFifo(info.batches, need); + this.setData({ + [`batchesMap.${id}.need`]: need, + [`batchesMap.${id}.plan`]: plan, + [`batchesMap.${id}.shortfall`]: shortfall, + [`batchesMap.${id}.plan_text`]: formatBatchPlanText(plan, info.batches), + }); + }, + + /** 给待提交明细注入「本次出库批次」 */ + withPlans(items) { + return (items || []).map((item) => { + const plan = this.resolveItemPlan(item); + return plan ? { ...item, outbound_batches: plan } : item; + }); + }, + + sumEditorQty(rows) { + const total = (rows || []).reduce((sum, row) => sum + (Number(row.qty) || 0), 0); + return Math.round(total * 1000) / 1000; + }, + + openBatchEditor(e) { + const id = e.currentTarget.dataset.id; + const item = this.findItemById(id); + const info = this.data.batchesMap[id]; + if (!item || !info || !Array.isArray(info.batches) || !info.batches.length) { + wx.showToast({ title: '暂无可扣批次', icon: 'none' }); + return; + } + const need = resolveItemNeed(item); + const basePlan = + info.manual && Array.isArray(info.plan) + ? info.plan + : allocateBatchesFifo(info.batches, need).plan; + const qtyByNo = new Map((basePlan || []).map((p) => [String(p.batch_no), Number(p.qty) || 0])); + const rows = info.batches.map((b) => ({ + batch_no: String(b.batch_no), + storage_zone: b.storage_zone || '', + inbound_date: b.inbound_date || '', + available_qty: Number(b.available_qty) || 0, + qty: formatBatchQty(qtyByNo.get(String(b.batch_no)) || 0), + })); + this.setData({ + editor: { + itemId: id, + name: item.display_name || item.item_name || '商品', + unit: item.unit || '', + need, + claimable: Number(info.claimable) || 0, + rows, + total: this.sumEditorQty(rows), + shortfall: Number(info.shortfall) || 0, + }, + }); + }, + + closeBatchEditor() { + if (this.data.editor) this.setData({ editor: null }); + }, + + noop() {}, + + onBatchQtyInput(e) { + const index = Number(e.currentTarget.dataset.index); + const editor = this.data.editor; + if (!editor) return; + const rows = (editor.rows || []).map((row, i) => + i === index ? { ...row, qty: e.detail.value } : row + ); + this.setData({ 'editor.rows': rows, 'editor.total': this.sumEditorQty(rows) }); + }, + + moveBatchRow(e) { + const index = Number(e.currentTarget.dataset.index); + const dir = Number(e.currentTarget.dataset.dir); + const editor = this.data.editor; + if (!editor) return; + const rows = (editor.rows || []).slice(); + const target = index + dir; + if (target < 0 || target >= rows.length) return; + const tmp = rows[index]; + rows[index] = rows[target]; + rows[target] = tmp; + this.setData({ 'editor.rows': rows }); + }, + + resetBatchEditorFifo() { + const editor = this.data.editor; + if (!editor) return; + const info = this.data.batchesMap[editor.itemId]; + if (!info || !Array.isArray(info.batches)) return; + const item = this.findItemById(editor.itemId); + const need = item ? resolveItemNeed(item) : editor.need; + const { plan } = allocateBatchesFifo(info.batches, need); + const qtyByNo = new Map(plan.map((p) => [String(p.batch_no), Number(p.qty) || 0])); + const rows = info.batches.map((b) => ({ + batch_no: String(b.batch_no), + storage_zone: b.storage_zone || '', + inbound_date: b.inbound_date || '', + available_qty: Number(b.available_qty) || 0, + qty: formatBatchQty(qtyByNo.get(String(b.batch_no)) || 0), + })); + this.setData({ + 'editor.rows': rows, + 'editor.need': need, + 'editor.total': this.sumEditorQty(rows), + }); + }, + + applyBatchEditor() { + const editor = this.data.editor; + if (!editor) return; + const plan = (editor.rows || []) + .map((row) => ({ + batch_no: String(row.batch_no), + qty: Math.round((Number(row.qty) || 0) * 1000) / 1000, + })) + .filter((row) => row.qty > 0); + const info = this.data.batchesMap[editor.itemId] || { batches: [] }; + this.setData({ + [`batchesMap.${editor.itemId}`]: { + ...info, + manual: true, + need: editor.need, + plan, + plan_text: formatBatchPlanText(plan, info.batches), + }, + editor: null, + }); + }, + refreshActiveTaskView(pickCode, items) { const patch = { [`itemsMap.${pickCode}`]: items, @@ -520,6 +802,7 @@ Component({ } } this.setData(patch); + this.refreshItemBatchPlan(id); }, onFieldInput(e) { @@ -562,6 +845,7 @@ Component({ ); }); this.refreshActiveTaskView(pick, items); + this.refreshItemBatchPlan(id); }, onQtyInput(e) { @@ -608,6 +892,9 @@ Component({ picked_weight: targetMeasures.picked_weight, unit: target.unit || null, diff_reason: target.diff_reason_input || target.diff_reason || '', + outbound_batches: Array.isArray(target.outbound_batches) + ? target.outbound_batches + : undefined, }); } return rows; @@ -640,7 +927,7 @@ Component({ try { await confirmPickingComplete({ pick_code: pickCode, - items: buildProgressRows(items, pickCode), + items: buildProgressRows(this.withPlans(items), pickCode), }); wx.showToast({ title: '分拣完成,订单进入待配送', icon: 'success', duration: 2500 }); await this.loadRows(); @@ -669,7 +956,7 @@ Component({ (item) => item.can_pick || (Number(item.review_status) || 0) < 20 ); if (toSave.length) { - const rows = this.buildConfirmRows(toSave); + const rows = this.buildConfirmRows(this.withPlans(toSave)); if (!rows) { this.setData({ saving: false }); return; @@ -719,6 +1006,7 @@ Component({ picked_weight: targetMeasures.picked_weight, unit: target.unit || null, diff_reason: target.diff_reason_input || target.diff_reason || '', + outbound_batches: this.resolveItemPlan(target) || undefined, }, ]; diff --git a/miniprogram/components/picking-panel/index.wxml b/miniprogram/components/picking-panel/index.wxml index 7bd0593..baffd2b 100644 --- a/miniprogram/components/picking-panel/index.wxml +++ b/miniprogram/components/picking-panel/index.wxml @@ -74,56 +74,78 @@ 待 {{pendingCount}} - + + {{item.zone_label}} 确认 - {{item.display_name}} - 需求 {{item.required_qty}}{{item.unit || ''}} - - - {{item.qty_chip_label}} - + + - - - 重量 - 确认 + {{item.display_name}} + 需求 {{item.required_qty}}{{item.unit || ''}} + + + {{item.qty_chip_label}} + + + + 重量 + + + + + 已拣 {{item.picked_qty_num || 0}}{{item.unit || ''}} + + + catchtap="printCurrentPick" + >{{printing ? '打印中' : '打印'}} - - - 已拣 {{item.picked_qty_num || 0}}{{item.unit || ''}} - - {{printing ? '打印中' : '打印'}} - + + + 批次 + + 加载中 + + + {{batchesMap[item.id].plan_text}} + 缺 {{batchesMap[item.id].shortfall}} + + + {{batchesMap[item.id].error}} + + + 无可扣批次 + + 调整 + + + @@ -148,5 +170,40 @@ 分拣已完成,订单进入待配送,等待司机装车核货 + + + + + {{editor.name}} + 需 {{editor.need}}{{editor.unit}} · 可扣 {{editor.claimable}} + + + + + {{item.batch_no}} + {{item.storage_zone || '未设区域'}} · 入库 {{item.inbound_date || '—'}} · 可用 {{item.available_qty}} + + + ↑ + ↓ + + + + + + 合计 {{editor.total}} / 需 {{editor.need}} + 库存不足,还缺 {{editor.shortfall}} + + + 按先进先出 + 确定 + + diff --git a/miniprogram/components/picking-panel/index.wxss b/miniprogram/components/picking-panel/index.wxss index ea0372a..9447188 100644 --- a/miniprogram/components/picking-panel/index.wxss +++ b/miniprogram/components/picking-panel/index.wxss @@ -734,3 +734,231 @@ .btn-disabled { opacity: 0.45; } + +.zone-head { + margin: 12rpx 0 2rpx; + padding: 6rpx 4rpx; + font-size: 22rpx; + font-weight: 700; + color: #047857; +} + +.batch-line { + display: flex; + align-items: center; + gap: 8rpx; + margin-top: 8rpx; + min-width: 0; +} + +.batch-lab { + flex-shrink: 0; + padding: 2rpx 10rpx; + border-radius: 6rpx; + font-size: 20rpx; + font-weight: 600; + color: #047857; + background: #ecfdf5; +} + +.batch-sum { + flex: 1; + min-width: 0; + font-size: 22rpx; + color: #52525b; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.batch-muted { + flex: 1; + min-width: 0; + font-size: 22rpx; + color: #a1a1aa; +} + +.batch-warn { + flex-shrink: 0; + font-size: 22rpx; + font-weight: 600; + color: #dc2626; +} + +.btn-batch { + flex-shrink: 0; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + height: 44rpx; + padding: 0 18rpx; + border-radius: 999rpx; + font-size: 22rpx; + font-weight: 600; + color: #047857; + background: #fff; + border: 2rpx solid #059669; +} + +.batch-mask { + position: fixed; + left: 0; + right: 0; + top: 0; + bottom: 0; + background: rgba(15, 23, 42, 0.45); + z-index: 200; +} + +.batch-sheet { + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 201; + box-sizing: border-box; + padding: 24rpx 24rpx calc(24rpx + env(safe-area-inset-bottom)); + background: #fff; + border-radius: 24rpx 24rpx 0 0; + box-shadow: 0 -12rpx 32rpx rgba(15, 23, 42, 0.16); +} + +.batch-sheet-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12rpx; + margin-bottom: 12rpx; +} + +.batch-sheet-title { + flex: 1; + min-width: 0; + font-size: 30rpx; + font-weight: 700; + color: #0a0a0b; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.batch-sheet-sub { + flex-shrink: 0; + font-size: 22rpx; + color: #71717a; +} + +.batch-sheet-body { + max-height: 640rpx; + overflow-y: auto; +} + +.batch-row { + display: flex; + align-items: center; + gap: 12rpx; + padding: 14rpx 0; + border-bottom: 1rpx solid #f1f5f9; +} + +.batch-row-info { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4rpx; +} + +.batch-row-no { + font-size: 26rpx; + font-weight: 700; + color: #0a0a0b; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.batch-row-meta { + font-size: 20rpx; + color: #71717a; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.batch-move { + flex-shrink: 0; + display: flex; + flex-direction: column; + gap: 4rpx; +} + +.batch-move-btn { + width: 44rpx; + height: 36rpx; + line-height: 36rpx; + text-align: center; + border-radius: 8rpx; + font-size: 22rpx; + color: #52525b; + background: #f4f4f5; +} + +.batch-move-btn.is-off { + opacity: 0.35; +} + +.batch-input { + flex-shrink: 0; + box-sizing: border-box; + width: 150rpx; + height: 56rpx; + padding: 0 12rpx; + border-radius: 10rpx; + background: #f4f4f5; + font-size: 28rpx; + font-weight: 600; + font-variant-numeric: tabular-nums; + text-align: center; +} + +.batch-sheet-total { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12rpx; + margin-top: 16rpx; + font-size: 24rpx; + font-weight: 600; + color: #52525b; +} + +.batch-sheet-foot { + display: flex; + gap: 16rpx; + margin-top: 20rpx; +} + +.batch-btn { + flex: 1; + box-sizing: border-box; + display: flex; + align-items: center; + justify-content: center; + height: 84rpx; + border-radius: 20rpx; + font-size: 28rpx; + font-weight: 700; +} + +.batch-btn.ghost { + color: #047857; + background: #fff; + border: 2rpx solid #059669; +} + +.batch-btn.primary { + color: #fff; + background: linear-gradient(135deg, #047857 0%, #059669 100%); +} diff --git a/miniprogram/utils/pickingAssembly.js b/miniprogram/utils/pickingAssembly.js index 8d2accb..110f704 100644 --- a/miniprogram/utils/pickingAssembly.js +++ b/miniprogram/utils/pickingAssembly.js @@ -204,10 +204,60 @@ function buildProgressRows(items, pickCode) { unit: item.unit || null, diff_reason: item.diff_reason_input || item.diff_reason || '', pick_code: pickCode, + outbound_batches: Array.isArray(item.outbound_batches) ? item.outbound_batches : undefined, }; }); } +/** 本行本次出库需扣的总量(重量优先) */ +function resolveItemNeed(item) { + const measures = resolvePickMeasures(item); + return Number(measures.picked_weight) > 0 + ? Number(measures.picked_weight) || 0 + : Number(measures.picked_qty) || 0; +} + +/** + * 按先进先出把 need 量分配到候选批次(batches 已按 FIFO 排序)。 + * 返回 { plan:[{batch_no,qty}], shortfall };shortfall=库存总量不足的部分。 + */ +function allocateBatchesFifo(batches, need) { + const needQty = Math.max(0, Number(need) || 0); + const plan = []; + let remaining = needQty; + let availableSum = 0; + (batches || []).forEach((b) => { + const avail = Number(b.available_qty) || 0; + if (avail <= 0) return; + availableSum += avail; + if (remaining <= 0) return; + const take = Math.min(avail, remaining); + plan.push({ batch_no: String(b.batch_no), qty: Math.round(take * 1000) / 1000 }); + remaining = Math.round((remaining - take) * 1000) / 1000; + }); + return { plan, shortfall: Math.round(Math.max(0, needQty - availableSum) * 1000) / 1000 }; +} + +/** 行内批次摘要文案:`10-08 20 · 10-09 10`(入库日 + 数量) */ +function formatBatchPlanText(plan, batches) { + const byNo = new Map(); + (batches || []).forEach((b) => byNo.set(String(b.batch_no), b)); + return (plan || []) + .map((p) => { + const b = byNo.get(String(p.batch_no)) || {}; + const date = displayText(b.inbound_date || b.created_at).slice(5, 10); + const qty = formatBatchQty(p.qty); + return [date, qty].filter(Boolean).join(' '); + }) + .filter(Boolean) + .join(' · '); +} + +function formatBatchQty(value) { + const num = Number(value) || 0; + return String(Math.round(num * 1000) / 1000); +} + module.exports = { PICK_STATUS_LABELS, displayText, @@ -221,4 +271,8 @@ module.exports = { normalizePickingItem, summarizeTask, buildProgressRows, + resolveItemNeed, + allocateBatchesFifo, + formatBatchPlanText, + formatBatchQty, }; diff --git a/miniprogram/utils/request.js b/miniprogram/utils/request.js index 7bb227a..d40502a 100644 --- a/miniprogram/utils/request.js +++ b/miniprogram/utils/request.js @@ -673,6 +673,12 @@ function confirmPickingComplete(payload) { }); } +function fetchPickingOutboundBatches(pickItemId) { + const id = String(pickItemId || '').trim(); + const qs = id ? `?pick_item_id=${encodeURIComponent(id)}` : ''; + return request(`/mobile/picking/outbound-batches${qs}`); +} + function scanPickingBarcode(payload) { return request('/mobile/picking/scan', { method: 'POST', @@ -1313,6 +1319,7 @@ module.exports = { createPickingPrintJobs, savePickingProgress, confirmPickingComplete, + fetchPickingOutboundBatches, scanPickingBarcode, searchPurchaseSkus, createSelfPurchaseStockInbound, diff --git a/server/src/modules/workflow/routes/pickingRoutes.ts b/server/src/modules/workflow/routes/pickingRoutes.ts index 72ceda5..0c54e71 100644 --- a/server/src/modules/workflow/routes/pickingRoutes.ts +++ b/server/src/modules/workflow/routes/pickingRoutes.ts @@ -16,6 +16,7 @@ import { listPickingAssignees, assignPickingTaskPicker, rebuildUntouchedOpenPickingTasks, + listPickingOutboundBatches, } from '../../../services/pickingOps'; import { getPickingTaskMode, @@ -278,6 +279,21 @@ export function mountPickingWorkflowRoutes(router: Router): void { } }); + /** 只读:某分拣明细的「本次可扣批次」(默认 FIFO 顺序 + SKU 级汇总),供 UI 预分配。不扣库。 */ + router.get('/picking/outbound-batches', authMiddleware, async (req: AuthRequest, res) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['picking_manage', 'delivery_manage', 'inventory_manage']); + const data = await listPickingOutboundBatches({ + pickItemId: String(req.query?.pick_item_id || ''), + ctx, + }); + return res.json({ data }); + } catch (error: any) { + return sendWorkflowError(res, error, '加载可扣批次失败'); + } + }); + router.post('/picking/outbound', authMiddleware, async (req: AuthRequest, res) => { try { const ctx = await getWorkflowCtx(req); diff --git a/server/src/routes/mobile/mobileWarehouseRoutes.ts b/server/src/routes/mobile/mobileWarehouseRoutes.ts index 3348889..1781940 100644 --- a/server/src/routes/mobile/mobileWarehouseRoutes.ts +++ b/server/src/routes/mobile/mobileWarehouseRoutes.ts @@ -24,6 +24,7 @@ import { updatePickingItemProgress, submitPickingAudit, confirmPickingComplete, + listPickingOutboundBatches, listMyPickingTasks, } from '../../services/pickingOps'; import { isPickingBarcodeEnabled } from '../../services/pickingBarcodeService'; @@ -769,6 +770,24 @@ router.post('/picking/complete', authMiddleware, async (req: AuthRequest, res: R } }); +/** 只读:某分拣明细的「本次可扣批次」(默认 FIFO 顺序 + SKU 级汇总),供小程序预分配。不扣库。 */ +router.get('/picking/outbound-batches', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + await requirePickingAccess(req); + const ctx = await loadTenantContext(req.userId); + const data = await listPickingOutboundBatches({ + pickItemId: String(req.query?.pick_item_id || ''), + ctx, + }); + return res.json({ success: true, data }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '加载可扣批次失败', + }); + } +}); + /** 兼容旧名:仅分拣完成,不再自动出库 */ router.post('/picking/audit', authMiddleware, async (req: AuthRequest, res: Response) => { try { diff --git a/server/src/services/inventoryOutboundService.ts b/server/src/services/inventoryOutboundService.ts index 73e2479..0c3499a 100644 --- a/server/src/services/inventoryOutboundService.ts +++ b/server/src/services/inventoryOutboundService.ts @@ -8,6 +8,7 @@ import { import { notifyInventoryShortage } from './inventoryShortageNotificationService'; import { isPassThroughSku } from './stockModeService'; import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery'; +import { writeAuditLog } from './auditService'; export interface InventoryDeductBatch { batchNo: string; @@ -83,9 +84,11 @@ export async function fifoDeductInventory( remark?: string | null; /** 默认 true:扣库不得超过「毛可用−他单预留」 */ respectOtherReservations?: boolean; + /** 手选批次计划(可选):按顺序/数量优先扣;**不传 = 纯 FIFO(逐字不变)** */ + batchPlan?: Array<{ batchNo: string; qty: number }> | null; }, onBatchDeducted?: ( - batch: { batchNo: string; costPrice: number; supplierCode?: string | null }, + batch: { batchNo: string; costPrice: number; supplierCode?: string | null; inboundAt?: string | null }, deductedQty: number, costPrice: number ) => void @@ -149,7 +152,7 @@ export async function fifoDeductInventory( branchFilter = `AND inv.branch_code = $${params.length}`; } return client.query( - `SELECT inv.id, inv.batch_no, inv.available_qty, inv.cost_price, inv.supplier_code + `SELECT inv.id, inv.batch_no, inv.available_qty, inv.cost_price, inv.supplier_code, inv.created_at FROM picking_items pi JOIN inspections insp ON insp.order_code = pi.order_code @@ -171,7 +174,7 @@ export async function fifoDeductInventory( } // SELECT 里带上 supplier_code,供加工领料追溯来源 return client.query( - `SELECT id, batch_no, available_qty, cost_price, supplier_code FROM inventory + `SELECT id, batch_no, available_qty, cost_price, supplier_code, created_at FROM inventory WHERE sku_code = $1 AND available_qty > 0 ${branchFilter} ORDER BY expiry_date ASC NULLS LAST, created_at ASC FOR UPDATE`, @@ -191,10 +194,40 @@ export async function fifoDeductInventory( } } - for (const batch of batches.rows) { + // 手选批次计划(可选):先按计划顺序/数量扣,其余批次按 FIFO 兜底。 + // 不传 batchPlan ⇒ map 为空、orderedRows === batches.rows ⇒ 与改前逐字一致。 + const planQtyByBatch = new Map(); + const planOrderByBatch = new Map(); + for (const p of input.batchPlan || []) { + const bn = String(p?.batchNo || '').trim(); + const q = Number(p?.qty); + if (!bn || !Number.isFinite(q) || q <= 0) continue; + planQtyByBatch.set(bn, q); + if (!planOrderByBatch.has(bn)) planOrderByBatch.set(bn, planOrderByBatch.size); + } + let orderedRows: any[] = batches.rows; + if (planQtyByBatch.size) { + const planned: any[] = []; + const rest: any[] = []; + for (const row of batches.rows) { + if (planOrderByBatch.has(String(row.batch_no))) planned.push(row); + else rest.push(row); + } + planned.sort( + (a, b) => + (planOrderByBatch.get(String(a.batch_no)) || 0) - + (planOrderByBatch.get(String(b.batch_no)) || 0) + ); + orderedRows = [...planned, ...rest]; + } + + for (const batch of orderedRows) { if (remaining <= 0) break; const beforeQty = Number(batch.available_qty) || 0; - const deductQty = Math.min(beforeQty, remaining); + // 手选批次:本批扣减不超过「该批可用」与「计划指定量」的较小者 + const planCap = planQtyByBatch.get(String(batch.batch_no)); + const deductQty = Math.min(planCap != null ? Math.min(beforeQty, planCap) : beforeQty, remaining); + if (deductQty <= 0) continue; const afterQty = Math.round((beforeQty - deductQty) * 100) / 100; remaining = Math.round((remaining - deductQty) * 100) / 100; const batchCostPrice = Number(batch.cost_price) || 0; @@ -227,6 +260,7 @@ export async function fifoDeductInventory( batchNo: String(batch.batch_no), costPrice: batchCostPrice, supplierCode: batch.supplier_code != null ? String(batch.supplier_code) : null, + inboundAt: batch.created_at ? new Date(batch.created_at).toISOString() : null, }, deductQty, batchCostPrice @@ -513,6 +547,30 @@ export async function deductInventoryForOrderDeparture( String(options?.taskCode || '') || `DL-${code}`; + // 分拣「完成」时手选的出库批次计划(picking_items.outbound_batches)⇒ 发车优先按它扣;无则纯 FIFO。 + const planById = new Map>(); + { + const ids = deductLines.map((r) => String(r.id)).filter(Boolean); + if (ids.length) { + const planRes = await client.query( + `SELECT id, outbound_batches FROM picking_items WHERE id = ANY($1::uuid[])`, + [ids] + ); + for (const pr of planRes.rows) { + const raw = (pr as { outbound_batches?: unknown }).outbound_batches; + if (!Array.isArray(raw)) continue; + const plan: Array<{ batchNo: string; qty: number }> = []; + for (const x of raw) { + const bn = String((x as any)?.batch_no ?? (x as any)?.batchNo ?? '').trim(); + const q = Number((x as any)?.qty); + if (!bn || !Number.isFinite(q) || q <= 0) continue; + plan.push({ batchNo: bn, qty: q }); + } + if (plan.length) planById.set(String((pr as { id?: unknown }).id), plan); + } + } + } + const softSkipped: Array<{ sku: string; itemName: string | null; @@ -520,6 +578,14 @@ export async function deductInventoryForOrderDeparture( message: string; }> = []; let deductedAny = false; + /** 出库留痕:逐批次(品名/批次/入库日/数量) */ + const departDetail: Array<{ + sku_code: string | null; + sku_name: string | null; + batch_no: string; + inbound_at: string | null; + qty: number; + }> = []; for (const row of deductLines) { if (row.needSkuBackfill) { @@ -552,6 +618,16 @@ export async function deductInventoryForOrderDeparture( itemName: row.item_name, operationType: 'delivery_loading_out', remark: `配送核货出库 ${options?.taskCode || pickCode}`, + batchPlan: planById.get(String(row.id)) || undefined, + }, + (batch, deductedQty) => { + departDetail.push({ + sku_code: row.sku || null, + sku_name: row.item_name ? String(row.item_name) : null, + batch_no: batch.batchNo, + inbound_at: batch.inboundAt ?? null, + qty: deductedQty, + }); }); deductedAny = true; } catch (error: any) { @@ -570,6 +646,54 @@ export async function deductInventoryForOrderDeparture( await consumeReservationsForOrder(client, code); if (ownsTxn) await client.query('COMMIT'); + // 出库留痕到系统操作日志(操作人 + 分拣员 + 逐批次:品名/批次/入库日/数量) + if (departDetail.length) { + try { + const pickCodes = Array.from( + new Set(deductLines.map((r) => String(r.pick_code || '')).filter(Boolean)) + ); + let pickerIds: string[] = []; + let pickerNames: string[] = []; + if (pickCodes.length) { + const pr = await pool.query( + `SELECT DISTINCT pt.uid, p.name + FROM ( + SELECT COALESCE(reviewer_id, pick_completed_by) AS uid + FROM picking_tasks WHERE pick_code = ANY($1::text[]) + ) pt + LEFT JOIN public.profiles p ON p.id = pt.uid + WHERE pt.uid IS NOT NULL`, + [pickCodes] + ); + pickerIds = pr.rows.map((r) => String(r.uid)).filter((v) => v && v !== 'null'); + pickerNames = Array.from( + new Set( + pr.rows + .map((r) => (r.name != null ? String(r.name).trim() : '')) + .filter(Boolean) + ) + ); + } + await writeAuditLog({ + operatorId: options?.operatorId || null, + operationType: 'picking_outbound', + targetTable: 'orders', + targetId: code, + oldValue: null, + newValue: { + order_code: code, + pick_codes: pickCodes, + picker_ids: pickerIds, + picker_names: pickerNames, + batches: departDetail, + }, + branchCode: branchCode || null, + actionCategory: 'inventory', + }); + } catch (auditError) { + console.error('[depart] writeAuditLog(outbound) failed:', auditError); + } + } if (softSkipped.length && !deductedAny) { return { deducted: false, diff --git a/server/src/services/pickingOps.ts b/server/src/services/pickingOps.ts index 8676d38..792f731 100644 --- a/server/src/services/pickingOps.ts +++ b/server/src/services/pickingOps.ts @@ -17,6 +17,7 @@ export { updatePickingItemProgress, submitPickingAudit, confirmPickingComplete, + listPickingOutboundBatches, listPickingAssignees, assignPickingTaskPicker, rebuildUntouchedOpenPickingTasks, diff --git a/server/src/services/pickingService.ts b/server/src/services/pickingService.ts index 1f6f3ab..433b539 100644 --- a/server/src/services/pickingService.ts +++ b/server/src/services/pickingService.ts @@ -27,6 +27,7 @@ import { consumeReservationsForOrder, getClaimableStockQty, listPurchaseMergePee import { fifoDeductInventory, orderSkuSkippedPassThroughLedger } from './inventoryOutboundService'; import { notifyInventoryShortage } from './inventoryShortageNotificationService'; import { isPassThroughSku } from './stockModeService'; +import { writeAuditLog } from './auditService'; import { supplierSkipInboundExistsSql } from './supplierSkipInbound'; import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery'; import { @@ -44,8 +45,23 @@ type PickingProgressRow = { picked_weight?: number; diff_reason?: string; unit?: string | null; + /** 手选出库批次计划(分拣完成时选定);不传=不动,[]/空=默认 FIFO */ + outbound_batches?: Array<{ batch_no: string; qty: number }> | null; }; +/** 归一化手选批次计划 → [{batch_no, qty}];非法项丢弃;无有效项返回 null */ +function normalizeOutboundBatches(raw: unknown): Array<{ batch_no: string; qty: number }> | null { + if (!Array.isArray(raw)) return null; + const out: Array<{ batch_no: string; qty: number }> = []; + for (const x of raw) { + const bn = String((x as any)?.batch_no ?? (x as any)?.batchNo ?? '').trim(); + const q = Number((x as any)?.qty); + if (!bn || !Number.isFinite(q) || q <= 0) continue; + out.push({ batch_no: bn, qty: q }); + } + return out.length ? out : null; +} + function isTruthyFlag(value: unknown): boolean { return value === true || value === 't' || value === 'true' || value === 1; } @@ -739,9 +755,21 @@ export async function updatePickingItemProgress(input: { await client.query( `UPDATE picking_items SET picked_qty = $1, picked_weight = $2, review_status = $3, diff_reason = $4, - unit = COALESCE($7::varchar, unit) + unit = COALESCE($7::varchar, unit), + outbound_batches = COALESCE($8::jsonb, outbound_batches) WHERE id = $5 AND pick_code = $6`, - [saved.picked_qty, saved.picked_weight, itemStatus, row.diff_reason || null, row.id, input.pickCode, unit] + [ + saved.picked_qty, + saved.picked_weight, + itemStatus, + row.diff_reason || null, + row.id, + input.pickCode, + unit, + row.outbound_batches !== undefined + ? JSON.stringify(normalizeOutboundBatches(row.outbound_batches) || []) + : null, + ] ); } @@ -830,9 +858,21 @@ export async function confirmPickingComplete(input: { await client.query( `UPDATE picking_items SET picked_qty = $1, picked_weight = $2, review_status = $3, diff_reason = $4, - unit = COALESCE($7::varchar, unit) + unit = COALESCE($7::varchar, unit), + outbound_batches = COALESCE($8::jsonb, outbound_batches) WHERE id = $5 AND pick_code = $6`, - [saved.picked_qty, saved.picked_weight, itemStatus, row.diff_reason || null, row.id, pickCode, unit] + [ + saved.picked_qty, + saved.picked_weight, + itemStatus, + row.diff_reason || null, + row.id, + pickCode, + unit, + row.outbound_batches !== undefined + ? JSON.stringify(normalizeOutboundBatches(row.outbound_batches) || []) + : null, + ] ); } } @@ -917,6 +957,97 @@ export async function confirmPickingComplete(input: { } /** 兼容旧名:仅分拣完成,不再自动出库、不调单 */ +/** pg 的 date/timestamptz → 中国时区 'YYYY-MM-DD' */ +function toDateOnlyLocal(v: unknown): string | null { + if (v == null) return null; + const d = v instanceof Date ? v : new Date(String(v)); + if (Number.isNaN(d.getTime())) return null; + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +/** + * 某分拣明细「本次可扣批次」:逐批可用 + SKU 级汇总(总可用 / 他单预留 / 本次可扣)。 + * **只读**,不扣库。默认按 FIFO 顺序返回,供 UI 预分配。 + * 见 docs/design/20261031-分拣出库可选批次与区域分组.md + */ +export async function listPickingOutboundBatches(input: { + pickItemId: string; + ctx?: TenantContext | null; +}): Promise<{ + sku_code: string | null; + order_code: string | null; + total_available: number; + other_reserved: number; + claimable: number; + batches: Array<{ + batch_id: string; + batch_no: string; + available_qty: number; + storage_zone: string | null; + inbound_date: string | null; + production_date: string | null; + }>; +}> { + const pickItemId = String(input.pickItemId || '').trim(); + if (!pickItemId) throw Object.assign(new Error('缺少分拣明细'), { status: 400 }); + const itemRes = await pool.query( + `SELECT pi.sku_code, pi.order_code, pt.branch_code + FROM picking_items pi + LEFT JOIN picking_tasks pt ON pt.pick_code = pi.pick_code + WHERE pi.id = $1::uuid LIMIT 1`, + [pickItemId] + ); + const item = itemRes.rows[0]; + if (!item) throw Object.assign(new Error('分拣明细不存在'), { status: 404 }); + const skuCode = String(item.sku_code || '').trim(); + const orderCode = String(item.order_code || '').trim() || null; + const branchCode = item.branch_code ? String(item.branch_code) : null; + if ( + input.ctx?.branchCode && + branchCode && + branchCode !== input.ctx.branchCode && + !input.ctx.isSuperAdmin + ) { + throw Object.assign(new Error('无权查看其他分公司分拣明细'), { status: 403 }); + } + + const params: unknown[] = [skuCode]; + let branchFilter = ''; + if (branchCode) { + params.push(branchCode); + branchFilter = `AND branch_code = $${params.length}`; + } + const batchRes = await pool.query( + `SELECT id, batch_no, available_qty, storage_zone, created_at, production_date + FROM inventory + WHERE sku_code = $1 AND available_qty > 0 ${branchFilter} + ORDER BY expiry_date ASC NULLS LAST, created_at ASC`, + params + ); + const batches = batchRes.rows.map((r) => ({ + batch_id: String(r.id), + batch_no: String(r.batch_no), + available_qty: Number(r.available_qty) || 0, + storage_zone: r.storage_zone == null ? null : String(r.storage_zone), + inbound_date: toDateOnlyLocal(r.created_at), + production_date: toDateOnlyLocal(r.production_date), + })); + const totalAvailable = batches.reduce((s, b) => s + b.available_qty, 0); + const claimable = await getClaimableStockQty(pool, skuCode, branchCode, orderCode || undefined); + const round3 = (n: number) => Math.round(n * 1000) / 1000; + return { + sku_code: skuCode || null, + order_code: orderCode, + total_available: round3(totalAvailable), + other_reserved: round3(Math.max(0, totalAvailable - claimable)), + claimable: round3(claimable), + batches, + }; +} + export async function submitPickingAudit(input: { pickCode: string; reviewerId?: string | null; @@ -943,9 +1074,16 @@ async function fifoDeduct( pickItemId?: string | null; operatorId?: string | null; itemName?: string | null; - } + /** 手选批次计划;不传 = 纯 FIFO */ + batchPlan?: Array<{ batchNo: string; qty: number }> | null; + }, + onBatchDeducted?: ( + batch: { batchNo: string; costPrice: number; supplierCode?: string | null; inboundAt?: string | null }, + deductedQty: number, + costPrice: number + ) => void ) { - return fifoDeductInventory(client, input); + return fifoDeductInventory(client, input, onBatchDeducted); } async function resolvePickingItemSkus( @@ -1159,6 +1297,8 @@ export async function completePickingOutbound(input: { pickCode: string; operatorId?: string | null; ctx?: TenantContext | null; + /** 手选批次计划(按分拣明细 id);不传 = 全部按 FIFO */ + itemPlans?: Array<{ pickItemId: string; batches: Array<{ batchNo: string; qty: number }> }> | null; }) { const client = await pool.connect(); try { @@ -1199,6 +1339,21 @@ export async function completePickingOutbound(input: { ); if (!allItems.rows.length) throw businessError('分拣任务没有明细'); + // 手选批次计划:按分拣明细 id 归组(不传则全部走 FIFO) + const planByItem = new Map>(); + for (const plan of input.itemPlans || []) { + const id = String(plan?.pickItemId || '').trim(); + if (!id || !Array.isArray(plan?.batches)) continue; + planByItem.set(id, plan.batches); + } + const outboundDetail: Array<{ + sku_code: string | null; + sku_name: string | null; + batch_no: string; + inbound_at: string | null; + qty: number; + }> = []; + for (const code of new Set( allItems.rows .map((r: { order_code?: string | null }) => String(r.order_code || '').trim()) @@ -1261,16 +1416,29 @@ export async function completePickingOutbound(input: { ) { continue; } - await fifoDeduct(client, { - skuCode: trimSku(item.sku_code), - qty: outboundQty, - branchCode: task.branch_code, - orderCode: item.order_code || task.order_code, - pickCode: input.pickCode, - pickItemId: item.id, - operatorId: input.operatorId, - itemName: item.item_name, - }); + await fifoDeduct( + client, + { + skuCode: trimSku(item.sku_code), + qty: outboundQty, + branchCode: task.branch_code, + orderCode: item.order_code || task.order_code, + pickCode: input.pickCode, + pickItemId: item.id, + operatorId: input.operatorId, + itemName: item.item_name, + batchPlan: planByItem.get(String(item.id)) || undefined, + }, + (batch, deductedQty) => { + outboundDetail.push({ + sku_code: trimSku(item.sku_code) || null, + sku_name: item.item_name ? String(item.item_name) : null, + batch_no: batch.batchNo, + inbound_at: batch.inboundAt ?? null, + qty: deductedQty, + }); + } + ); } await client.query( @@ -1324,6 +1492,26 @@ export async function completePickingOutbound(input: { await ensureDeliveryTaskForOrder(orderCode, task.branch_code || null); } } + // 出库留痕到系统操作日志(分拣员 + 逐批次:品名/批次/入库日/数量) + try { + await writeAuditLog({ + operatorId: input.operatorId || null, + operationType: 'picking_outbound', + targetTable: 'picking_tasks', + targetId: input.pickCode, + oldValue: null, + newValue: { + pick_code: input.pickCode, + order_codes: relatedOrderCodes, + batches: outboundDetail, + }, + branchCode: task.branch_code || null, + actionCategory: 'picking', + }); + } catch (auditError) { + console.error('[picking] writeAuditLog(outbound) failed:', auditError); + } + return { success: true }; } catch (error) { await client.query('ROLLBACK').catch(() => undefined); @@ -2598,6 +2786,8 @@ const PICKING_ITEMS_ENRICHED_SQL = ` NULLIF(TRIM(catalog.code), '') ) AS barcode, pcn.container_code, pcn.staged_at, + s.storage_zone AS storage_zone, + pi.outbound_batches, o_del.delivery_date::text AS delivery_date FROM picking_items pi LEFT JOIN order_items oi ON oi.id = pi.order_item_id diff --git a/src/i18n/locales/en/picking.ts b/src/i18n/locales/en/picking.ts index 62f03c0..f448d1a 100644 --- a/src/i18n/locales/en/picking.ts +++ b/src/i18n/locales/en/picking.ts @@ -32,6 +32,21 @@ export const picking: MessageDict = { 'itemCol.weight': 'Picked weight', 'itemCol.diff': 'Variance', 'itemCol.container': 'Container', + 'itemCol.batch': 'Outbound batches', + 'batch.title': 'Adjust outbound batches', + 'batch.adjust': 'Adjust', + 'batch.loading': 'Loading', + 'batch.none': 'No available batches', + 'batch.fail': 'Failed to load batches', + 'batch.noZone': 'No zone', + 'batch.shortfall': 'Insufficient stock, short by {qty}', + 'batch.summary': 'Need {need}{unit} · Claimable {claimable}', + 'batch.rowMeta': '{zone} · Inbound {date} · Available {qty}', + 'batch.total': 'Total {total} / need {need}', + 'batch.resetFifo': 'Reset to FIFO', + 'batch.apply': 'Apply', + 'batch.moveUp': 'Move up', + 'batch.moveDown': 'Move down', 'status.pending': 'Pending pick', 'status.inProgress': 'Picking', 'status.done': 'Pick complete', diff --git a/src/i18n/locales/id/picking.ts b/src/i18n/locales/id/picking.ts index 93a76bb..0ac3d9a 100644 --- a/src/i18n/locales/id/picking.ts +++ b/src/i18n/locales/id/picking.ts @@ -32,6 +32,21 @@ export const picking: MessageDict = { 'itemCol.weight': 'Berat diambil', 'itemCol.diff': 'Selisih', 'itemCol.container': 'Keranjang', + 'itemCol.batch': 'Batch keluar', + 'batch.title': 'Sesuaikan batch keluar', + 'batch.adjust': 'Sesuaikan', + 'batch.loading': 'Memuat', + 'batch.none': 'Tidak ada batch tersedia', + 'batch.fail': 'Gagal memuat batch', + 'batch.noZone': 'Tanpa zona', + 'batch.shortfall': 'Stok kurang, kurang {qty}', + 'batch.summary': 'Butuh {need}{unit} · Dapat diklaim {claimable}', + 'batch.rowMeta': '{zone} · Masuk {date} · Tersedia {qty}', + 'batch.total': 'Total {total} / butuh {need}', + 'batch.resetFifo': 'Atur ke FIFO', + 'batch.apply': 'Terapkan', + 'batch.moveUp': 'Naik', + 'batch.moveDown': 'Turun', 'status.pending': 'Menunggu sortir', 'status.inProgress': 'Sedang sortir', 'status.done': 'Sortir selesai', diff --git a/src/i18n/locales/zh-CN/picking.ts b/src/i18n/locales/zh-CN/picking.ts index e601861..fe3454e 100644 --- a/src/i18n/locales/zh-CN/picking.ts +++ b/src/i18n/locales/zh-CN/picking.ts @@ -32,6 +32,21 @@ export const picking: MessageDict = { 'itemCol.weight': '实拣重量', 'itemCol.diff': '差异', 'itemCol.container': '装框', + 'itemCol.batch': '出库批次', + 'batch.title': '调整出库批次', + 'batch.adjust': '调整', + 'batch.loading': '加载中', + 'batch.none': '无可扣批次', + 'batch.fail': '批次加载失败', + 'batch.noZone': '未设区域', + 'batch.shortfall': '库存不足,还缺 {qty}', + 'batch.summary': '需 {need}{unit} · 可扣 {claimable}', + 'batch.rowMeta': '{zone} · 入库 {date} · 可用 {qty}', + 'batch.total': '合计 {total} / 需 {need}', + 'batch.resetFifo': '按先进先出', + 'batch.apply': '确定', + 'batch.moveUp': '上移', + 'batch.moveDown': '下移', 'status.pending': '待分拣', 'status.inProgress': '分拣中', 'status.done': '分拣完成', diff --git a/src/pages/picking/PickingManagement.tsx b/src/pages/picking/PickingManagement.tsx index 2ca6b38..dfdf229 100644 --- a/src/pages/picking/PickingManagement.tsx +++ b/src/pages/picking/PickingManagement.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useMemo, useState } from 'react'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { ClipboardCheck, @@ -21,6 +21,7 @@ import { syncPickingTasksApi, savePickingProgressApi, confirmPickingCompleteApi, + fetchPickingOutboundBatchesApi, logPickingScanApi, fetchPickingTasksApi, fetchPickingAssigneesApi, @@ -55,7 +56,7 @@ import { type PickingTaskRow, } from '../../utils/picking'; import { buildRoleLabelResolver } from '../../utils/roleLabel'; -import type { WeighMatchToleranceMode, WeighDeviceRow, PrintJobRow } from '../../utils/workflowApi'; +import type { WeighMatchToleranceMode, WeighDeviceRow, PrintJobRow, PickingOutboundBatches } from '../../utils/workflowApi'; import { useCategoryRows } from '../../hooks/useCategoryRows'; import type { DateRangeValue } from '../../components/ui/DateRangeFilterButton'; import { resolveOrderDateRange, type OrderDateField, type OrderDatePreset } from '../../components/ui/OrderDateFilter'; @@ -87,7 +88,7 @@ type PickingListColumnId = | 'status' | 'actions'; -type PickingDetailColumnId = 'product' | 'required' | 'picked' | 'weight' | 'diff' | 'container'; +type PickingDetailColumnId = 'product' | 'required' | 'picked' | 'weight' | 'diff' | 'container' | 'batch'; const PICKING_LIST_COLUMNS: Array> = [ { id: 'pick_code', label: 'col.pick_code' }, @@ -107,10 +108,11 @@ const PICKING_DETAIL_COLUMNS: Array> = [ { id: 'weight', label: 'itemCol.weight' }, { id: 'diff', label: 'itemCol.diff' }, { id: 'container', label: 'itemCol.container' }, + { id: 'batch', label: 'itemCol.batch' }, ]; const PICKING_LIST_COLUMN_ORDER_KEY = 'table_column_order:picking-list:v1'; -const PICKING_DETAIL_COLUMN_ORDER_KEY = 'table_column_order:picking-detail:v2'; +const PICKING_DETAIL_COLUMN_ORDER_KEY = 'table_column_order:picking-detail:v3'; const PRINT_DEVICE_STORAGE_KEY = 'picking-remote-print-device-id'; const PRINT_COPIES_STORAGE_KEY = 'picking-remote-print-copies'; @@ -151,6 +153,57 @@ function formatQty(value: unknown) { return Number.isInteger(num) ? String(num) : num.toFixed(2); } +type BatchPlanEntry = { batch_no: string; qty: number }; +type BatchEditorRow = { + batch_no: string; + storage_zone: string; + inbound_date: string; + available_qty: number; + qty: string; +}; + +function round3(value: number) { + return Math.round((Number(value) || 0) * 1000) / 1000; +} + +/** 按先进先出把 need 量分配到候选批次(batches 已按 FIFO 排序) */ +function fifoAllocateBatches( + batches: Array<{ batch_no: string; available_qty: number }> | undefined, + need: number +): { plan: BatchPlanEntry[]; shortfall: number } { + const needQty = Math.max(0, Number(need) || 0); + const plan: BatchPlanEntry[] = []; + let remaining = needQty; + let availableSum = 0; + for (const b of batches || []) { + const avail = Number(b.available_qty) || 0; + if (avail <= 0) continue; + availableSum += avail; + if (remaining <= 0) continue; + const take = Math.min(avail, remaining); + plan.push({ batch_no: String(b.batch_no), qty: round3(take) }); + remaining = round3(remaining - take); + } + return { plan, shortfall: round3(Math.max(0, needQty - availableSum)) }; +} + +/** 批次计划摘要:`10-08 20 · 10-09 10`(入库日 + 数量) */ +function formatBatchPlanText( + plan: BatchPlanEntry[] | undefined, + batches: Array<{ batch_no: string; inbound_date?: string | null }> | undefined +) { + const byNo = new Map(); + for (const b of batches || []) byNo.set(String(b.batch_no), b); + return (plan || []) + .map((p) => { + const b = byNo.get(String(p.batch_no)) || {}; + const date = String(b.inbound_date || '').slice(5, 10); + return [date, formatQty(p.qty)].filter(Boolean).join(' '); + }) + .filter(Boolean) + .join(' · '); +} + function taskOrderDisplay( task: PickingTaskRow, t: (key: string, vars?: Record) => string @@ -251,6 +304,13 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin const [taskItems, setTaskItems] = useState([]); const [draftQty, setDraftQty] = useState>({}); const [draftWeight, setDraftWeight] = useState>({}); + const [batchInfo, setBatchInfo] = useState< + Record + >({}); + const [manualPlan, setManualPlan] = useState>({}); + const [batchEditorItemId, setBatchEditorItemId] = useState(null); + const [batchEditorRows, setBatchEditorRows] = useState([]); + const batchCtxRef = useRef<{ pickCode: string; ids: Set }>({ pickCode: '', ids: new Set() }); const [scanBarcode, setScanBarcode] = useState(''); const [saving, setSaving] = useState(false); const [assigningPickCode, setAssigningPickCode] = useState(null); @@ -892,6 +952,129 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin return weight > 0 ? weight : qty; }; + // ---- 分拣出库批次:默认 FIFO 预分配,可手改;分拣「完成」时持久化,发车核货按此扣库 ---- + const resolveItemPlan = (item: PickingItemRow): BatchPlanEntry[] | null => { + const manual = manualPlan[item.id]; + if (manual && manual.length) return manual; + const batches = batchInfo[item.id]?.data?.batches; + if (!batches || !batches.length) return null; + const need = settlementQtyOf(item.id, item); + if (!(need > 0)) return null; + const plan = fifoAllocateBatches(batches, need).plan; + return plan.length ? plan : null; + }; + + const planByItem = useMemo(() => { + const out: Record = {}; + for (const item of taskItems) { + const manual = manualPlan[item.id]; + const batches = batchInfo[item.id]?.data?.batches || []; + const need = settlementQtyOf(item.id, item); + let plan: BatchPlanEntry[] = []; + let shortfall = 0; + if (manual && manual.length) { + plan = manual; + shortfall = fifoAllocateBatches(batches, need).shortfall; + } else if (batches.length && need > 0) { + const alloc = fifoAllocateBatches(batches, need); + plan = alloc.plan; + shortfall = alloc.shortfall; + } + out[item.id] = { plan, shortfall, text: formatBatchPlanText(plan, batches) }; + } + return out; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [taskItems, batchInfo, manualPlan, draftQty, draftWeight]); + + useEffect(() => { + if (!selectedTask) return; + const pickCode = selectedTask.pick_code; + if (batchCtxRef.current.pickCode !== pickCode) { + batchCtxRef.current = { pickCode, ids: new Set() }; + setBatchInfo({}); + setManualPlan({}); + setBatchEditorItemId(null); + } + for (const item of taskItems) { + if (!item.id || !String(item.sku_code || '').trim()) continue; + if (batchCtxRef.current.ids.has(item.id)) continue; + batchCtxRef.current.ids.add(item.id); + setBatchInfo((prev) => ({ ...prev, [item.id]: { loading: true, data: null } })); + fetchPickingOutboundBatchesApi(item.id) + .then((res) => { + setBatchInfo((prev) => ({ ...prev, [item.id]: { loading: false, data: res.data } })); + }) + .catch((error: unknown) => { + setBatchInfo((prev) => ({ + ...prev, + [item.id]: { + loading: false, + data: null, + error: error instanceof Error ? error.message : '', + }, + })); + }); + } + }, [selectedTask, taskItems]); + + const openBatchEditor = (item: PickingItemRow) => { + const batches = batchInfo[item.id]?.data?.batches || []; + if (!batches.length) { + notify(t('picking.batch.none')); + return; + } + const plan = resolveItemPlan(item) || []; + const qtyByNo = new Map(plan.map((p) => [p.batch_no, p.qty])); + setBatchEditorRows( + batches.map((b) => ({ + batch_no: String(b.batch_no), + storage_zone: b.storage_zone || '', + inbound_date: b.inbound_date || '', + available_qty: Number(b.available_qty) || 0, + qty: String(qtyByNo.get(String(b.batch_no)) ?? 0), + })) + ); + setBatchEditorItemId(item.id); + }; + + const resetBatchEditorFifo = () => { + const item = taskItems.find((row) => row.id === batchEditorItemId); + const data = batchEditorItemId ? batchInfo[batchEditorItemId]?.data : null; + if (!item || !data) return; + const { plan } = fifoAllocateBatches(data.batches, settlementQtyOf(item.id, item)); + const qtyByNo = new Map(plan.map((p) => [p.batch_no, p.qty])); + setBatchEditorRows( + (data.batches || []).map((b) => ({ + batch_no: String(b.batch_no), + storage_zone: b.storage_zone || '', + inbound_date: b.inbound_date || '', + available_qty: Number(b.available_qty) || 0, + qty: String(qtyByNo.get(String(b.batch_no)) ?? 0), + })) + ); + }; + + const applyBatchEditor = () => { + if (!batchEditorItemId) return; + const plan = batchEditorRows + .map((row) => ({ batch_no: row.batch_no, qty: round3(Number(row.qty) || 0) })) + .filter((row) => row.qty > 0); + setManualPlan((prev) => ({ ...prev, [batchEditorItemId]: plan })); + setBatchEditorItemId(null); + }; + + const moveBatchEditorRow = (index: number, dir: number) => { + setBatchEditorRows((prev) => { + const target = index + dir; + if (target < 0 || target >= prev.length) return prev; + const next = [...prev]; + const tmp = next[index]; + next[index] = next[target]; + next[target] = tmp; + return next; + }); + }; + const buildProgressItems = () => taskItems.map((item) => { const pickedQty = Number(draftQty[item.id] ?? item.picked_qty ?? 0) || 0; @@ -907,6 +1090,7 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin Math.abs(settlement - Number(item.required_qty || 0)) < 0.0001 ? '' : item.diff_reason || '', + outbound_batches: resolveItemPlan(item) || undefined, }; }); @@ -948,6 +1132,7 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin picked_qty: Number(item.required_qty) || 0, picked_weight: Number(draftWeight[item.id] ?? item.picked_weight ?? 0) || 0, diff_reason: '', + outbound_batches: resolveItemPlan(item) || undefined, })), }); notify.success(t('picking.toast.confirmed')); @@ -1166,6 +1351,7 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin picked_weight: pickedWeight, unit: item.unit || '', diff_reason: '', + outbound_batches: resolveItemPlan(item) || undefined, }; }) .filter((row) => (Number(row.picked_weight) || Number(row.picked_qty) || 0) > 0); @@ -2325,6 +2511,41 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin {item.container_code || '—'} ); + case 'batch': { + const info = planByItem[item.id]; + const meta = batchInfo[item.id]; + const editable = + Number(selectedTask.pick_status) < 40 && + Boolean(String(item.sku_code || '').trim()); + const summary = meta?.loading + ? t('picking.batch.loading') + : info?.text + ? info.text + : meta?.error + ? t('picking.batch.fail') + : t('picking.batch.none'); + return ( + +
+ {summary} + {editable ? ( + + ) : null} +
+ {info?.shortfall > 0 ? ( +
+ {t('picking.batch.shortfall', { qty: formatQty(info.shortfall) })} +
+ ) : null} + + ); + } default: return null; } @@ -2335,6 +2556,107 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin + {batchEditorItemId + ? (() => { + const item = taskItems.find((row) => row.id === batchEditorItemId); + const data = batchInfo[batchEditorItemId]?.data; + const need = item ? settlementQtyOf(item.id, item) : 0; + const total = batchEditorRows.reduce((sum, row) => sum + (Number(row.qty) || 0), 0); + const shortfall = fifoAllocateBatches(data?.batches, need).shortfall; + return ( +
+
+

+ {t('picking.batch.title')} ·{' '} + {item?.item_name || t('picking.productFallback')} +

+ + {t('picking.batch.summary', { + need: formatQty(need), + unit: item?.unit || '', + claimable: formatQty(data?.claimable ?? 0), + })} + +
+
+ {batchEditorRows.map((row, index) => ( +
+
+
{row.batch_no}
+
+ {t('picking.batch.rowMeta', { + zone: row.storage_zone || t('picking.batch.noZone'), + date: row.inbound_date || '—', + qty: formatQty(row.available_qty), + })} +
+
+
+ + +
+ + setBatchEditorRows((prev) => + prev.map((r, i) => (i === index ? { ...r, qty: v } : r)) + ) + } + className="app-input app-focus-ring w-24 px-2 py-1 border rounded text-sm text-right" + /> +
+ ))} +
+
+ + {t('picking.batch.total', { + total: formatQty(round3(total)), + need: formatQty(need), + })} + + {shortfall > 0 ? ( + + {t('picking.batch.shortfall', { qty: formatQty(shortfall) })} + + ) : null} +
+
+ + +
+
+ ); + })() + : null} + {Number(selectedTask.pick_status) < 30 && pickingBarcodeEnabled && (

{t('picking.modal.scanTitle')}

diff --git a/src/utils/picking.ts b/src/utils/picking.ts index 5802aeb..5f63eae 100644 --- a/src/utils/picking.ts +++ b/src/utils/picking.ts @@ -32,6 +32,10 @@ export interface PickingItemRow { sort_order?: number | null; container_code?: string | null; staged_at?: string | null; + /** 商品默认区域(`skus.storage_zone`),用于分拣按区域展示 */ + storage_zone?: string | null; + /** 分拣「完成」时手选的出库批次计划(发车核货按此扣库;空=默认 FIFO) */ + outbound_batches?: Array<{ batch_no: string; qty: number }> | null; } export interface PickingTaskRow { diff --git a/src/utils/workflowApi.ts b/src/utils/workflowApi.ts index 8089e81..7723bec 100644 --- a/src/utils/workflowApi.ts +++ b/src/utils/workflowApi.ts @@ -1133,6 +1133,31 @@ export async function savePickingProgressApi(body: Record) { }); } +/** 分拣明细的出库批次候选(只读,默认 FIFO 顺序 + SKU 级可扣汇总) */ +export interface PickingOutboundBatches { + sku_code: string | null; + order_code: string | null; + total_available: number; + other_reserved: number; + claimable: number; + batches: Array<{ + batch_id: string; + batch_no: string; + available_qty: number; + storage_zone: string | null; + inbound_date: string | null; + production_date: string | null; + }>; +} + +/** 按分拣明细取「本次可扣批次」;不扣库 */ +export async function fetchPickingOutboundBatchesApi(pickItemId: string) { + const params = new URLSearchParams({ pick_item_id: pickItemId }); + return workflowFetch<{ data: PickingOutboundBatches }>( + `/picking/outbound-batches?${params.toString()}` + ); +} + /** 分拣完成:回写订单结算量,置分拣完成(30),订单自动进入待配送 */ export async function confirmPickingCompleteApi(body: { pick_code: string; @@ -1142,6 +1167,7 @@ export async function confirmPickingCompleteApi(body: { picked_qty: number; picked_weight?: number; diff_reason?: string; + outbound_batches?: Array<{ batch_no: string; qty: number }>; }>; }) { return workflowFetch<{