diff --git a/docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md b/docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md new file mode 100644 index 0000000..b6e1bf2 --- /dev/null +++ b/docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md @@ -0,0 +1,658 @@ +# 仓内加工:原材料自动采购 + 成品免入库(设计稿) + +- 日期:2026-11-02 +- 提出人:开发者 +- 状态:**设计待批准**(阶段 1 可先做;阶段 2 涉及加工/验收/库存/配送冻结模块,需单独批准) +- 关联: + - [20260823-warehouse-processing-demand-sheet.md](20260823-warehouse-processing-demand-sheet.md)(仓内加工需求单现状) + - [20261027-self-purchase-warehouse-demand-pending.md](20261027-self-purchase-warehouse-demand-pending.md)(成品占位单在自采列表的展示口径) + - [.cursor/rules/purchase-prep-freeze.mdc](../../.cursor/rules/purchase-prep-freeze.mdc)、[inspection-processing-freeze](../../.cursor/rules/inspection-processing-freeze.mdc)、[inventory-freeze](../../.cursor/rules/inventory-freeze.mdc)、[delivery-freeze](../../.cursor/rules/delivery-freeze.mdc) + +## 0. 开发者口径(2026-11-02 原话整理) + +1. 加工原料采购放到**自采列表**,来源标记「加工原料采购」; +2. **原材料走正常采购/入库流程**;**加工成品不入库**——加工出来多少配送多少,不在库存里; +3. 采购数量可以先按 BOM/损耗算一个预估值,采购员**可修改**; +4. 成本价不能填 0,除非开启了「允许成本价为 0」开关; +5. **一个成品对应一个原材料**;多原料场景属于「独立加工单」,不在本次范围; +6. 原料采购**按加工单汇总**:A、B 两张订单都是去皮土豆时,订单仍是两张,但「加工单」只有一张(同配送日+同成品+同加工方式),原料采购按这张加工单汇总一张; +7. 成品分配:按订单创建时间先到先得,先满足各自需求;**产出有余量时按参与订单数平均分**(不按各单需求量比例;A 需 4 斤、B 需 5 斤,若余量 2 斤则 A、B 各 1 斤); +8. 损耗由**人工按加工方式填写**,也可在商品关联里设置;不做历史损耗自动推断; +9. 自采管理里**仍需保留加工商品记录**(不再作为待入库)。 + +## 1. 现状(生产库只读核实,`tenant_br002`) + +- 加工配置目前只在 **`customer_skus.processing_method / processing_owner`**;商品主数据 `product_catalog/skus` 没有原材料/BOM 字段; +- 仓内加工需求单按 `(分公司, 配送日, 成品 SKU, 加工方式)` 汇总(A/B 多订单共用一张,`processing_demand_items` 挂订单行); +- 原料领料记录在 `processing_demand_picks`(task_id + 原料 sku + qty);历史上 80 张需求任务,72 张有领料记录; +- 历史成品关系:34 个成品 SKU 中 27 个单原料、7 个多原料(多原料按口径属独立加工单/异常,不在本次); +- **当前成品实际会入库**:今日 `ORD_WEB_20261102_BR002_0002` 的「去皮白萝卜」仍有待验收单;历史加工成品 SKU 的 `inventory_logs` 有 `inspection_in`(如土豆丝 124.6 斤)+ `delivery_loading_out`; +- 原料采购目前靠采购员手工「新增自采/独立入库」。 + +## 2. 目标 / 非目标 + +**目标** + +1. 商品管理/商品关联可配置:仓内加工成品 → **一个原材料商品 + 该加工方式的损耗率**(人工填); +2. 订单出现仓内加工成品时,按**加工单汇总**自动在自采列表生成「加工原料采购」行(预估计数量、成本价待填、可改); +3. 原料走现有正常采购/验收/入库流程,入库后供加工单领料; +4. 加工完工时按分配规则回写各订单行实际实收数量与成本,**成品不入库存、不入验收/入库列表**; +5. 自采列表保留加工商品记录(跟踪用,不参与入库); +6. 历史数据只做「原材料关联建议 + 人工确认」,损耗率人工填写。 + +**非目标** + +- 独立加工单/多原料 BOM; +- 自动推断历史损耗率; +- 改订单主状态链、改供应商备货链路; +- 改独立入库/普通采购的既有验收开关语义。 + +## 3. 数据模型(新增,仅加表/列) + +### 3.1 加工 BOM(正常加工单) + +```sql +processing_bom +- id uuid pk +- branch_code varchar null -- 空=全分公司默认 +- output_sku varchar not null -- 成品 SKU(去皮土豆) +- processing_method varchar not null-- 加工方式(去皮/切丝…) +- material_sku varchar not null -- 原材料 SKU(土豆) +- loss_rate numeric(6,4) not null default 0 -- 人工填写,0~1 +- enabled boolean default true +- source varchar(20) default 'manual' -- manual/backfill +- created_at/updated_at/updated_by +- UNIQUE (COALESCE(branch_code,''), output_sku, processing_method) +``` + +- 一成品一加工方式只允许一个原材料(符合本次口径); +- 商品关联(`customer_skus`)如需按客户覆盖损耗,可新增 `processing_loss_rate` 可空列(客户级优先);商品管理表单在「加工方式=仓内加工」时展示原材料与损耗。 + +### 3.2 加工原料采购关联 + +```sql +processing_raw_purchase_items +- id uuid pk +- demand_task_id uuid not null -- 加工单(processing_tasks.source_type='demand') +- material_sku varchar not null +- purchase_code varchar not null -- 自采采购单(purchase_orders) +- planned_qty numeric -- 当前预估计数量 +- created_at/updated_at +- UNIQUE (demand_task_id, material_sku) +``` + +- 一张加工单 → 一条原料采购(口径 6); +- 订单变更时通过 demand_task 关联明细重算,而不是按 order_code 单独算。 + +## 4. 流程设计 + +### 4.1 原料采购自动生成(阶段 1,可先上线) + +触发点:订单保存/改量、分配、`syncWarehouseProcessingDemandForOrder` 完成后。 + +``` +对每张 demand 加工单: + 取 BOM(output_sku + processing_method;客户级损耗覆盖优先) + 原料需求 = 加工单成品总需求 × (1 + loss_rate) // 或按确认的损耗公式 + 查 processing_raw_purchase_items: + · 不存在 → 在自采列表创建「加工原料采购」草稿 + - 商品 = material_sku,数量 = 预估值,成本价 = 空/待填 + - 采购状态 10(待采购),source_type = warehouse_raw_material + - 来源标记:加工原料采购 + 关联加工单号/成品 + · 已存在且 purchase_status ∈ (10,32) → 按新总需求重算 planned_qty + · 已采购/已入库(20/30) → 只标记「需求已变化,人工确认」,不自动改 + 采购员可改数量/成本价;成本价 ≤0 时拒绝,除非分公司「允许成本为 0」开关开启 +``` + +- 原料采购走现有采购→验收→入库链(进入入库列表是正常的,与成品无关); +- 原料采购完成/入库后,仓库库存增加;加工单领料扣减该库存(现有 `processing_demand_picks`)。 + +### 4.2 成品完工回写 + 不入库(阶段 2,需单独批准) + +加工完工时(`completeProcessingWork` 及相关提交路径): + +1. **不再创建成品验收单**,不写成品 `inventory` / `inventory_logs`;删除/关闭历史占位单的“待验收入库”语义; +2. 按分配规则把**实际产出数量**分配到加工单下的订单行: + +``` +订单按 created_at ASC 排序(先到先得) +需求合计 D = Σ订单需求 +实际产出 O: + O ≤ D:按顺序填满,先 A 后 B;不足部分记差异(损耗/未满足) + O > D:先各自满足需求;余量按参与订单数**平均分** + (A 需 4、B 需 5,余量 2 → A +1、B +1;除不尽时尾差按 created_at 顺序补) +``` + +3. 成本:`成品单位成本 = 加工总成本(原料成本 + 加工费) / O`;按分配数量分摊到订单行,写回 `order_items.received_qty`、成本字段; +4. 自采管理保留加工商品记录:不再显示「待入库」,改为「仓内加工 · 已加工/无需操作」;**但记录保留**; +5. 配送:仓内加工成品行**不再按库存扣减/校验**;发车核货与结案按加工单回写的实收数量处理; +6. 订单主状态链不变(20→30→40→45→50→60→90)。 + +## 5. 订单变更规则(第 6 点,我的判断) + +| 原料采购状态 | 订单改量 | 订单删行/取消 | +|---|---|---| +| 待采购草稿(10) | 按加工单新总量重算 | 若该采购只服务此加工单 → 作废;多单共用 → 重算 | +| 已采购待入库(20)/已退回(32) | 不自动改,自采列表标记「需求已变化,人工确认」 | 同上,人工处理 | +| 已入库(30) | 不回退;多余原料留库存,后续领料/盘点 | 同上 | + +原则:**只自动改未开始的采购草稿;已开始/已入库的一律人工确认**,避免账实不一致。 + +## 5.1 订单商品切换/取消仓内加工(2026-11-02 开发者确认) + +订单详情也能修改加工方式,因此订单行从「仓内加工」切换回原材料/供应商时按以下规则处理: + +| 原料采购状态 | 处理 | +|---|---| +| 待采购草稿(10) | 直接删除 | +| 已提交采购、**尚未入库**(20) | 允许取消:删除其待验单,采购记录置 40(备注「取消仓内加工,原料采购取消(未入库)」) | +| 已入库(30) | **按独立入库保留**,不退货/不自动作废;备注「原料已入库,按独立入库保留」 | +| 成品已完工回写 | 一般不回退(开发者口径:仓内加工强制自采,成品回写后一般不再改回供应商/原材料);保持已回写实收与成本,不做自动回滚 | + +- 成品自采占位单:取消仓内加工时由既有 `clearStaleWarehouseDemandPurchaseFlags` 恢复为待采购并删成品待验单; +- 加工需求单:最后一个订单需求移除后,未开工任务删除;已领料/已产出任务保留(仅需求量归零); +- 录单界面与订单详情共用同一套 `syncWarehouseProcessingDemandForOrder` 链路,两个入口行为一致。 + +## 6. 历史数据与回填 + +- 原材料关联:从 `processing_demand_picks` 按成品 SKU 统计主要原料 SKU,生成建议清单;仅**人工确认后**写入 `processing_bom`(`source=backfill`); +- 损耗率:按口径**人工逐加工方式填写**,不自动推断;历史领料/净重数据只作参考(现有数据存在负损耗/100%/同 SKU 异常); +- 多原料/独立加工单不纳入本次回填。 + +## 7. 灰度开关与回滚 + +- 新增配置: + - `warehouse_processing_raw_purchase_enabled`:自动生成原料采购;**阶段 1 默认开启**(只有配置了 BOM 的成品才触发,未配置商品零变化),分公司/全局均可在 `system_configs` 关闭; + - `warehouse_processing_finished_no_inventory_enabled`:成品免入库/完工回写(阶段 2;**默认开启,作为 kill switch**;只有配置了 BOM 的成品生效); +- 迁移只加表/列;关闭开关即回退到现有链路; +- 阶段 2 上线前需备份并演练回滚(成品验收/库存链路恢复)。 + +## 8. 风险与待确认 + +1. 损耗率公式与单位换算(成品单位、原料单位、精度); +2. 加工总成本口径(原料成本 + 加工费)与财务分摊口径需财务确认; +3. 阶段 2 是**真实行为变更**:成品不再进库存/验收,影响配送扣库、结案、成本、报表,必须独立评审; +4. 余量分配已确认:**按参与订单数平均分**(不是按需求量比例);除不尽时尾差按 created_at 顺序补,实现时需固定小数精度与舍入规则; +5. 自采列表里「加工原料采购」与现有独立自采/自采的筛选、合计、成本统计需要兼容。 + +## 9. 验收标准(阶段 1) + +- [ ] 商品配置 BOM/损耗后,订单出现仓内加工成品 → 自采列表出现「加工原料采购」行,数量为预估值且可改; +- [ ] A/B 两订单同成品同加工方式 → 加工单一张,原料采购一张(数量=A+B 汇总); +- [ ] 成本价 0 被拒(除非开允许 0); +- [ ] 原料采购按正常流程验收/入库,入库列表正常出现原料; +- [ ] 订单改量/删行:待采购草稿自动重算/作废,已采购/已入库不动; +- [ ] 历史关联回填 dry-run 可输出确认清单; +- [ ] 关开关回到现有手工流程。 + +## 10. 阶段计划 + +| 阶段 | 内容 | 前置 | +|---|---|---| +| 1 | BOM/损耗配置 + 自采列表自动原料采购草稿 + 历史关联建议(dry-run) | 本设计批准 | +| 2 | 成品免入库 + 加工完工分配回写 + 配送链路适配 | 阶段 1 验收 + 冻结模块单独批准 | +| 3 | 历史 BOM 人工确认回填、灰度放量 | 阶段 2 验证 | + + +## 11. 阶段 1 实现记录(2026-11-02) + +### 11.1 落点 + +| 层 | 文件 | 内容 | +|---|---|---| +| 迁移 | `migrations/20261102_processing_raw_material_purchase.sql` | `product_catalog.processing_bom`、`processing_raw_purchases`;登记 `tenant_business_tables()`;表数 129→130 | +| 服务 | `server/src/services/processingRawMaterialService.ts` | BOM 解析/损耗估算、按加工单同步原料采购草稿、修改/提交、验收回写、BOM 变更同步 | +| 服务 | `server/src/services/processingRawPurchaseConfigService.ts` | 自动采购开关(默认开启,可分公司/全局关闭) | +| 挂钩 | `processingDemandSheetService.ts` | 需求单同步后同步原料采购;失败只 warning,不阻断订单 | +| 挂钩 | `inspectionComplianceService.ts` | 独立入库验收完成 → 原料采购回写已入库 | +| 挂钩 | `selfPurchaseStockInboundService.ts` | 待验退回 → 原料采购回到待采购 | +| 挂钩 | `processingDemandSheetService.ts` | 已提交/已入库原料采购保护,加工单不随订单删除丢失 | +| 路由 | `server/src/modules/workflow/routes/purchaseRoutes.ts` | 列表 / 修改 / 提交 / BOM 变更同步 4 个接口(无内嵌 SQL) | +| 前端 | `src/utils/productCatalog.ts`、`src/pages/products/SkuManagement.tsx` | 商品管理编辑弹窗「仓内加工原料(BOM)」:加工方式 + 原材料 + 损耗率;保存后同步未完工加工单 | +| 前端 | `src/components/purchase/ProcessingRawMaterialPanel.tsx`、`src/pages/purchase/PurchaseManagement.tsx` | 自采列表「加工原料采购」面板:预计数量/成本价可改、提交采购 | +| 小程序 | `miniprogram/components/processing-raw-purchase-panel/`、`miniprogram/pages/purchase`、`miniprogram/pages/admin-purchase`、`miniprogram/utils/request.js` | 采购列表顶部「加工原料采购」:采购数量/成本价可改、保存、提交采购(与 Web 同接口) | +| 文案 | `src/i18n/locales/{zh-CN,en,id}/products.ts`、`purchase.ts` | BOM 配置与原料采购三语文案 | + +### 11.2 验证 + +- `server/tests/processingRawMaterialPurchase.test.ts`:17 项通过(BOM 解析、损耗估算、开关、同步/提交/回写/删除保护源码契约) +- `src/pages/products/processingBom.contract.test.ts` + `src/components/purchase/processingRawMaterialPanel.contract.test.ts`:9 项通过 +- 小程序契约:`miniprogram/components/processing-raw-purchase-panel/processingRawPurchase.contract.test.js`(采购页/管理采购页挂载、改数量/成本价、提交、只读状态) +- 本地库事务实测:需求单 → 原料采购草稿(42 斤成品/损耗 10% → 46.667 斤原料);幂等重跑不重复建;改损耗率更新数量;移出 BOM 删除待采购草稿 +- 本地库实测提交:生成独立入库待验单、原料采购状态 20 +- `tsc --noEmit`、`npm --prefix server run build` 通过 + +### 11.3 未做 / 下一步 + +- 阶段 1 暂无「开关 UI」;如需页面开关另加系统配置入口; +- 阶段 2(成品免入库/完工回写)已接默认流程:只要成品配置了原材料 BOM,订单选择仓内加工后即走「成品免入库 + 原料采购 + 领料完工回写」;订单推进、配送扣库逻辑不动。 + +## 12. 阶段 2 原型代码(2026-11-02,待开发者核查) + +### 12.1 已写什么 + +| 文件 | 内容 | +|---|---| +| `server/src/services/processingFinishedNoInventoryConfigService.ts` | 免入库开关 `warehouse_processing_finished_no_inventory_enabled`,**默认开启(kill switch)**,支持分公司/全局关闭;未配置 BOM 的成品不受影响 | +| `server/src/services/processingFinishedOutputService.ts` | 纯分配算法 `planFinishedOutputAllocation` + 只读预演 `previewFinishedOutputAllocation` + 回写服务 `applyFinishedOutputAllocation` | +| `server/tests/processingFinishedOutput.test.ts` | 18 项测试:A4/B5 正常/不足/有余量、0.001 尾差、同订单多行、默认开启、自动触发、BOM 条件、不写库存/验收/订单状态 | + +### 12.2 分配口径(已实现) + +- 订单按 `orders.created_at ASC` 先到先得; +- 产出 ≤ 总需求:按顺序填满,先 A 后 B; +- 产出 > 总需求:先满足需求,余量按**参与订单数平均分**(0.001 斤粒度;如余量 3 → 每单 1.5;余量 0.001 无法二分时整份给先创建的订单); +- 分配之和严格等于实际产出。 + +**开发者示例(2026-11-02)**:A 需 5 斤、B 需 4 斤,实际加工出 10 斤: + +1. 先填满 A=5、B=4(用掉 9 斤); +2. 余 1 斤按 2 个订单平均分 → A=5.5、B=4.5; +3. 回写两个订单行的实收数量分别为 5.5 / 4.5;成本价按(领料成本 ÷ 实际产出 10 斤)统一计算后回写。 + +这里的实际产出 = 加工单「完工」时填写的净重(不是领料量,也不是订单需求量)。 + +### 12.3 回写内容(原型) + +- `order_items.received_qty` / `received_at`:走唯一写入口 `writeOrderItemReceivedQty`,阶段暂用 20(相当于验收实收,可评审调整); +- `order_items.unit_cost`、`processing_settled_unit_cost`:按(原料成本 + 加工费)/ 实际产出计算统一单价; +- **不写** inventory / inventory_logs / cost_details。 + +### 12.4 开发者核查口径(2026-11-02) + +| # | 开发者口径 | 代码对应 | +|---|---|---| +| 1 | 成品没有验收单,入库列表也没有成品 | 阶段 2 成本回写**不再依赖验收单**(结算改用分配量 override);开关打开后,成品占位单自动完成时**不再生成新的成品待验收单**(`skipWarehouseProcessingPurchase` 直写 purchase_status=20,不建 inspection);历史已有待验单不清理(开发者:有的就不用管) | +| 2 | 订单推进与成品无关;原材料入库后该商品即算完结,不能卡订单 | 阶段 2 回写时写**履约覆盖**(`order_item_fulfillments` + `stock_cover_qty`),随后调用 `tryAdvanceOrderToInspection` / `maybeAdvanceOrderAfterFulfillment` 推进订单(30→40→45/待配送),后续正常分拣/配送 | +| 3 | 成品不入库,发车不会扣成品库存 | 阶段 2 **不写** inventory/inventory_logs;配送链路不动(无库存时 softInventory 不拦发车) | +| 4 | 自采列表保留加工商品记录 | 保留成品自采占位单;免入库模式显示「仓内加工 · 无需操作」(UI 待接) | +| 5 | 成本在领料后回写,沿用原逻辑 | 复用 `settleDemandSheetCostOnCompletion`,新增可选 `perOrderQty`:阶段 2 传本次分配量;**默认不传时仍走原验收 actual_qty 口径,行为不变** | +| 6 | 只是回写价格,不改订单状态 | `received_stage` 只是实收字段的单调标记(10 采购/20 验收/30 分拣/40 配送/50 完结/60 管理员),**不是订单状态**;阶段 2 暂用 20(验收口径),不影响订单状态链 | +| 7 | 重复调用怎么解决 | 迁移给 `processing_tasks` 加 `finished_output_applied_at / finished_output_actual_qty / finished_output_applied_by / finished_output_plan`;同一实际产出重复调用直接返回(不重复写),产出变化才重算覆盖 | + +### 12.5 生产数据说明(已按开发者口径处理) + +生产库只读核实(`tenant_br002`,2026-11-02): + +- 订单 `ORD_WEB_20261102_BR002_0002` 的「去皮白萝卜」存在一条 `inspections` 待验收记录, + `source_type='purchase'`、`processing_details.purchase_code=PUR17936147156689b4f356`, + 对应 `purchase_orders.self_processed=true`、`purchase_status=20`(成品自采占位单自动完成时生成)。 +- 开发者 2026-11-02 裁决:成品待验收单**不需要历史**;开关打开后不再生成新的成品待验单, + 已存在的历史待验单**不清理、不处理**(有的就不用管)。 +- 实现:`skipWarehouseProcessingPurchase` 在成品**配置了原材料 BOM**且开关未关闭时, + 直接写 `purchase_status=20`(占位单保留),不调用会创建待验单的 `updatePurchaseOrderStatus`; + 未配置 BOM 的成品仍走原成品待验收流程。 + +### 12.6 仍待接线 + +1. 成品自采占位单在免入库模式的显示(按开发者口径:「仓内加工 · 无需操作」,UI 待接); +2. 阶段 2 的 `applyFinishedOutputAllocation` 触发点(当前未接线): + - 方案 A:加工单完工(仓管提交净重)后自动执行;条件 = 分公司开关开 + `source_type='demand'` + 有领料 + 净重>0 + 挂订单行; + - 方案 B:加工单详情「确认完工回写」手动按钮(灰度更安全); + - 方案 C:入库/配送节点触发(不推荐,易重复)。 + 还需配套:加工单状态从「靠成品验收完成」改为「完工即完成(40)」,并确认订单推进不受影响(开发者口径:与成品无关)。 +3. 阶段 2 是否在加工单完工时把 `process_status` 直接置 40(不再 pendingInspection); +4. 上线前置:开关、迁移(仅加列)、回滚与核对报表;**部署必须等开发者本地测试后明确指令,不得自动发布**。 + +### 12.5 验证 + +- `server/tests/processingFinishedOutput.test.ts`:12 项通过; +- `npm --prefix server run build` 通过; +- 原型未接到任何现有业务路径(开关关闭时也不会被调用),对现有流程零影响。 + + +### 12.7 默认流程与触发点(2026-11-02 开发者确认) + +订单选择仓内加工、且该成品配置了原材料 BOM 时,系统**默认**执行: + +1. 成品占位单自动完成(`purchase_status=20`,自采列表保留记录),**不生成成品待验收单**、不进入入库列表; +2. 自采列表自动生成「加工原料采购」草稿(阶段 1),采购员提交后原料走正常验收/入库; +3. 原料入库后,仓管在加工单领料; +4. **加工单点「完工」提交实际产出净重时,加工单直接完结(`process_status=40`),不等待成品入库**; + 系统按分配规则回写订单行实收数量,并按既有领料成本结算逻辑回写成本价(`settleDemandSheetCostOnCompletion` + `perOrderQty` override); +5. 重复调用幂等(`processing_tasks.finished_output_applied_at` 标记),产出变化才重算覆盖。 + +> 说明:当前 UI 的「完工」弹窗仍需要填写毛重/净重(实际产出);开发者如希望「领料完毕即自动完结、不用填净重」, +> 需再确认实收数量取订单需求量还是其他口径,确认后调整。 + + +### 12.8 履约覆盖与订单推进(2026-11-02 开发者定方案 1) + +- 加工单完工回写时,对每个分配到货的订单行写: + - `order_items.stock_cover_qty = GREATEST(原值, 订单行数量)`; + - `order_item_fulfillments` 覆盖行(`purchase_code=NULL`、`supplier_preparation_id=NULL`、`inventory_cover_qty=订单行数量`)。 +- 目的:让 `fetchOrderInspectionState` 判为 `passed`,订单不再卡在 30;随后调用 + `tryAdvanceOrderToInspection` 与 `maybeAdvanceOrderAfterFulfillment`,该订单行视为履约完成, + 后续按正常流程分拣/配送。 +- 覆盖数量取**订单行需求量**而非分配量(沿用「实收多少不挡订单状态」口径); + 成本/实收数量仍按分配结果写在订单行。 +- 已用本地模拟订单验证:纯仓内加工订单完工后 `inspectionState=passed`、订单状态 30→45、自动创建分拣任务; + 测试数据已清理。 +- 风险/待验证:成品无库存但 `stock_cover_qty` 标记为已覆盖,后续分拣/发车按订单数量走;需在完整 UI 流程中确认 + 发车/结案不因「无成品库存」报错。 +## 13. 录单/订单详情的原材料内联设置(2026-11-02) + +- 触发:录单提交前 / 订单详情保存前,检查仓内加工行是否配置了「该商品 + 该加工方式」的原材料 BOM; +- 缺失时在**当前页面弹窗**(`src/components/order/ProcessingBomSetupModal.tsx`)填写原材料商品 + 损耗率, + 保存后自动继续原来的提交/保存动作,**不跳转商品管理**,避免用户重录订单; +- BOM 保存到 `product_catalog.processing_bom`(与商品管理同一份数据,按加工方式合并); +- 覆盖入口:录单页 `CustomerOrder.tsx`、订单详情 `OrderManagementPage.tsx`; +- 文案三语(zh/en/id);纯前端拦截,后端保存校验待确认是否加(加了会同时影响小程序录单/导入,需要配套内联设置入口)。 + + +### 13.1 录单行内原材料按钮(2026-11-02) + +- 录单行选择「仓内加工」后,在该行的加工方式旁边直接显示原材料按钮: + - 未配置:琥珀色「选择原材料」; + - 已配置:绿色「原材料:xxx」,点击即可修改; +- 点击复用 `ProcessingBomSetupModal`,在当前页面选择原材料 + 损耗率,保存到 `product_catalog.processing_bom`; +- 保存后行内标签立即刷新,不需要跳商品管理; +- 提交订单时仍保留兜底校验:若漏配,提交前弹窗要求补配置,补完自动继续提交。 +- 订单详情同样支持:仓内加工行显示「选择原材料 / 原材料:xxx」按钮,点击设置/修改; + 未配置时也可先点订单「保存」,保存前弹窗补配置,补完自动继续保存。 + + +### 13.2 商品级单原料改版(2026-11-02 开发者确认) + +- 商品管理「仓内加工原料」只维护**一个商品级配置**:原材料商品 + 加工损耗; +- **不再有「加工方式」字段、不允许多行/添加多个加工方式**;具体加工方式由录单员在下单时填写; +- `processing_bom` 仍兼容数组,但新保存只写一条 `{ method: '', material_sku, loss_rate }`(method 为空 = 所有加工方式通用); +- 后端读取顺序:匹配当前加工方式 → method 为空 → 只有一条配置时视为通用; +- 订单行内按钮显示/修改同一份商品级原材料,不再按加工方式区分。 +- 商品管理「原材料商品」下拉搜索不到时可直接新建商品(复用录单的 `QuickCreateProductModal`: + 填名称/分类/单位/售价/成本价 → 创建成功自动选中为原材料,不跳页); +- 录单/订单详情的内联 BOM 弹窗里同样支持搜不到原材料时新建商品(同一套创建接口)。 + + +### 13.3 保存 BOM 报 invalid input syntax for type json 修复(2026-11-02) + +- 根因:`product_catalog.processing_bom` 是 jsonb;前端把 JS 数组直接交给数据网关, + Node `pg` 按 PostgreSQL 数组字面量传参,jsonb 输入解析失败; +- 修复:所有 BOM 写入(录单弹窗 `saveProductProcessingBom`、商品管理新增/编辑 + `insertCatalogProduct` / `updateCatalogProduct`)统一 `JSON.stringify(...)` 后再写库; +- 回归:契约测试断言 `JSON.stringify`,本地 `/api/data/query` 数组写入复现报错、字符串写入成功。 + + +### 13.4 加工原料采购并入自采列表(2026-11-02 开发者要求) + +- 不再在自采列表上方单独渲染「加工原料采购」表; +- 加工原料采购作为**自采列表的行**展示: + - 商品名称 = 原材料名称; + - 描述 = 加工单 + 成品(加工方式); + - 来源列 = **加工原料采购**; + - 待采购(10)/已采购待入库(20) 的数量、成本价仍可在行内修改; + - 待采购行操作 = 提交采购;已提交行操作列显示状态; +- 原 `ProcessingRawMaterialPanel` 组件删除,数据仍走 + `list/update/submitProcessingRawPurchaseApi`; +- 行内操作列固定为「复制 + 完成」(待采购行),不再用独立「提交采购」按钮文案; +- 不生成/不展示「加工单…成品×…原料预计…」备注,备注列显示 `-`; +- 采购计划数量生成时向上取整为整数(如 15 × 1.3 = 19.5 → 20),不再落小数。 + + +### 13.5 统一数据源:原料采购镜像为自采 purchase_orders(2026-11-02 开发者确认) + +开发者明确:原材料就是走自采列表、走自采流程,不能 Web 单独整理、小程序看不到,也不能是单独接口。 + +- 每条 `processing_raw_purchases` 同步生成一条 `purchase_orders`: + - `source_type='processing_raw_material'`,`source_id=原料采购行 id`; + - `order_code=NULL`(独立入库),`sku_code=原材料`,数量为加工单需求; + - 初始 `purchase_price=0`,完成自采时按既有规则要求成本 >0(除非开启允许 0); +- Web 自采列表、小程序采购列表、完成/复制、验收、入库全部读这条 `purchase_orders`; + - `processing_raw_purchases` 只作为加工单↔原材料的锚点,不再单独提供列表/编辑/提交接口; +- 迁移 `20261102_processing_raw_purchase_mirror.sql` 回填已有原料采购行镜像,并把待采购数量向上取整; +- 需求取消:待采购(10) 删原料行+镜像;已采购待入库(20) 删未验收待验单+镜像; + 已入库(>=30) 保留为独立入库。 + + +### 13.6 修复:仓内加工成品出现在待入库/验收(2026-11-02) + +问题:订单行选择「仓内加工」后,成品(如土豆丝)仍被 `ensureInspectionsForOrder` +按 `supplier_code=INTERNAL` 当成供应商入库行生成待验,出现在入库列表。 +原材料(土豆)反而因原料采购未完成而没有待验。 + +修复: + +- `ensureInspectionsForOrder` 在生成普通订单行待验前,先用 + `requiresWarehouseProcessing(processing_method, processing_owner)` 跳过仓内加工成品, + 并删除其未验收、未入库的历史待验; +- 新增迁移 `20261102_processing_finished_pending_inspection_cleanup.sql` + 按租户清理历史遗留的成品待验行(只删未验收、未入库的); +- 原材料仍由自采单「完成」后走 `ensurePurchaseInspectionForCompletedPurchase` + 生成独立入库待验(商品名=原材料),这才是入库列表该出现的行。 + + +### 13.7 修复:原材料采购完成后入库列表看不到原料(2026-11-02) + +- `inspectionVisibleInListSql` 要求 `order_code` 有有效订单,或 `processing_details.independent_inbound=true`; +- 加工原料采购镜像自采单的待验 `order_code=NULL`,但历史生成时没有独立入库标记,导致 + 「土豆」待验存在却不在入库列表显示(截图只剩苹果); +- 修复:`ensurePurchaseInspectionForCompletedPurchase` 对 + `purchase_orders.source_type='processing_raw_material'` 的待验写入 + `independent_inbound: true`;已有待验更新时也补标记; +- 迁移 `20261102_processing_raw_inspection_visibility.sql` 回填历史原料待验标记; +- 成品(土豆丝)仍由 13.6 的跳过逻辑保证不生成待验。 + + +### 13.8 需求单领料按 BOM 自动带出原材料(2026-11-02) + +- 加工单已配置成品 BOM 时,Web「需求单领料」弹窗打开即自动: + - 查 `product_catalog.processing_bom`,按当前加工方式匹配原材料(兼容商品级通用配置); + - 自动选中该原材料商品; + - 按 `成品需求 × (1 + 损耗率)` 向上取整预填领料数量(可人工修改); +- 无 BOM 时退回原手动搜索商品流程; +- 领料数量仍由后端校验库存/可用量,前端不绕过。 + + +### 13.9 需求单领料合并「加工产出」并直接完工(2026-11-02 开发者确认) + +成品免入库后不再有成品入库称重,实收数量来自加工完工填写: + +- 需求单领料弹窗(有 BOM)新增「加工产出数量(成品净重)」; +- 一次提交执行: + 1. 领料(可追加;在制单自动只带剩余量,也可不追加); + 2. 以「已领料合计」为 gross、填写产出为 net 调用 `completeProcessingWork`; + 3. 完工后按既有 phase2 规则回写订单行实收/成本并完结加工单; +- 加工产出数量默认取需求数量,可改;不得大于已领料数量; +- 无 BOM 的需求单保持原流程(领料后等成品入库)。 + + +### 13.10 修复:成品占位自采单重复生成待验(2026-11-02) + +- 订单保存时系统会为仓内加工成品自动完成一条 `self_processed=true` 的占位自采单; +- 该占位单进入 `ensurePurchaseInspectionForCompletedPurchase` 时仍会生成成品待验 + (如订单 0011 的土豆丝 30 斤再次出现在入库列表); +- 修复:该函数遇到 `self_processed=true` 直接返回,不生成成品待验; +- 历史遗留的未验收成品待验由 13.6 的迁移/预清理删除; +- 原材料待验仍由真实原料采购单(非占位)生成。 + + +### 13.11 修复:加工成品完工后订单列表误显示「库存抵扣」(2026-11-02) + +- phase2 完工回写会给成品订单行写履约覆盖 `stock_cover_qty`,用于订单推进判断; +- 订单列表把 `stock_cover_qty > 0` 一律显示为「库存抵扣」, + 于是加工完成的土豆丝出现 `库存抵扣:土豆丝`; +- 该覆盖不是真实多采库存抵扣;修复 `fetchStockCoverItemLabelsBatch`: + 排除 `processing_owner='warehouse'` 且加工方式非「原材料」的成品行; +- 实际库存/履约判断不变,仅修正列表文案归属。 + + +### 13.12 修复:新订单复用已完工加工单导致不生成原料采购(2026-11-02) + +- 现象:订单 0012 的土豆丝(1斤,去皮)在自采列表看不到原材料土豆; +- 原因:需求单汇总键原先只排除「已作废(50)」,会复用**已完工(40)** 的加工单; + 该加工单的原料采购已完成/入库,新订单行并入后不会重新生成原料采购; +- 修复: + - `findOrCreateDemandSheet` 只复用 `process_status < 30`(未开始/加工中)的需求单; + - 唯一索引同步收窄为同一条件(迁移 `20261102_processing_demand_reuse_open_only.sql`); + - 已完工/待验收任务不再接新需求,新订单行生成新的加工单和原料采购; +- 本地修复订单 0012:新加工单 `XQG-20261102-0002`,原料采购土豆 2 斤(待采购)。 + + +### 13.13 分拣展示标准商品名(2026-11-02 开发者要求) + +- 录单可填「原始录单名称/别名」(如大土豆),但分拣/标签/CSV 必须展示标准商品名(如土豆丝); +- `listPickingItemsEnriched` 增加 `standard_name = COALESCE(skus.sku_name, product_catalog.name)`; +- Web 分拣页统一 `pickingItemDisplayName(item) = standard_name || item_name || sku_code`, + 用于商品列、标签打印、CSV、勾选列表;`item_name` 仅作兜底。 + + +### 13.14 分拣外层与小程序统一标准商品名(2026-11-02) + +- 分拣任务按商品汇总时 `picking_tasks.scope_label` 存的是录单别名(如大土豆); +- `listPickingTasks` / `listMyPickingTasks` 新增 `scope_standard_label`: + 从该拣货单明细取 `skus.sku_name / product_catalog.name`; +- Web 分拣外层「订单」「客户/分类」优先 `scope_standard_label`; +- 小程序分拣行 `display_name` 优先 `item.standard_name`,分组/标签标题优先 + `task.scope_standard_label`;别名只兜底。 + + +### 13.15 全链路复核 + 下单 BOM 硬校验(2026-11-02) + +本地隔离测试单 `ORD_WEB_20261103_BR002_0001`(仓内加工土豆丝 5 斤)跑通: + +1. 下单 status30,生成 `XQG-20261103-0001` 与原料采购土豆 8 斤(待采购); +2. 完成原料自采(成本 4.5)→ 原料待验土豆 8 斤(独立入库,列表可见); +3. 原料验收入库 8 斤 → 库存 8; +4. 需求单领料 8 斤 + 加工产出 5 斤 → 加工单完结,订单 status45, + 订单行实收 5、单位成本 7.2(36/5),领料扣库 8→0; +5. 分拣完成 → 订单 status50;开始配送 + 签收 → 订单 status90、配送任务30。 + +同时补后端硬校验:`/orders/submit` 发现仓内加工行没有 BOM 时返回 +`processing_bom_required` 并回滚,不再只依赖 Web 前端弹窗。 + + +### 13.16 分拣调整加工成品数量与完工前置校验(2026-11-02) + +- 加工成品没有库存批次,分拣不扣库存;分拣时按客户调整实拣数量不会触发库存不足报错; +- 分拣完成把每行实拣量写回订单行 `received_qty(stage=30)`; + 配送签收完结冻结时,订单行 `quantity/amount` 按调整后的分拣量结算; +- 实测:加工单产出 5 斤的订单,分拣完成时把某客户改为 4 斤,分拣完成成功, + 签收后订单行 quantity=4、amount=24; +- 分拣人员需保证各客户调整后的合计与加工产出/分配口径一致;系统不会因成品无库存而拦截; +- 补后端校验:需求单 `material_qty=0` 时禁止提交加工完工(必须先领料), + 防止无原料成本仍产出成品; +- 修复原料验收入库回写锚点的 SQL 未使用参数 `$1` 导致事务 abort 的问题。 +- 本地测试单:`ORD_WEB_20261103_BR002_0001`(全链路90)、 + `ORD_WEB_20261103_BR002_0002`(分拣调整验证),均仅本地测试数据。 + + +### 13.17 损耗率口径修正(2026-11-02 开发者确认) + +- 业务口径:加工损耗按**成品数量**比例计算,`原料 = 成品 × (1 + 损耗率)`; +- 例:成品 15 斤、损耗 30% → 15 × 1.3 = 19.5 → 计划采购 **20 斤**(原 ÷(1-30%)=21.43→22 是错的); +- 已同步修改: + - 后端 `estimateRawMaterialQty` / `planRawMaterialPurchaseQty`; + - 需求单领料弹窗自动预填领料数量; + - 相关测试与设计文档。 + + +### 13.18 加工成品自采行成本只读并在完工后自动关闭(2026-11-02) + +- 仓内加工成品的 `self_processed` 占位自采单成本必须为 0,成本由加工完工后回写订单行; +- Web 自采列表不再给这类行提供成本价输入框(也不允许手动改成 0,自动自愈负责), + 数量/实收同样只读; +- phase2 加工完工回写订单后,占位自采单自动置为 `purchase_status=30`(关闭), + 不再长期停留在自采列表「仓内加工·待入库」。 + + +### 13.19 领料弹窗展示并可人工调整各客户成品分配(2026-11-02) + +- 输入加工产出数量后,弹窗调用 + `/processing/demand/:taskId/finished-output-preview` 预演分配; +- 按订单展示「客户 + 订单号 + 需求数量 + 本次可分到数量」; +- 分配默认沿用规则(先到先得/余量平均),可逐个客户手动改多改少; +- 提交加工完工时传 `manual_output_allocations`,后端校验: + - 必须覆盖该加工单全部订单行; + - 每行数量 >=0,产出不超过总需求时不得单行超过需求; + - 合计必须等于本次加工产出(0.001 精度); +- 通过后才按人工分配回写订单实收与成本;不传则保持原自动分配规则。 + + +### 13.20 加工完工同步分拣/配送数量(2026-11-02) + +- 分拣任务/分拣行在订单提交时就已生成,`required_qty` 默认取订单计划量; +- 加工完工(自动或人工调整客户分配)后,phase2 会把**尚未开始分拣**(pick_status<30、 + review_status<30)的对应 `picking_items.required_qty` 改成该客户实际分到的数量; +- 配送任务本身不存商品数量,装车核货从 `picking_items` 取数,所以分拣数量更新后 + 配送单/核货自然使用新数量; +- 若分拣已经开始/完成,系统不改历史分拣数量,只记录 warning,需人工核实; +- 新增/修改订单后再完工时按同上逻辑同步。 + + +### 13.21 历史分拣需求数量回填(2026-11-02) + +- 订单 0003/0004 的加工单已完成(产出 30,客户分配 17/13),但分拣行仍是 + 计划量 15/12(完成时间早于 picking required 同步修复); +- 新增迁移 `20261102_processing_picking_required_sync.sql`: + 对仓内加工成品、已完工回写实收(received_stage>=20)、分拣未开始的行, + 把 `required_qty` 对齐为 `order_items.received_qty`; +- 本地已执行:分拣行变为 17/13;无需重新下单,完成其它商品采购/备货后继续分拣→配送即可。 + + +### 13.22 小程序仓内加工单对齐 Web(2026-11-02) + +`processing-panel` 需求单领料弹窗由旧流程(手动选库存原料、只领料)对齐为: + +1. `GET /mobile/processing/demand/:taskId/bom` 按 BOM 自动带出原材料、损耗率, + 预填剩余领料数量; +2. 增加「加工产出数量(成品净重)」输入,默认等于需求数量; +3. `GET /mobile/processing/demand/:taskId/finished-output-preview` + 实时展示各订单客户可分到的数量; +4. 客户分配数量可逐个修改,提交时校验合计等于加工产出; +5. 确认后一次完成「领料 + 加工完工」,传 `manual_output_allocations`, + 后端按人工分配回写订单实收/成本并同步未开始分拣的需求数量; +6. BOM 读取失败时仍退回旧的手动选原料流程,不阻断领料。 + + +### 13.23 加工原料自采预计成本价(2026-11-02) + +- 加工原料自采行(`processing_raw_material`)没有订单行成本时,列表给一个只读预计成本: + 1. 该加工任务下**按订单创建时间第一个客户**的生效报价单成本价; + 2. 该客户商品库 `customer_skus.cost_price`; + 3. 历史订单同商品最近一次 `unit_cost`(同客户优先,再取任意客户); +- 多客户时固定取第一个客户,避免同一原料行口径混乱; +- 预计价只作为 `suggested_cost_price` 展示/预填,不写回采购实际成本,不参与成本 KPI; +- 本地验证:红薯原料行(需求任务首个客户报价成本 4)列表返回 suggested_cost_price=4。 + + +### 13.24 小程序自采列表参考成本价(2026-11-02) + +- 小程序采购列表行已有 `suggested_price` 字段,复用同一套「实际价 → 下单价 → 参考价」显示; +- 加工原料行补充使用 13.23 的预计成本回退(客户报价 → 客户商品库 → 历史订单), + 接口额外返回 `suggested_cost_source` 便于排查; +- 修正小程序 `pickCostPriceHint`:下单价 `0` 是未填占位,不能挡住参考价; + 实采价显式 `0` 仍作为合法值优先保留; +- 本地实测红薯原料行:actual_price=null、purchase_price=0、suggested_price=4、 + source=customer_quote,小程序应预填 4 元。 + + +### 13.25 BOM 命中口径与 Web 弹窗对齐(2026-11-03) + +开发者反馈:「当前小程序的仓内加工单与 web 的仓内加工单效果不一样 … 设置加工产出多少 分配给客户多少 也没有预选原料的机制」。 + +**实测根因**:小程序的需求单领料靠 `GET /mobile/purchase/processing/demand/:taskId/bom` 判定 `has_bom`, +再决定是否渲染「原材料自动带出 / 加工产出数量 / 客户分配」三块;而该端点复用的 +`processingRawMaterialService.loadBomEntry()` 比 Web 弹窗(`ProcessingManagement.tsx`)**更严**: + +| 情形 | Web(三条序) | 旧服务端 | +|---|---|---| +| 任务 `processing_method` 为空 | `entries[0]` 兜底命中 | `if (!sku \|\| !procMethod) return null` ⇒ 判无 BOM | +| BOM 多条且都不匹配加工方式 | `entries[0]` 兜底命中 | 只有 `entries.length === 1` 才兜底 ⇒ 判无 BOM | + +于是 Web 显示产出/客户分配,小程序却退回「手选原料 + 手填领料数量」的旧界面,两边不一致。 + +**改法**(只动 `loadBomEntry`,与 Web 三条序逐条对齐): + +1. 只要求成品 `sku` 非空;加工方式为空不再直接判死; +2. 兜底从「恰好 1 条」放宽为 `entries[0]`(多条不匹配时取首条,与 Web 一致)。 + +**影响面**:`hasProcessingBomForOutput()` 共用本函数 ⇒ 免入库 / 原料自动采购的判定入口**同口径变松** +(历史任务没填加工方式、或多条 BOM 不匹配时,以前不触发,现在会触发)。这是与商品级单原料 +(2026-11-02 改版,去掉按加工方式分行)一致的方向,但仍属行为变化,需在验收时确认。 + +**不动**:损耗率公式(原料 = 成品 x(1+损耗率))、领料数量算法、加工产出分配算法、任何状态链。 + +**验证**:`server/tests/processingRawMaterialPurchase.test.ts` 新增 4 例(加工方式为空仍命中 / +多条不匹配取首条 / 空方式条目优先 / 成品或 BOM 为空仍为 false),并把原来钉「恰好 1 条才兜底」的 +旧断言改为钉新口径。本地该文件 34 例通过、1 例因 Windows 工作树 CRLF 与断言的 LF 多行串不一致而红 +(内容正确,非本次改动引入)。 diff --git a/migrations/20261107_processing_raw_material_purchase.sql b/migrations/20261107_processing_raw_material_purchase.sql new file mode 100644 index 0000000..83cecf6 --- /dev/null +++ b/migrations/20261107_processing_raw_material_purchase.sql @@ -0,0 +1,109 @@ +-- 仓内加工:原材料 BOM + 加工原料采购草稿(阶段 1) +-- 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md +-- 纪律:只加列/加表 + 名单登记;不改既有业务表语义,可幂等重跑。 + +-- ① product_catalog.processing_bom JSONB: +-- [{"method":"去皮","material_sku":"SKU...","loss_rate":0.11}, ...] +-- 一个成品可配置多个加工方式,每个方式一个原材料(本次口径)。 +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT n.nspname FROM pg_namespace n + WHERE n.nspname IN ('public','legacy_public','tenant_template') OR n.nspname LIKE 'tenant\_%' + ORDER BY n.nspname + LOOP + IF to_regclass(format('%I.product_catalog', sch)) IS NOT NULL THEN + EXECUTE format( + 'ALTER TABLE %I.product_catalog + ADD COLUMN IF NOT EXISTS processing_bom JSONB NOT NULL DEFAULT ''[]''::jsonb', + sch + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.product_catalog.processing_bom IS %L', + sch, + '仓内加工原料配置:[{method, material_sku, loss_rate}],人工维护' + ); + END IF; + END LOOP; +END $$; + +-- ② processing_raw_purchases:按加工单汇总的原料采购草稿 +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT n.nspname FROM pg_namespace n + WHERE n.nspname IN ('public','legacy_public','tenant_template') OR n.nspname LIKE 'tenant\_%' + ORDER BY n.nspname + LOOP + IF to_regclass(format('%I.processing_tasks', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'CREATE TABLE IF NOT EXISTS %I.processing_raw_purchases (' + ' id UUID PRIMARY KEY DEFAULT gen_random_uuid(),' + ' purchase_code VARCHAR(64) NOT NULL UNIQUE,' + ' branch_code VARCHAR(20) NOT NULL,' + ' demand_task_id UUID NOT NULL REFERENCES %I.processing_tasks(id) ON DELETE CASCADE,' + ' output_sku VARCHAR(50) NOT NULL,' + ' processing_method VARCHAR(50) NOT NULL,' + ' material_sku VARCHAR(50) NOT NULL,' + ' material_name VARCHAR(200),' + ' unit VARCHAR(20),' + ' planned_qty NUMERIC(14,3) NOT NULL DEFAULT 0,' + ' actual_qty NUMERIC(14,3),' + ' unit_cost NUMERIC(14,4) NOT NULL DEFAULT 0,' + ' total_amount NUMERIC(14,2) NOT NULL DEFAULT 0,' + ' purchase_status INTEGER NOT NULL DEFAULT 10,' + ' inspection_id UUID,' + ' inventory_id UUID,' + ' purchaser_code VARCHAR(30),' + ' purchaser_name VARCHAR(100),' + ' remark TEXT,' + ' created_by UUID,' + ' created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),' + ' updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),' + ' CONSTRAINT processing_raw_purchases_task_material_uq UNIQUE (demand_task_id, material_sku)' + ')', + sch, sch + ); + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_processing_raw_purchases_branch_status ON %I.processing_raw_purchases (branch_code, purchase_status)', + sch + ); + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_processing_raw_purchases_task ON %I.processing_raw_purchases (demand_task_id)', + sch + ); + END LOOP; +END $$; + +-- ③ 登记到租户业务表名单(新业务表必须登记) +DO $$ +DECLARE + tables text[]; +BEGIN + tables := public.tenant_business_tables(); + IF tables @> ARRAY['processing_raw_purchases'] THEN + RETURN; + END IF; + tables := tables || ARRAY['processing_raw_purchases']; + EXECUTE format( + 'CREATE OR REPLACE FUNCTION public.tenant_business_tables() RETURNS TEXT[] LANGUAGE sql IMMUTABLE AS $fn$ SELECT %L::text[] $fn$', + tables + ); +END $$; + +DO $$ +BEGIN + IF NOT public.tenant_business_tables() @> ARRAY['processing_raw_purchases'] THEN + RAISE EXCEPTION '迁移未生效:tenant_business_tables() 未包含 processing_raw_purchases'; + END IF; +END $$; + +SELECT public.ensure_tenant_schemas_match_template(); +SELECT public.assert_tenant_template_matches_business_tables(); diff --git a/migrations/20261108_processing_finished_output_apply.sql b/migrations/20261108_processing_finished_output_apply.sql new file mode 100644 index 0000000..ccc34a9 --- /dev/null +++ b/migrations/20261108_processing_finished_output_apply.sql @@ -0,0 +1,44 @@ +-- 仓内加工成品完工分配(阶段 2 原型):幂等标记 +-- 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md §12.4 +-- 纪律:只加列(processing_tasks),不新增业务表、不改既有列语义、可幂等重跑。 + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT n.nspname FROM pg_namespace n + WHERE n.nspname IN ('public','legacy_public','tenant_template') OR n.nspname LIKE 'tenant\_%' + ORDER BY n.nspname + LOOP + IF to_regclass(format('%I.processing_tasks', sch)) IS NULL THEN + CONTINUE; + END IF; + EXECUTE format( + 'ALTER TABLE %I.processing_tasks + ADD COLUMN IF NOT EXISTS finished_output_applied_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS finished_output_actual_qty NUMERIC(14,3), + ADD COLUMN IF NOT EXISTS finished_output_applied_by UUID, + ADD COLUMN IF NOT EXISTS finished_output_plan JSONB', + sch + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.processing_tasks.finished_output_applied_at IS %L', + sch, + '阶段2原型:成品完工分配回写时间(NULL=未回写,重复调用以此为幂等标记)' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.processing_tasks.finished_output_actual_qty IS %L', + sch, + '阶段2原型:上次回写所用实际产出数量(与本次不一致时重算覆盖)' + ); + EXECUTE format( + 'COMMENT ON COLUMN %I.processing_tasks.finished_output_plan IS %L', + sch, + '阶段2原型:上次分配结果快照(供核查/追溯)' + ); + END LOOP; +END $$; + +SELECT public.ensure_tenant_schemas_match_template(); +SELECT public.assert_tenant_template_matches_business_tables(); diff --git a/migrations/20261109_processing_picking_required_sync.sql b/migrations/20261109_processing_picking_required_sync.sql new file mode 100644 index 0000000..b44cc2f --- /dev/null +++ b/migrations/20261109_processing_picking_required_sync.sql @@ -0,0 +1,37 @@ +-- 加工完工后,未开始分拣的成品分拣行需求数量应等于该客户实际分到的成品数量。 +-- 历史数据(改动前完成加工)仍停留在订单计划量,这里一次性对齐。 +-- 只处理仓内加工成品、已完工回写实收(received_stage>=20)、分拣未开始/未完成的行。 + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT n.nspname FROM pg_namespace n + WHERE n.nspname IN ('public','legacy_public','tenant_template') OR n.nspname LIKE 'tenant\_%' + ORDER BY n.nspname + LOOP + IF to_regclass(format('%I.picking_items', sch)) IS NULL + OR to_regclass(format('%I.order_items', sch)) IS NULL + OR to_regclass(format('%I.picking_tasks', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'UPDATE %I.picking_items pi + SET required_qty = oi.received_qty + FROM %I.order_items oi, %I.picking_tasks pt + WHERE pt.pick_code = pi.pick_code + AND pi.order_item_id = oi.id + AND TRIM(COALESCE(oi.processing_owner, '''')) = ''warehouse'' + AND NULLIF(TRIM(COALESCE(oi.processing_method, '''')), '''') IS NOT NULL + AND TRIM(oi.processing_method) <> ''原材料'' + AND COALESCE(oi.received_stage, 0) >= 20 + AND COALESCE(oi.received_qty, 0) > 0 + AND COALESCE(pt.pick_status, 0) < 30 + AND COALESCE(pi.review_status, 10) < 30 + AND pi.required_qty IS DISTINCT FROM oi.received_qty', + sch, sch, sch + ); + END LOOP; +END $$; diff --git a/migrations/20261110_processing_raw_purchase_mirror.sql b/migrations/20261110_processing_raw_purchase_mirror.sql new file mode 100644 index 0000000..d2249a8 --- /dev/null +++ b/migrations/20261110_processing_raw_purchase_mirror.sql @@ -0,0 +1,62 @@ +-- 加工原料采购并入自采列表:把已有原料采购行镜像成 purchase_orders, +-- 同时把待采购计划量向上取整(历史草稿可能残留 15.714 类小数)。 +-- 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md +-- 幂等:只补缺、只处理 pending(10);可重复执行。 + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT n.nspname FROM pg_namespace n + WHERE n.nspname IN ('public','legacy_public','tenant_template') OR n.nspname LIKE 'tenant\_%' + ORDER BY n.nspname + LOOP + IF to_regclass(format('%I.processing_raw_purchases', sch)) IS NULL + OR to_regclass(format('%I.purchase_orders', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'UPDATE %I.processing_raw_purchases + SET planned_qty = CEIL(planned_qty), updated_at = NOW() + WHERE purchase_status = 10 + AND planned_qty IS NOT NULL + AND planned_qty <> CEIL(planned_qty)', + sch + ); + + EXECUTE format( + 'INSERT INTO %I.purchase_orders ( + purchase_code, order_code, sku_code, supplier_code, purchase_qty, purchase_price, + purchase_status, source_type, source_id, remark, branch_code + ) + SELECT r.purchase_code, + NULL, + r.material_sku, + NULL, + r.planned_qty, + 0, + CASE + WHEN r.purchase_status IN (10, 20, 30, 40) THEN r.purchase_status + ELSE 10 + END, + ''processing_raw_material'', + r.id::text, + NULL, + r.branch_code + FROM %I.processing_raw_purchases r + WHERE NOT EXISTS ( + SELECT 1 FROM %I.purchase_orders po WHERE po.purchase_code = r.purchase_code + ) + ON CONFLICT (purchase_code) DO NOTHING', + sch, sch, sch + ); + + EXECUTE format( + 'CREATE INDEX IF NOT EXISTS idx_purchase_orders_processing_raw + ON %I.purchase_orders (source_type, source_id)', + sch + ); + END LOOP; +END $$; diff --git a/migrations/20261111_processing_finished_pending_inspection_cleanup.sql b/migrations/20261111_processing_finished_pending_inspection_cleanup.sql new file mode 100644 index 0000000..8045bb7 --- /dev/null +++ b/migrations/20261111_processing_finished_pending_inspection_cleanup.sql @@ -0,0 +1,40 @@ +-- 仓内加工成品不应进入待入库/验收:清理历史遗留的成品待验行。 +-- 只删「未验收、未入库」且对应订单行是仓内加工成品的 inspections; +-- 原料的独立入库待验(order_code 为空)不受影响。 +-- 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT n.nspname FROM pg_namespace n + WHERE n.nspname IN ('public','legacy_public','tenant_template') OR n.nspname LIKE 'tenant\_%' + ORDER BY n.nspname + LOOP + IF to_regclass(format('%I.inspections', sch)) IS NULL + OR to_regclass(format('%I.order_items', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'DELETE FROM %I.inspections i + USING %I.order_items oi + WHERE i.order_code = oi.order_code + AND i.inspection_time IS NULL + AND i.inbound_batch_no IS NULL + AND TRIM(COALESCE(oi.processing_owner, '''')) = ''warehouse'' + AND NULLIF(TRIM(COALESCE(oi.processing_method, '''')), '''') IS NOT NULL + AND TRIM(oi.processing_method) <> ''原材料'' + AND ( + (oi.sku_code IS NOT NULL AND i.sku_code = oi.sku_code) + OR ( + oi.sku_code IS NULL + AND i.sku_code IS NULL + AND TRIM(COALESCE(i.item_name, '''')) = TRIM(COALESCE(oi.item_name, '''')) + ) + )', + sch, sch + ); + END LOOP; +END $$; diff --git a/migrations/20261112_processing_raw_inspection_visibility.sql b/migrations/20261112_processing_raw_inspection_visibility.sql new file mode 100644 index 0000000..44a6f08 --- /dev/null +++ b/migrations/20261112_processing_raw_inspection_visibility.sql @@ -0,0 +1,38 @@ +-- 加工原料采购(自采镜像)生成的待验是独立入库:order_code 为空, +-- 入库列表靠 processing_details.independent_inbound=true 才可见。 +-- 历史行没有这个标记,导致原材料已采购完成但入库列表看不到;这里幂等补齐。 +-- 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md + +DO $$ +DECLARE + sch text; +BEGIN + FOR sch IN + SELECT n.nspname FROM pg_namespace n + WHERE n.nspname IN ('public','legacy_public','tenant_template') OR n.nspname LIKE 'tenant\_%' + ORDER BY n.nspname + LOOP + IF to_regclass(format('%I.inspections', sch)) IS NULL + OR to_regclass(format('%I.purchase_orders', sch)) IS NULL THEN + CONTINUE; + END IF; + + EXECUTE format( + 'UPDATE %I.inspections i + SET processing_details = COALESCE(i.processing_details, ''{}''::jsonb) + || ''{"independent_inbound": true}''::jsonb + WHERE i.order_code IS NULL + AND i.inspection_time IS NULL + AND COALESCE(i.processing_details->>''independent_inbound'', '''') <> ''true'' + AND EXISTS ( + SELECT 1 FROM %I.purchase_orders po + WHERE po.source_type = ''processing_raw_material'' + AND ( + po.purchase_code = i.processing_details->>''purchase_code'' + OR COALESCE(i.processing_details->''purchase_codes'', ''[]''::jsonb) ? po.purchase_code + ) + )', + sch, sch + ); + END LOOP; +END $$; diff --git a/server/src/modules/workflow/routes/inspectionRoutes.ts b/server/src/modules/workflow/routes/inspectionRoutes.ts index cdd7d09..e774492 100644 --- a/server/src/modules/workflow/routes/inspectionRoutes.ts +++ b/server/src/modules/workflow/routes/inspectionRoutes.ts @@ -19,6 +19,7 @@ import { setProcessingWorkflowConfig, amendDemandSheetMaterialQty, deleteOrphanDemandSheet, + previewFinishedOutputAllocation, } from '../../../services/processingOps'; import { getInspectionWorkflowOptions } from '../../../services/inspectionPhotoService'; import { amendInspectionInbound } from '../../../services/inspectionAmendService'; @@ -612,6 +613,60 @@ router.delete('/processing/demand/:taskId', authMiddleware, async (req: AuthRequ } }); +/** 删除订单已完结后残留的加工单(仅管理员;只允许待加工/加工中,且订单已完结/已删除) */ +router.delete('/processing/order/:taskId', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['processing_manage', 'inspection_manage']); + if (!ctx || (!ctx.isSuperAdmin && !ctx.isBranchAdmin)) { + throw Object.assign(new Error('仅管理员可删除历史残留加工单'), { status: 403, code: 'forbidden' }); + } + const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req)); + if (!branchCode) { + return res.status(400).json({ error: 'invalid_request', error_description: '请选择当前操作分公司' }); + } + const { deleteCompletedOrderProcessingTask } = await import('../../../services/processingHistoryCleanupService'); + const data = await deleteCompletedOrderProcessingTask({ + taskId: String(req.params.taskId || ''), + branchCode, + operatorId: ctx?.userId || null, + }); + 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.delete('/processing/demand-history/:taskId', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['processing_manage', 'inspection_manage']); + if (!ctx || (!ctx.isSuperAdmin && !ctx.isBranchAdmin)) { + throw Object.assign(new Error('仅管理员可删除历史残留需求单'), { status: 403, code: 'forbidden' }); + } + const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req)); + if (!branchCode) { + return res.status(400).json({ error: 'invalid_request', error_description: '请选择当前操作分公司' }); + } + const { deleteOrphanDemandSheet } = await import('../../../services/processingDemandSheetService'); + const data = await deleteOrphanDemandSheet({ + taskId: String(req.params.taskId || ''), + expectedBranchCode: branchCode, + allowCompletedOrderLinks: true, + }); + 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.delete('/processing/standalone/:taskId', authMiddleware, async (req: AuthRequest, res: Response) => { try { @@ -681,6 +736,23 @@ router.put('/processing/workflow-enabled', authMiddleware, async (req: AuthReque } }); +router.get('/processing/demand/:taskId/finished-output-preview', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['processing_manage', 'inventory_manage']); + const data = await previewFinishedOutputAllocation({ + taskId: String(req.params.taskId || ''), + actualQty: req.query.actual_qty != null ? Number(req.query.actual_qty) : undefined, + }); + 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('/processing/start', authMiddleware, async (req: AuthRequest, res: Response) => { try { const ctx = await getWorkflowCtx(req); @@ -708,6 +780,12 @@ router.post('/processing/complete', authMiddleware, async (req: AuthRequest, res processUnitPrice: Number(req.body?.process_unit_price), remark: req.body?.remark ? String(req.body.remark) : undefined, operatorId: req.userId, + manualOutputAllocations: Array.isArray(req.body?.manual_output_allocations) + ? req.body.manual_output_allocations.map((row: any) => ({ + orderItemId: String(row?.order_item_id || ''), + qty: Number(row?.qty), + })) + : undefined, }); return res.json({ success: true }); } catch (error: any) { diff --git a/server/src/modules/workflow/routes/purchaseRoutes.ts b/server/src/modules/workflow/routes/purchaseRoutes.ts index c5ed848..9603fbf 100644 --- a/server/src/modules/workflow/routes/purchaseRoutes.ts +++ b/server/src/modules/workflow/routes/purchaseRoutes.ts @@ -58,6 +58,7 @@ import { } from '../../../services/zeroSupplyCostConfigService'; import { listPurchaseOrdersForManagement, sumSelfPurchaseTotalAmount } from '../../../services/purchaseOrderQueryService'; import { listPriceInvertRisks } from '../../../services/priceInvertRiskQueryService'; +import { syncRawMaterialPurchasesForOutputSku } from '../../../services/processingRawMaterialService'; import { resolveSelfPurchaseWriteAccess } from '../../../services/selfPurchaseHttpAccess'; import { assertOwnedStoragePaths } from '../../../services/storageObjectOwnership'; @@ -1184,6 +1185,26 @@ router.get('/purchase-orders/management-counts', authMiddleware, async (req: Aut } }); + +/** BOM 配置保存后调用:只同步未完工加工单,不阻断商品保存 */ +router.post('/purchase-orders/processing-raw-materials/sync', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['purchase_manage', 'inspection_manage']); + const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req)); + const data = await syncRawMaterialPurchasesForOutputSku({ + branchCode: branchCode || null, + outputSku: req.body?.output_sku ? String(req.body.output_sku) : null, + }); + return res.json({ data }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '同步加工原料采购失败', + }); + } +}); + /** 自采总成本:按日期范围全状态合计,不受列表 Tab / 搜索影响 */ router.get('/purchase-orders/self-purchase-total', authMiddleware, async (req: AuthRequest, res: Response) => { try { diff --git a/server/src/services/customerOrderSubmitService.ts b/server/src/services/customerOrderSubmitService.ts index e532b55..6933daf 100644 --- a/server/src/services/customerOrderSubmitService.ts +++ b/server/src/services/customerOrderSubmitService.ts @@ -587,6 +587,36 @@ export async function submitMobileCustomerOrder( (item: any, index: number) => String(item.id || item.key || `line-${index}`) ); + // 仓内加工必须有商品级原材料 BOM(防止小程序/接口绕过前端弹窗)。 + { + const { requiresWarehouseProcessing } = await import('./processingMethodUtils'); + const { hasProcessingBomForOutput } = await import('./processingRawMaterialService'); + const missingBomNames: string[] = []; + for (const item of pricedForInsert as Array>) { + if (!requiresWarehouseProcessing(item.processing_method, item.processing_owner)) continue; + const skuCode = String(item.sku_code || '').trim(); + const method = String(item.processing_method || '').trim(); + const hasBom = + skuCode && method + ? await hasProcessingBomForOutput(client, input.branchCode, skuCode, method) + : false; + if (!hasBom) { + missingBomNames.push( + String(item.item_name || item.sku_name || skuCode || '商品').trim() + ); + } + } + if (missingBomNames.length) { + await client.query('ROLLBACK'); + throw Object.assign( + new Error( + `以下仓内加工商品未配置原材料:${[...new Set(missingBomNames)].join('、')},请先在商品管理配置原材料后再下单` + ), + { status: 409, code: 'processing_bom_required' } + ); + } + } + orderCode = await allocateOrderCode(client, { channel: input.entryChannel, branchCode: input.branchCode, diff --git a/server/src/services/inspectionComplianceService.ts b/server/src/services/inspectionComplianceService.ts index aa81ec2..72142ec 100644 --- a/server/src/services/inspectionComplianceService.ts +++ b/server/src/services/inspectionComplianceService.ts @@ -600,7 +600,7 @@ export async function ensurePurchaseInspectionForCompletedPurchase( const poResult = await client.query( `SELECT purchase_code, order_code, sku_code, supplier_code, purchase_qty, purchase_price, - actual_qty, actual_price, purchase_status, branch_code + actual_qty, actual_price, purchase_status, branch_code, self_processed FROM purchase_orders WHERE purchase_code = $1 LIMIT 1`, @@ -608,6 +608,9 @@ export async function ensurePurchaseInspectionForCompletedPurchase( ); const po = poResult.rows[0]; if (!po || Number(po.purchase_status) !== 20) return; + // 仓内加工成品占位单(self_processed):成品免入库,不生成待验; + // 原材料由加工原料采购的独立自采单完成后再生成待验。 + if (Boolean(po.self_processed)) return; const skuCode = String(po.sku_code || '').trim(); if (skuCode && (await isSkuDirectDeliveryForPurchase(code, client))) { @@ -2011,6 +2014,20 @@ export async function submitInspectionCompliance( WHERE inspection_id = $1 AND inventory_id IS NULL`, [input.id, actualQty, purchasePrice, independentTotal, batchNo, inboundInventoryId] ); + // 加工原料采购:验收入库完成后同步采购记录(阶段 1,不阻断验收) + try { + const { syncProcessingRawPurchaseInboundFromInspection } = await import( + './processingRawMaterialService' + ); + await syncProcessingRawPurchaseInboundFromInspection(client, { + inspectionId: String(input.id), + actualQty, + unitCost: purchasePrice, + inventoryId: inboundInventoryId, + }); + } catch (rawError: any) { + console.warn('[processing-raw] 原料采购入库回写失败(不阻断验收)', rawError?.message || rawError); + } } if (isPartialInbound && row.order_code) { diff --git a/server/src/services/preparationFulfillmentService.ts b/server/src/services/preparationFulfillmentService.ts index 7339033..e8bab5a 100644 --- a/server/src/services/preparationFulfillmentService.ts +++ b/server/src/services/preparationFulfillmentService.ts @@ -2,6 +2,7 @@ import { PoolClient } from 'pg'; import { NON_VENDOR_SUPPLIER_SQL_LIST } from './allocationRules'; import { isOrderIndependentInbound } from './independentInbound'; import { pool } from '../db'; +import { requiresWarehouseProcessing } from './processingMethodUtils'; import { isRetailOrder } from './retailOrder'; import { lookupInspectionItemName } from './inspectionDisplayService'; import { @@ -474,8 +475,31 @@ export async function ensureInspectionsForOrder( ) )`; + // 先清掉仓内加工成品的历史待验(成品免入库) + await db.query( + `DELETE FROM inspections i + USING order_items oi + WHERE i.order_code = $1 + AND oi.order_code = $1 + AND TRIM(COALESCE(oi.processing_owner, '')) = 'warehouse' + AND NULLIF(TRIM(COALESCE(oi.processing_method, '')), '') IS NOT NULL + AND TRIM(oi.processing_method) <> '原材料' + AND i.inspection_time IS NULL + AND i.inbound_batch_no IS NULL + AND ( + (oi.sku_code IS NOT NULL AND i.sku_code = oi.sku_code) + OR ( + oi.sku_code IS NULL + AND i.sku_code IS NULL + AND TRIM(COALESCE(i.item_name, '')) = TRIM(COALESCE(oi.item_name, '')) + ) + )`, + [orderCode] + ); + const items = await db.query( `SELECT oi.id, oi.sku_code, oi.quantity, oi.price, oi.item_name, oi.supplier_code, + oi.processing_method, oi.processing_owner, COALESCE(oi.stock_cover_qty, 0)::float AS stock_cover_qty FROM order_items oi WHERE oi.order_code = $1 @@ -550,6 +574,26 @@ export async function ensureInspectionsForOrder( continue; } + // 仓内加工成品:成品不走供应商入库,也不应生成待验;原材料走原料采购独立入库 + if (requiresWarehouseProcessing(item.processing_method, item.processing_owner)) { + await db.query( + `DELETE FROM inspections + WHERE order_code = $1 + AND inspection_time IS NULL + AND inbound_batch_no IS NULL + AND ( + ($2::varchar IS NOT NULL AND sku_code = $2::varchar) + OR ( + $2::varchar IS NULL + AND sku_code IS NULL + AND TRIM(COALESCE(item_name, '')) = TRIM(COALESCE($3, '')) + ) + )`, + [orderCode, item.sku_code || null, item.item_name || null] + ); + continue; + } + const matchKey = { orderCode, skuCode: item.sku_code, diff --git a/server/src/services/processingDemandSheetService.ts b/server/src/services/processingDemandSheetService.ts index 55d3940..95016dd 100644 --- a/server/src/services/processingDemandSheetService.ts +++ b/server/src/services/processingDemandSheetService.ts @@ -1,5 +1,6 @@ /** * 仓内加工需求单:按分公司+配送日+成品 SKU+加工方式 汇总,仓管在单内领库存原料。 + * 2026-11-03:只复用「未开始/加工中」需求单,已完工/待验收不再接新需求。 * (业务前提:同一订单同一商品只会有一种加工方式,验收净重按 order_code+sku_code 归属不串单) * 成本口径:领料只扣库存、冲减持有行(在制品),不提前费用化; * 需求单完工时按「Σ领料成本 ÷ Σ验收净重」得出成品单位成本, @@ -213,7 +214,7 @@ async function findOrCreateDemandSheet( AND process_status < $5 ORDER BY process_status ASC, created_at ASC LIMIT 1`, - [input.branchCode, input.deliveryDate, input.sku, input.method, PROCESS_STATUS.rejected] + [input.branchCode, input.deliveryDate, input.sku, input.method, 30] ); if (existing.rowCount) return String(existing.rows[0].id); @@ -381,6 +382,14 @@ export async function syncWarehouseProcessingDemandForOrder( await recalcDemandSheetFromInspections(taskId, client); } + // 原材料自动采购草稿(阶段 1):需求单变化后按加工单同步;失败不阻断订单/需求单 + if (affectedTaskIds.size) { + const { syncRawMaterialPurchasesForDemandTasksSafely } = await import( + './processingRawMaterialService' + ); + await syncRawMaterialPurchasesForDemandTasksSafely(client, [...affectedTaskIds]); + } + if (branchCode) { await autoSkipOpenWarehouseDemandPurchases(code, client, branchCode); await clearStaleWarehouseDemandPurchaseFlags(client, { orderCode: code, branchCode }); @@ -510,6 +519,21 @@ async function loadClosedWarehouseDemandSheet(taskId: string, client: Db): Promi // 完工结算与追溯记录失去依据),调用方只把需求量归零。 return { exists: true, started: true }; } + // 原料采购已提交/已入库:不能随加工单 CASCADE 删除(否则采购/入库记录丢失), + // 保留加工单,交人工后续处理。 + try { + const submittedRaw = await client.query( + `SELECT 1 FROM processing_raw_purchases + WHERE demand_task_id = $1::uuid AND purchase_status >= 20 + LIMIT 1`, + [taskId] + ); + if (submittedRaw.rowCount) { + return { exists: true, started: true }; + } + } catch (error: any) { + if (!/processing_raw_purchases/i.test(String(error?.message || ''))) throw error; + } await client.query(`DELETE FROM processing_tasks WHERE id = $1 AND source_type = 'demand'`, [ taskId, ]); @@ -610,6 +634,43 @@ export async function skipWarehouseProcessingPurchase(input: { }); } + // 阶段2(成品免入库):已配置原材料 BOM 的成品不再生成成品待验收单, + // 占位单留在自采列表作为记录;未配置 BOM 的成品仍走原流程。 + if (row.order_code) { + const { hasProcessingBomForOutput } = await import('./processingRawMaterialService'); + const { isProcessingFinishedNoInventoryEnabled } = await import( + './processingFinishedNoInventoryConfigService' + ); + const oi = await client.query( + `SELECT sku_code, processing_method FROM order_items + WHERE order_code = $1 ORDER BY id ASC LIMIT 1`, + [row.order_code] + ); + const outputSku = trimText(oi.rows[0]?.sku_code); + const method = trimText(oi.rows[0]?.processing_method); + const hasBom = + outputSku && method + ? await hasProcessingBomForOutput(client, input.branchCode, outputSku, method) + : false; + if (hasBom && (await isProcessingFinishedNoInventoryEnabled(input.branchCode))) { + const baseRemark = trimText(input.operatorRemark) || SKIP_WAREHOUSE_REMARK; + await client.query( + `UPDATE purchase_orders + SET purchase_status = 20, actual_qty = $2, actual_price = 0, total_amount = 0, + submitted_at = NOW(), + remark = CASE + WHEN COALESCE(remark, '') = '' THEN $3 + WHEN POSITION($3 IN remark) > 0 THEN remark + ELSE remark || ';' || $3 + END + WHERE purchase_code = $1`, + [input.purchaseCode, qty, `${baseRemark}(成品免入库,无需操作)`] + ); + if (owns) await client.query('COMMIT'); + return { purchase_code: input.purchaseCode, status: 20 }; + } + } + await updatePurchaseOrderStatus( { purchaseCode: input.purchaseCode, @@ -1207,6 +1268,27 @@ export async function recalcDemandSheetFromInspections( const taskIdTrimmed = trimText(taskId); if (!taskIdTrimmed) return { net_weight: 0, completed: false, loss_qty: 0 }; + // 阶段2:已按加工单净重回写分配的成品,不再用成品验收单重算/降级状态 + try { + const phase2 = await db.query( + `SELECT finished_output_applied_at, COALESCE(net_weight, 0)::float AS net_weight, + COALESCE(loss_qty, 0)::float AS loss_qty + FROM processing_tasks + WHERE id = $1 AND finished_output_applied_at IS NOT NULL + LIMIT 1`, + [taskIdTrimmed] + ); + if (phase2.rows[0]) { + return { + net_weight: Number(phase2.rows[0].net_weight) || 0, + completed: true, + loss_qty: Number(phase2.rows[0].loss_qty) || 0, + }; + } + } catch (error: any) { + if (!/finished_output_applied_at|undefined_column/i.test(String(error?.message || ''))) throw error; + } + const items = await db.query( `SELECT di.order_item_id, di.order_code, di.sku_code, di.qty, oi.is_returned, oi.quantity, @@ -1518,7 +1600,11 @@ export function allocateProcessingCostByWeight( export async function settleDemandSheetCostOnCompletion( taskId: string, db: Db = pool, - options?: { overwriteInboundCostPrice?: boolean } + options?: { + overwriteInboundCostPrice?: boolean; + /** 阶段2(成品免入库)专用:直接给「订单 → 本单实际产出分配量」 */ + perOrderQty?: Array<{ orderCode: string; qty: number }>; + } ): Promise<{ unit_cost: number; allocated_amount: number }> { const id = trimText(taskId); if (!id) return { unit_cost: 0, allocated_amount: 0 }; @@ -1546,26 +1632,34 @@ export async function settleDemandSheetCostOnCompletion( [id] ); - // 按订单汇总验收净重(已称重入库的实收,含不合格标记) - const perOrder = await db.query( - `SELECT di.order_code, - COALESCE(( - SELECT SUM(COALESCE(i.actual_qty, 0)) - FROM inspections i - WHERE i.order_code = di.order_code - AND i.sku_code = $2 - AND i.actual_qty > 0 - AND i.inspection_time IS NOT NULL - AND COALESCE(i.compliance_status, 0) <> 30 - ), 0)::float AS inspected_qty - FROM processing_demand_items di - JOIN order_items oi ON oi.id = di.order_item_id - WHERE di.task_id = $1 - AND COALESCE(oi.is_returned, false) = false - GROUP BY di.order_code - ORDER BY di.order_code`, - [id, skuCode] - ); + // 按订单汇总验收净重;阶段2 免入库模式可直接传入分配量。 + const overrideRows = (options?.perOrderQty || []) + .map((row) => ({ + order_code: trimText(row.orderCode), + inspected_qty: roundQty(Number(row.qty) || 0), + })) + .filter((row) => row.order_code && row.inspected_qty > 0); + const perOrder = overrideRows.length + ? { rows: overrideRows } + : await db.query( + `SELECT di.order_code, + COALESCE(( + SELECT SUM(COALESCE(i.actual_qty, 0)) + FROM inspections i + WHERE i.order_code = di.order_code + AND i.sku_code = $2 + AND i.actual_qty > 0 + AND i.inspection_time IS NOT NULL + AND COALESCE(i.compliance_status, 0) <> 30 + ), 0)::float AS inspected_qty + FROM processing_demand_items di + JOIN order_items oi ON oi.id = di.order_item_id + WHERE di.task_id = $1 + AND COALESCE(oi.is_returned, false) = false + GROUP BY di.order_code + ORDER BY di.order_code`, + [id, skuCode] + ); const totalInspected = roundQty( perOrder.rows.reduce((s, r) => s + (Number(r.inspected_qty) || 0), 0) @@ -1662,6 +1756,8 @@ export async function recalcDemandSheetsForOrder( export async function deleteOrphanDemandSheet(input: { taskId: string; expectedBranchCode?: string | null; + /** 仅历史残留清理:允许关联订单,但要求所有关联订单已完结 */ + allowCompletedOrderLinks?: boolean; }): Promise<{ id: string; task_code: string; returned_material: boolean }> { const taskId = trimText(input.taskId); if (!taskId) { @@ -1684,15 +1780,40 @@ export async function deleteOrphanDemandSheet(input: { } const row = task.rows[0]; const liveCount = await countLiveDemandSheetOrderLinks(taskId, client); - assertOrphanDemandSheetDeletable({ - sourceType: row.source_type, - liveCount, - branchCode: row.branch_code, - expectedBranchCode: input.expectedBranchCode, - }); + if (input.allowCompletedOrderLinks) { + if (liveCount <= 0) { + throw Object.assign(new Error('该需求单没有订单关联,请使用普通删除'), { + status: 409, + code: 'not_linked', + }); + } + const unfinished = await client.query( + `SELECT COUNT(*)::int AS c + FROM processing_demand_items di + JOIN orders o ON o.order_code = di.order_code + WHERE di.task_id = $1 AND COALESCE(o.order_status, 0) < 90`, + [taskId] + ); + if (Number(unfinished.rows[0]?.c) > 0) { + throw Object.assign(new Error('关联订单尚未完结,不能删除'), { + status: 409, + code: 'order_not_completed', + }); + } + if (String(row.source_type || '') !== 'demand') { + throw Object.assign(new Error('仅可删除仓内加工需求单'), { status: 409, code: 'invalid_source' }); + } + } else { + assertOrphanDemandSheetDeletable({ + sourceType: row.source_type, + liveCount, + branchCode: row.branch_code, + expectedBranchCode: input.expectedBranchCode, + }); + } let returnedMaterial = false; - if ((Number(row.net_weight) || 0) <= 0) { + if (!input.allowCompletedOrderLinks && (Number(row.net_weight) || 0) <= 0) { returnedMaterial = (await returnDemandSheetMaterials(taskId, client)) > 0; } diff --git a/server/src/services/processingFinishedNoInventoryConfigService.ts b/server/src/services/processingFinishedNoInventoryConfigService.ts new file mode 100644 index 0000000..631f039 --- /dev/null +++ b/server/src/services/processingFinishedNoInventoryConfigService.ts @@ -0,0 +1,70 @@ +/** + * 仓内加工成品「免入库」开关(阶段 2 原型) + * + * 默认开启(kill switch):成品配置了原材料 BOM 时,成品免入库并按加工单回写实收/成本; + * 未配置 BOM 的成品完全不受影响(仍走原成品验收流程)。 + * 打开方式:system_configs.config_key='warehouse_processing_finished_no_inventory_enabled' + * (支持分公司级,branch_code IS NULL 为全局)。 + */ +import { pool } from '../db'; + +export const PROCESSING_FINISHED_NO_INVENTORY_KEY = + 'warehouse_processing_finished_no_inventory_enabled'; + +export interface ProcessingFinishedNoInventoryConfig { + enabled: boolean; +} + +export function parseProcessingFinishedNoInventoryConfig( + raw: unknown +): ProcessingFinishedNoInventoryConfig { + // 开发者 2026-11-02:成品免入库是默认流程(只在成品配置了原材料 BOM 时生效); + // 本开关作为 kill switch,默认开启,显式 enabled=false 可关闭。 + if (raw == null) return { enabled: true }; + if (typeof raw === 'boolean') return { enabled: raw }; + if (typeof raw === 'object') { + const obj = raw as Record; + if (typeof obj.enabled === 'boolean') return { enabled: obj.enabled }; + } + return { enabled: true }; +} + +export async function getProcessingFinishedNoInventoryConfig( + branchCode?: string | null +): Promise { + const code = String(branchCode || '').trim(); + try { + if (code) { + const branchRow = await pool.query( + `SELECT config_value FROM system_configs + WHERE config_key = $1 AND branch_code = $2 + LIMIT 1`, + [PROCESSING_FINISHED_NO_INVENTORY_KEY, code] + ); + if (branchRow.rows[0]?.config_value != null) { + return parseProcessingFinishedNoInventoryConfig(branchRow.rows[0].config_value); + } + } + const globalRow = await pool.query( + `SELECT config_value FROM system_configs + WHERE config_key = $1 AND branch_code IS NULL + LIMIT 1`, + [PROCESSING_FINISHED_NO_INVENTORY_KEY] + ); + if (globalRow.rows[0]?.config_value != null) { + return parseProcessingFinishedNoInventoryConfig(globalRow.rows[0].config_value); + } + } catch (error: any) { + console.warn( + '[processing-finished] 读取免入库开关失败,按默认开启处理(有 BOM 才生效)', + error?.message || error + ); + } + return { enabled: true }; +} + +export async function isProcessingFinishedNoInventoryEnabled( + branchCode?: string | null +): Promise { + return (await getProcessingFinishedNoInventoryConfig(branchCode)).enabled; +} diff --git a/server/src/services/processingFinishedOutputService.ts b/server/src/services/processingFinishedOutputService.ts new file mode 100644 index 0000000..ad655fd --- /dev/null +++ b/server/src/services/processingFinishedOutputService.ts @@ -0,0 +1,598 @@ +/** + * 仓内加工成品「完工分配 + 免入库回写」阶段 2 原型 + * + * 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md §4.2 / §12 + * + * ⚠️ 当前状态:**未接线**。本文件只提供: + * 1) 纯分配算法(可单测); + * 2) 事务内把分配结果回写订单行 received_qty / unit_cost / processing_settled_unit_cost 的服务。 + * 仍待开发者核查后再决定: + * - 是否删除/跳过成品验收单; + * - 订单状态 30→40→45 如何推进; + * - 配送扣库/发车核货如何跳过成品; + * - 成本记账口径(当前不写 inventory / cost_details)。 + * 开关默认关闭:warehouse_processing_finished_no_inventory_enabled。 + */ +import { pool } from '../db'; +import type { PoolClient } from 'pg'; +import { writeOrderItemReceivedQty } from './orderItemReceivedQtyService'; +import { + allocateProcessingCostByWeight, + settleDemandSheetCostOnCompletion, +} from './processingDemandSheetService'; +import { isProcessingFinishedNoInventoryEnabled } from './processingFinishedNoInventoryConfigService'; + +type Db = Pick; + +const QTY_SCALE = 1000; + +function roundQty(value: unknown): number { + return Math.round((Number(value) || 0) * QTY_SCALE) / QTY_SCALE; +} + +function roundMoney(value: unknown): number { + return Math.round((Number(value) || 0) * 100) / 100; +} + +function trimText(value: unknown): string { + return String(value ?? '').trim(); +} + +function allocatedTotalQty(plan: FinishedOutputPlan): number { + return plan.allocations.reduce((sum, row) => sum + row.allocatedQty, 0); +} + +export interface FinishedOutputDemandItem { + orderItemId: string; + orderCode: string; + customerName?: string | null; + demandQty: number; + orderCreatedAt: string | null; +} + +export interface FinishedOutputAllocation { + orderItemId: string; + orderCode: string; + customerName?: string | null; + demandQty: number; + allocatedQty: number; + orderCreatedAt: string | null; +} + +export interface FinishedOutputPlan { + actualQty: number; + totalDemandQty: number; + /** 产出不足时未满足的需求量 */ + shortfallQty: number; + /** 产出超过总需求时多出来的量(已按订单平均分给各订单) */ + excessQty: number; + allocations: FinishedOutputAllocation[]; +} + +function normalizeDemandItems(items: FinishedOutputDemandItem[]): FinishedOutputDemandItem[] { + return items + .map((item) => ({ + orderItemId: trimText(item.orderItemId), + orderCode: trimText(item.orderCode), + customerName: trimText((item as any).customerName) || null, + demandQty: roundQty(item.demandQty), + orderCreatedAt: item.orderCreatedAt || null, + })) + .filter((item) => item.orderItemId && item.orderCode && item.demandQty > 0) + .sort((a, b) => { + const at = a.orderCreatedAt ? Date.parse(a.orderCreatedAt) : Number.POSITIVE_INFINITY; + const bt = b.orderCreatedAt ? Date.parse(b.orderCreatedAt) : Number.POSITIVE_INFINITY; + if (at !== bt) return at - bt; + return a.orderItemId.localeCompare(b.orderItemId); + }); +} + +/** + * 成品产出分配(纯函数)。 + * + * 规则(开发者 2026-11-02 确认): + * - 订单按创建时间先到先得; + * - 产出 ≤ 总需求:按顺序满足,先 A 后 B; + * - 产出 > 总需求:先各自满足需求,余量按**参与订单数平均分** + * (A 需 4、B 需 5,余量 2 → A +1、B +1;除不尽时尾差按创建时间顺序补)。 + * 所有计算按 0.001 为单位,保证分配之和恰好等于实际产出。 + */ +export function planFinishedOutputAllocation( + demandItems: FinishedOutputDemandItem[], + actualQty: number +): FinishedOutputPlan { + const items = normalizeDemandItems(demandItems); + const actualUnits = Math.max(0, Math.round((Number(actualQty) || 0) * QTY_SCALE)); + const demandUnits = items.map((item) => Math.round(item.demandQty * QTY_SCALE)); + const totalDemandUnits = demandUnits.reduce((sum, units) => sum + units, 0); + const allocatedUnits = new Array(items.length).fill(0) as number[]; + + if (actualUnits > 0 && items.length) { + if (actualUnits >= totalDemandUnits) { + // 先满足各自需求 + for (let i = 0; i < items.length; i += 1) allocatedUnits[i] = demandUnits[i]; + // 余量按参与订单数平均分(订单内多行时再平均到行) + const extraUnits = actualUnits - totalDemandUnits; + const orders: Array<{ orderCode: string; itemIndexes: number[] }> = []; + for (let i = 0; i < items.length; i += 1) { + const existing = orders.find((order) => order.orderCode === items[i].orderCode); + if (existing) existing.itemIndexes.push(i); + else orders.push({ orderCode: items[i].orderCode, itemIndexes: [i] }); + } + const perOrder = Math.floor(extraUnits / orders.length); + let remainder = extraUnits - perOrder * orders.length; + for (const order of orders) { + let orderExtra = perOrder; + if (remainder > 0) { + orderExtra += 1; + remainder -= 1; + } + const perItem = Math.floor(orderExtra / order.itemIndexes.length); + let itemRemainder = orderExtra - perItem * order.itemIndexes.length; + for (const index of order.itemIndexes) { + allocatedUnits[index] += perItem + (itemRemainder > 0 ? 1 : 0); + if (itemRemainder > 0) itemRemainder -= 1; + } + } + } else { + // 不足:按订单创建时间顺序填满(先到先得) + let remaining = actualUnits; + for (let i = 0; i < items.length && remaining > 0; i += 1) { + const take = Math.min(remaining, demandUnits[i]); + allocatedUnits[i] = take; + remaining -= take; + } + } + } + + const allocations: FinishedOutputAllocation[] = items.map((item, index) => ({ + orderItemId: item.orderItemId, + orderCode: item.orderCode, + customerName: item.customerName || null, + demandQty: roundQty(item.demandQty), + allocatedQty: allocatedUnits[index] / QTY_SCALE, + orderCreatedAt: item.orderCreatedAt, + })); + const allocatedSum = allocations.reduce((sum, row) => sum + row.allocatedQty, 0); + return { + actualQty: actualUnits / QTY_SCALE, + totalDemandQty: roundQty(totalDemandUnits / QTY_SCALE), + shortfallQty: roundQty(Math.max(0, (totalDemandUnits - actualUnits) / QTY_SCALE)), + excessQty: roundQty(Math.max(0, allocatedSum - totalDemandUnits / QTY_SCALE)), + allocations, + }; +} + +export interface ManualFinishedOutputAllocation { + orderItemId: string; + qty: number; +} + +/** + * 人工指定各订单分配量:必须覆盖任务内全部订单行,数量 >=0, + * 合计与本次加工产出完全一致(0.001 精度),否则拒绝。 + */ +export function applyManualFinishedOutputAllocations( + demandItems: FinishedOutputDemandItem[], + actualQty: number, + manualAllocations: ManualFinishedOutputAllocation[] +): FinishedOutputPlan { + const base = planFinishedOutputAllocation(demandItems, actualQty); + if (!manualAllocations.length) return base; + const itemsById = new Map(base.allocations.map((row) => [row.orderItemId, row])); + const seen = new Set(); + const allocations = base.allocations.map((row) => { + const manual = manualAllocations.find((entry) => entry.orderItemId === row.orderItemId); + if (!manual) return { ...row, allocatedQty: 0 }; + seen.add(row.orderItemId); + const qty = roundQty(Number(manual.qty)); + if (!Number.isFinite(qty) || qty < 0) { + throw Object.assign(new Error('手工分配数量无效'), { status: 400, code: 'invalid_allocation' }); + } + if (qty > row.demandQty + 1e-6 && Number(actualQty) <= base.totalDemandQty + 1e-6) { + // 产出未超过总需求时不能给单订单超过其需求(超出部分应按超产能规则处理) + throw Object.assign(new Error('手工分配数量不能超过该订单需求'), { + status: 400, + code: 'invalid_allocation', + }); + } + return { ...row, allocatedQty: qty }; + }); + for (const entry of manualAllocations) { + if (!itemsById.has(String(entry.orderItemId))) { + throw Object.assign(new Error('手工分配包含不属于该加工单的订单行'), { + status: 400, + code: 'invalid_allocation', + }); + } + } + const sum = roundQty(allocations.reduce((total, row) => total + row.allocatedQty, 0)); + if (Math.abs(sum - roundQty(actualQty)) > 0.0011) { + throw Object.assign( + new Error(`手工分配合计 ${sum} 与加工产出 ${roundQty(actualQty)} 不一致`), + { status: 400, code: 'invalid_allocation' } + ); + } + return { + ...base, + allocations, + shortfallQty: roundQty( + Math.max(0, base.totalDemandQty - allocations.reduce((total, row) => total + row.allocatedQty, 0)) + ), + excessQty: roundQty( + Math.max(0, allocations.reduce((total, row) => total + row.allocatedQty, 0) - base.totalDemandQty) + ), + }; +} + +interface ProcessingTaskForFinishedOutput { + id: string; + task_code: string | null; + branch_code: string | null; + sku_code: string | null; + processing_method: string | null; + source_type: string | null; + process_status: number; + net_weight: number; + material_cost: number; + process_fee: number; + finished_output_applied_at: string | null; + finished_output_actual_qty: number | null; +} + +async function loadTaskWithDemandItems( + db: Db, + taskId: string +): Promise<{ + task: ProcessingTaskForFinishedOutput; + items: FinishedOutputDemandItem[]; +}> { + const id = trimText(taskId); + if (!id) throw Object.assign(new Error('缺少加工任务'), { status: 400 }); + const taskRow = ( + await db.query( + `SELECT id, task_code, branch_code, sku_code, processing_method, source_type, + COALESCE(process_status, 0)::int AS process_status, + COALESCE(net_weight, 0)::float AS net_weight, + COALESCE(material_cost, 0)::float AS material_cost, + COALESCE(process_fee, 0)::float AS process_fee, + finished_output_applied_at::text AS finished_output_applied_at, + finished_output_actual_qty::float AS finished_output_actual_qty + FROM processing_tasks + WHERE id = $1::uuid AND source_type = 'demand' + LIMIT 1`, + [id] + ) + ).rows[0]; + if (!taskRow) throw Object.assign(new Error('仓内加工需求单不存在'), { status: 404 }); + const itemRows = ( + await db.query( + `SELECT di.order_item_id::text AS order_item_id, + di.order_code, + COALESCE(di.qty, 0)::float AS demand_qty, + o.created_at::text AS order_created_at, + c.company_name AS customer_name + FROM processing_demand_items di + LEFT JOIN orders o ON o.order_code = di.order_code + LEFT JOIN customers c ON c.customer_code = o.customer_code + WHERE di.task_id = $1::uuid + ORDER BY o.created_at ASC NULLS LAST, di.created_at ASC, di.order_item_id ASC`, + [id] + ) + ).rows; + return { + task: taskRow as ProcessingTaskForFinishedOutput, + items: itemRows.map((row: any) => ({ + orderItemId: String(row.order_item_id || ''), + orderCode: String(row.order_code || ''), + customerName: row.customer_name ? String(row.customer_name) : null, + demandQty: Number(row.demand_qty) || 0, + orderCreatedAt: row.order_created_at || null, + })), + }; +} + +export interface FinishedOutputPreview { + task: { + id: string; + taskCode: string | null; + branchCode: string | null; + outputSku: string | null; + processingMethod: string | null; + netWeight: number; + materialCost: number; + processFee: number; + }; + plan: FinishedOutputPlan; + /** 加工总成本(原料成本 + 加工费) ÷ 实际产出 */ + unitCost: number; + totalCost: number; + /** 按订单实际分配数量分摊的金额(供评审成本口径) */ + costAllocations: Array<{ orderCode: string; amount: number }>; +} + +/** 只读预演:按加工任务当前完工净重(或指定实际产出)计算分配与成本,不写库。 */ +export async function previewFinishedOutputAllocation(input: { + taskId: string; + actualQty?: number; +}): Promise { + const { task, items } = await loadTaskWithDemandItems(pool, input.taskId); + const actualQty = + input.actualQty != null ? Number(input.actualQty) : Number(task.net_weight) || 0; + const plan = planFinishedOutputAllocation(items, actualQty); + // 成本口径沿用既有完工结算(settleDemandSheetCostOnCompletion):只分摊 material_cost, + // 加工费另走操作成本链路,不在这里重复计入。 + const totalCost = roundMoney(Number(task.material_cost)); + const allocatedTotal = plan.allocations.reduce((sum, row) => sum + row.allocatedQty, 0); + const unitCost = allocatedTotal > 0 ? roundMoney(totalCost / allocatedTotal) : 0; + const byOrder = new Map(); + for (const row of plan.allocations) { + if (row.allocatedQty <= 0) continue; + byOrder.set(row.orderCode, (byOrder.get(row.orderCode) || 0) + row.allocatedQty); + } + const { allocations: costAllocations } = allocateProcessingCostByWeight( + totalCost, + [...byOrder.entries()].map(([orderCode, inspectedQty]) => ({ orderCode, inspectedQty })) + ); + return { + task: { + id: task.id, + taskCode: task.task_code, + branchCode: task.branch_code, + outputSku: task.sku_code, + processingMethod: task.processing_method, + netWeight: Number(task.net_weight) || 0, + materialCost: Number(task.material_cost) || 0, + processFee: Number(task.process_fee) || 0, + }, + plan, + unitCost, + totalCost, + costAllocations, + }; +} + +export interface ApplyFinishedOutputResult extends FinishedOutputPreview { + applied: boolean; + /** 同一加工任务、同一实际产出、同阶段重复调用:直接返回,不重复写库 */ + alreadyApplied?: boolean; + /** 实际产出变了:按新产出重算并覆盖回写 */ + reapplied?: boolean; + /** 本原型回写订单行实收所用阶段(20=验收口径,待评审是否调整) */ + receivedStage: number; + /** 明确未做的部分,供开发者核查 */ + skipped: string[]; +} + +/** + * 阶段 2 原型:把完工产出按分配规则回写订单行实收与成本。 + * + * ⚠️ 不写库存、不动验收单、不改订单状态、不写 cost_details —— 这些接线待开发者核查后决定。 + * 开关关闭时直接拒绝(409)。 + */ +export async function applyFinishedOutputAllocation(input: { + taskId: string; + actualQty?: number; + operatorId?: string | null; + receivedStage?: 10 | 20 | 30 | 40 | 50 | 60; + /** 人工指定各订单本次分到的成品数量(不传则按默认分配规则) */ + manualAllocations?: ManualFinishedOutputAllocation[]; +}): Promise { + const client = await pool.connect(); + const receivedStage = input.receivedStage || 20; + try { + await client.query('BEGIN'); + const { task, items } = await loadTaskWithDemandItems(client, input.taskId); + const enabled = await isProcessingFinishedNoInventoryEnabled(task.branch_code); + if (!enabled) { + throw Object.assign( + new Error('成品免入库开关未开启(warehouse_processing_finished_no_inventory_enabled)'), + { status: 409, code: 'feature_disabled' } + ); + } + const actualQty = + input.actualQty != null ? Number(input.actualQty) : Number(task.net_weight) || 0; + const plan = input.manualAllocations?.length + ? applyManualFinishedOutputAllocations(items, actualQty, input.manualAllocations) + : planFinishedOutputAllocation(items, actualQty); + // 成本口径沿用既有完工结算(material_cost ÷ 分配数量),加工费不在本函数重复计。 + const totalCost = roundMoney(Number(task.material_cost)); + const alreadyAppliedQty = + task.finished_output_actual_qty != null ? Number(task.finished_output_actual_qty) : null; + const alreadyApplied = + Boolean(task.finished_output_applied_at) && + alreadyAppliedQty != null && + Math.abs(roundQty(alreadyAppliedQty) - roundQty(actualQty)) < 0.0005; + + const buildBase = (unitCost: number, costAllocations: Array<{ orderCode: string; amount: number }>) => ({ + receivedStage, + skipped: [ + '成品库存/库存流水未写(免入库)', + '成品验收单未删除/未跳过(待评审接线)', + '已写履约覆盖并尝试推进订单状态;若失败见服务日志', + '配送扣库/发车核货未跳过成品(待评审接线)', + 'cost_details 不写(沿用既有 processing_task 结算口径)', + ], + task: { + id: task.id, + taskCode: task.task_code, + branchCode: task.branch_code, + outputSku: task.sku_code, + processingMethod: task.processing_method, + netWeight: Number(task.net_weight) || 0, + materialCost: Number(task.material_cost) || 0, + processFee: Number(task.process_fee) || 0, + }, + plan, + unitCost, + totalCost, + costAllocations, + }); + + if (alreadyApplied) { + // 幂等:同产出重复调用直接返回上次结果(不重复写实收/成本) + const allocatedTotal = plan.allocations.reduce((sum, row) => sum + row.allocatedQty, 0); + const unitCost = allocatedTotal > 0 ? roundMoney(totalCost / allocatedTotal) : 0; + const byOrder = new Map(); + for (const row of plan.allocations) { + if (row.allocatedQty <= 0) continue; + byOrder.set(row.orderCode, (byOrder.get(row.orderCode) || 0) + row.allocatedQty); + } + const { allocations: costAllocations } = allocateProcessingCostByWeight( + totalCost, + [...byOrder.entries()].map(([orderCode, inspectedQty]) => ({ orderCode, inspectedQty })) + ); + await client.query('ROLLBACK'); + return { + applied: false, + alreadyApplied: true, + ...buildBase(unitCost, costAllocations), + }; + } + + for (const row of plan.allocations) { + if (row.allocatedQty <= 0) continue; + await writeOrderItemReceivedQty(client, { + orderCode: row.orderCode, + orderItemId: row.orderItemId, + qty: row.allocatedQty, + stage: receivedStage, + operatorId: input.operatorId || null, + }); + // 分拣单在订单提交时就已生成,需求数量默认取订单计划量; + // 加工完工分配后必须把「尚未完成分拣」的行改成该客户实际分到的成品数量, + // 否则分拣员会按原始需求拣、配送核货也会用旧数量。 + const pickUpdate = await client.query( + `UPDATE picking_items pi + SET required_qty = $2::numeric + FROM picking_tasks pt + WHERE pt.pick_code = pi.pick_code + AND pi.order_item_id = $1::uuid + AND COALESCE(pt.pick_status, 0) < 30 + AND COALESCE(pi.review_status, 10) < 30`, + [row.orderItemId, row.allocatedQty] + ); + if (Number(pickUpdate.rowCount || 0) === 0) { + const existingPick = await client.query( + `SELECT 1 FROM picking_items WHERE order_item_id = $1::uuid LIMIT 1`, + [row.orderItemId] + ); + if (existingPick.rowCount) { + console.warn( + '[processing-finished] 分拣已开始/已完成,未改写分拣需求数量', + row.orderCode, + row.orderItemId, + row.allocatedQty + ); + } + } + // 免入库路线:加工完工即视为该订单行履约完成(不产生成品库存/验收单)。 + // 写履约覆盖,让订单验收/推进判定通过,后续正常分拣/配送,不卡在待验收。 + const oiRow = await client.query( + `SELECT COALESCE(quantity, 0)::float AS quantity FROM order_items WHERE id = $1::uuid`, + [row.orderItemId] + ); + const coverQty = Number(oiRow.rows[0]?.quantity) || 0; + if (coverQty > 0) { + await client.query( + `UPDATE order_items + SET stock_cover_qty = GREATEST(COALESCE(stock_cover_qty, 0), $2::numeric) + WHERE id = $1::uuid`, + [row.orderItemId, coverQty] + ); + await client.query( + `INSERT INTO order_item_fulfillments + (order_item_id, order_code, supplier_preparation_id, purchase_code, + inventory_cover_qty, direct_delivery_cover) + VALUES ($1::uuid, $2, NULL, NULL, $3::numeric, false) + ON CONFLICT (order_item_id) DO UPDATE + SET supplier_preparation_id = NULL, + purchase_code = NULL, + inventory_cover_qty = EXCLUDED.inventory_cover_qty, + direct_delivery_cover = false, + updated_at = NOW()`, + [row.orderItemId, row.orderCode, coverQty] + ); + } + } + + // 仓内加工成品占位自采单:成品免入库,完工即关闭,避免列表长期显示「待入库」。 + const finishedOrderItemIds = plan.allocations + .filter((row) => row.allocatedQty > 0 && row.orderItemId) + .map((row) => String(row.orderItemId)); + if (finishedOrderItemIds.length) { + await client.query( + `UPDATE purchase_orders + SET purchase_status = 30, + actual_price = 0, + purchase_price = 0, + total_amount = 0, + updated_at = NOW() + WHERE self_processed = true + AND source_id = ANY($1::text[]) + AND purchase_status < 30`, + [finishedOrderItemIds] + ); + } + + // 成本回写复用既有完工结算逻辑:按本次分配量分摊 material_cost + const byOrder = new Map(); + for (const row of plan.allocations) { + if (row.allocatedQty <= 0) continue; + byOrder.set(row.orderCode, (byOrder.get(row.orderCode) || 0) + row.allocatedQty); + } + const settled = await settleDemandSheetCostOnCompletion(task.id, client, { + perOrderQty: [...byOrder.entries()].map(([orderCode, qty]) => ({ orderCode, qty })), + }); + + await client.query( + `UPDATE processing_tasks + SET finished_output_applied_at = NOW(), + finished_output_actual_qty = $2::numeric, + finished_output_applied_by = $3::uuid, + finished_output_plan = $4::jsonb + WHERE id = $1::uuid`, + [ + task.id, + roundQty(actualQty), + input.operatorId || null, + JSON.stringify({ + actual_qty: roundQty(actualQty), + received_stage: receivedStage, + unit_cost: settled.unit_cost, + allocations: plan.allocations, + applied_at: new Date().toISOString(), + }), + ] + ); + + await client.query('COMMIT'); + + // 加工完工即该订单行履约完成:推进订单状态(30→40→分拣/待配送),不卡订单。 + for (const orderCode of [...new Set(plan.allocations.filter((row) => row.allocatedQty > 0).map((row) => row.orderCode))]) { + try { + const { tryAdvanceOrderToInspection } = await import('./preparationFulfillmentService'); + await tryAdvanceOrderToInspection(orderCode); + const { maybeAdvanceOrderAfterFulfillment } = await import('./processingTaskService'); + await maybeAdvanceOrderAfterFulfillment(orderCode); + } catch (advanceError: any) { + console.warn('[processing-finished] 订单推进失败(不阻断回写)', orderCode, advanceError?.message || advanceError); + } + } + + const { allocations: costAllocations } = allocateProcessingCostByWeight( + totalCost, + [...byOrder.entries()].map(([orderCode, inspectedQty]) => ({ orderCode, inspectedQty })) + ); + return { + applied: true, + reapplied: Boolean(alreadyAppliedQty != null), + ...buildBase(settled.unit_cost || (allocatedTotalQty(plan) > 0 ? roundMoney(totalCost / allocatedTotalQty(plan)) : 0), costAllocations), + }; + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + throw error; + } finally { + client.release(); + } +} diff --git a/server/src/services/processingHistoryCleanupService.ts b/server/src/services/processingHistoryCleanupService.ts new file mode 100644 index 0000000..a7c140d --- /dev/null +++ b/server/src/services/processingHistoryCleanupService.ts @@ -0,0 +1,97 @@ +import { pool } from '../db'; + +/** + * 历史残留加工单清理(只读列表之外唯一的写操作)。 + * + * 场景:订单已经完结(order_status>=90),但订单验收链路生成的加工任务还停在 + * 待加工/加工中,页面上一直留着一条无法继续处理的“加工单”。 + * + * 约束(故意收窄): + * · 只允许 source_type='order' 且 process_status IN (10,20) 的残留任务; + * · 必须关联到已完结/已删除订单;未完结订单一律拒绝; + * · 仅管理员;事务内删除,processing_task_* 依赖由 FK ON DELETE CASCADE 清理; + * · 删除 task 关联的 cost_details(若有),不触碰订单、库存、结算。 + */ +export async function deleteCompletedOrderProcessingTask(input: { + taskId: string; + branchCode: string; + operatorId?: string | null; +}): Promise<{ id: string; task_code: string; order_code: string }> { + const taskId = String(input.taskId || '').trim(); + const branchCode = String(input.branchCode || '').trim(); + if (!taskId) { + throw Object.assign(new Error('缺少加工单 ID'), { status: 400, code: 'invalid_request' }); + } + if (!branchCode) { + throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' }); + } + + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const taskResult = await client.query( + `SELECT id, task_code, source_type, order_code, process_status, branch_code + FROM processing_tasks + WHERE id = $1 + FOR UPDATE`, + [taskId] + ); + const task = taskResult.rows[0]; + if (!task) { + throw Object.assign(new Error('加工单不存在'), { status: 404, code: 'not_found' }); + } + if (String(task.branch_code || '') !== branchCode) { + throw Object.assign(new Error('无权操作其它分公司的加工单'), { + status: 403, + code: 'branch_mismatch', + }); + } + if (String(task.source_type || '') !== 'order' || !String(task.order_code || '').trim()) { + throw Object.assign(new Error('仅订单验收链路的历史残留加工单可删除'), { + status: 400, + code: 'invalid_source', + }); + } + if (![10, 20].includes(Number(task.process_status))) { + throw Object.assign(new Error('只能删除待加工/加工中的历史残留加工单'), { + status: 409, + code: 'invalid_status', + }); + } + const orderResult = await client.query( + `SELECT order_code, order_status, deleted_at + FROM orders + WHERE order_code = $1 + LIMIT 1`, + [String(task.order_code)] + ); + const order = orderResult.rows[0]; + if (!order) { + throw Object.assign(new Error('关联订单不存在'), { status: 404, code: 'order_not_found' }); + } + if (Number(order.order_status) < 90 && !order.deleted_at) { + throw Object.assign(new Error('关联订单尚未完结,不能删除'), { + status: 409, + code: 'order_not_completed', + }); + } + + await client.query( + `DELETE FROM cost_details + WHERE reference_type = 'processing_task' AND reference_id = $1`, + [taskId] + ); + await client.query(`DELETE FROM processing_tasks WHERE id = $1`, [taskId]); + await client.query('COMMIT'); + return { + id: String(task.id), + task_code: String(task.task_code || ''), + order_code: String(task.order_code || ''), + }; + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + throw error; + } finally { + client.release(); + } +} diff --git a/server/src/services/processingOps.ts b/server/src/services/processingOps.ts index c48bab1..50a0ea7 100644 --- a/server/src/services/processingOps.ts +++ b/server/src/services/processingOps.ts @@ -31,3 +31,5 @@ export { } from './processingWorkflowConfigService'; export { amendDemandSheetMaterialQty } from './processingDemandPickAmendService'; + +export { previewFinishedOutputAllocation } from './processingFinishedOutputService'; diff --git a/server/src/services/processingRawMaterialService.ts b/server/src/services/processingRawMaterialService.ts new file mode 100644 index 0000000..6df710a --- /dev/null +++ b/server/src/services/processingRawMaterialService.ts @@ -0,0 +1,920 @@ +/** + * 仓内加工:原材料 BOM + 加工原料采购草稿(阶段 1) + * + * 口径(docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md): + * - 成品 product_catalog.processing_bom = [{method, material_sku, loss_rate}](人工维护,一成品一方法一原料) + * - 成品订单 → 加工单(processing_tasks.source_type='demand')汇总后,按加工单生成原料采购草稿 + * - 原料采购行同时镜像到 purchase_orders(source_type='processing_raw_material'), + * Web/小程序自采列表、完成、验收、入库全部走既有自采流程; + * - processing_raw_purchases 仅保留加工单↔原料的锚点信息(任务、BOM 原料、数量); + * - 只自动维护「待采购(10)」;已提交/已入库的不自动改。 + */ +import { pool } from '../db'; +import type { PoolClient } from 'pg'; +import { isZeroSupplyCostAllowed } from './zeroSupplyCostConfigService'; +import { createIndependentInboundInspection } from './independentInboundService'; +import { isProcessingRawPurchaseEnabled } from './processingRawPurchaseConfigService'; + +type Db = Pick; + +export interface ProcessingBomEntry { + method: string; + material_sku: string; + /** 损耗率 0~0.95:原料 = 成品 × (1 + loss_rate)(损耗按成品比例) */ + loss_rate: number; +} + +export type ProcessingRawPurchaseStatus = 10 | 20 | 30 | 40; + +export interface ProcessingRawPurchaseRow { + id: string; + purchase_code: string; + branch_code: string; + demand_task_id: string; + task_code: string | null; + output_sku: string; + output_name: string | null; + processing_method: string; + material_sku: string; + material_name: string | null; + unit: string | null; + planned_qty: number; + actual_qty: number | null; + unit_cost: number; + total_amount: number; + purchase_status: number; + inspection_id: string | null; + inventory_id: string | null; + purchaser_code: string | null; + purchaser_name: string | null; + remark: string | null; + created_at: string; + updated_at: string; +} + +function trimText(value: unknown): string { + return String(value ?? '').trim(); +} + +function roundQty(value: number): number { + return Math.round((Number(value) || 0) * 1000) / 1000; +} + +function roundMoney(value: number): number { + return Math.round((Number(value) || 0) * 100) / 100; +} + +function newRawPurchaseCode(): string { + return `RAW${Date.now()}${Math.random().toString(36).slice(2, 8).toUpperCase()}`; +} +/** + * 加工原料采购同时落一张自采列表可读的 purchase_orders 镜像: + * - 列表/小程序/完成/验收都走既有自采流程; + * - source_type='processing_raw_material'、source_id=原料采购行 id 用于回链; + * - 初始成本 0,完成时按自采规则要求成本 >0(除非分公司允许 0)。 + */ +async function upsertRawPurchaseOrderMirror( + db: Db, + input: { + rawId: string; + purchaseCode: string; + branchCode: string | null; + materialSku: string; + plannedQty: number; + } +): Promise { + await db.query( + `INSERT INTO purchase_orders ( + purchase_code, order_code, sku_code, supplier_code, purchase_qty, purchase_price, + purchase_status, source_type, source_id, remark, branch_code + ) VALUES ($1, NULL, $2, NULL, $3, 0, 10, 'processing_raw_material', $4, NULL, $5) + ON CONFLICT (purchase_code) DO UPDATE + SET sku_code = EXCLUDED.sku_code, + purchase_qty = EXCLUDED.purchase_qty, + branch_code = EXCLUDED.branch_code, + updated_at = NOW() + WHERE purchase_orders.source_type = 'processing_raw_material' + AND purchase_orders.purchase_status = 10`, + [ + input.purchaseCode, + input.materialSku, + input.plannedQty, + input.rawId, + input.branchCode, + ] + ); +} + +async function deleteRawPurchaseOrderMirror(db: Db, purchaseCode: string): Promise { + await db.query( + `DELETE FROM purchase_orders + WHERE purchase_code = $1 + AND source_type = 'processing_raw_material' + AND purchase_status < 20`, + [purchaseCode] + ); +} + + +/** 解析/归一 processing_bom JSON;非法项丢弃。 */ +export function normalizeProcessingBom(raw: unknown): ProcessingBomEntry[] { + if (!Array.isArray(raw)) return []; + const out: ProcessingBomEntry[] = []; + const seen = new Set(); + for (const item of raw) { + if (!item || typeof item !== 'object') continue; + const row = item as Record; + // method 允许为空:空 = 该商品所有加工方式通用(2026-11-02 商品级单原料) + const method = trimText(row.method); + const materialSku = trimText(row.material_sku ?? row.materialSku); + const lossRaw = Number(row.loss_rate ?? row.lossRate ?? 0); + if (!materialSku) continue; + if (!Number.isFinite(lossRaw) || lossRaw < 0 || lossRaw >= 1) continue; + const key = method.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push({ method, material_sku: materialSku, loss_rate: Math.round(lossRaw * 10000) / 10000 }); + } + return out; +} + +/** 成品需求 → 原料预计采购数量。损耗率按「损耗 = 原料 × 损耗率」定义,原料 = 成品 × (1 + 损耗率)。 */ +export function estimateRawMaterialQty(outputQty: number, lossRate: number): number { + const qty = Number(outputQty) || 0; + if (qty <= 0) return 0; + const loss = Number(lossRate) || 0; + if (loss <= 0) return roundQty(qty); + const clamped = Math.min(Math.max(loss, 0), 0.95); + return roundQty(qty * (1 + clamped)); +} + +/** 生成原料采购计划:向上取整为整数,避免 15.714 斤这类小数计划量。 */ +export function planRawMaterialPurchaseQty(outputQty: number, lossRate: number): number { + const estimated = estimateRawMaterialQty(outputQty, lossRate); + return estimated > 0 ? Math.max(1, Math.ceil(estimated - 1e-9)) : 0; +} + +/** 加工原料 BOM 明细(移动端领料弹窗用):原材料 sku、名称、单位、可用库存、损耗率。 */ +export async function getProcessingBomMaterialDetails(input: { + branchCode: string | null; + outputSku: string; + processingMethod: string; +}): Promise<{ + materialSku: string; + materialName: string; + materialUnit: string; + availableQty: number; + lossRate: number; +} | null> { + const bom = await loadBomEntry(pool as unknown as Db, input.branchCode, input.outputSku, input.processingMethod); + if (!bom) return null; + const materialSku = bom.material_sku; + const branch = input.branchCode || null; + const skuRow = await pool.query( + `SELECT sku_name, unit FROM skus + WHERE sku_code = $1 AND ($2::varchar IS NULL OR branch_code = $2 OR branch_code IS NULL) + ORDER BY (branch_code = $2) DESC NULLS LAST + LIMIT 1`, + [materialSku, branch] + ); + let materialName = String(skuRow.rows[0]?.sku_name || '').trim(); + let materialUnit = String(skuRow.rows[0]?.unit || '').trim(); + if (!materialName) { + const catRow = await pool.query( + `SELECT name, unit FROM product_catalog + WHERE item_type = 'product' AND code = $1 + AND ($2::varchar IS NULL OR branch_code = $2 OR branch_code IS NULL) + ORDER BY (branch_code = $2) DESC NULLS LAST + LIMIT 1`, + [materialSku, branch] + ); + materialName = String(catRow.rows[0]?.name || '').trim() || materialSku; + materialUnit = materialUnit || String(catRow.rows[0]?.unit || '').trim(); + } + const inventory = await pool.query( + `SELECT COALESCE(SUM(available_qty), 0)::float AS available_qty + FROM inventory + WHERE sku_code = $1 + AND ($2::varchar IS NULL OR branch_code = $2)`, + [materialSku, branch] + ); + return { + materialSku, + materialName, + materialUnit, + availableQty: Number(inventory.rows[0]?.available_qty) || 0, + lossRate: Number(bom.loss_rate) || 0, + }; +} + +async function loadBomEntry( + db: Db, + branchCode: string | null, + outputSku: string, + method: string +): Promise { + const sku = trimText(outputSku); + const procMethod = trimText(method); + // 只要求成品 SKU:加工方式为空不再直接判死(历史任务 / 未填加工方式)。 + // 2026-11-03 与 Web 弹窗对齐:Web 的顺序是「按方式 → 空方式通用 → 首条」。 + if (!sku) return null; + const result = await db.query( + `SELECT processing_bom + FROM product_catalog + WHERE item_type = 'product' + AND code = $1 + AND ($2::varchar IS NULL OR branch_code = $2::varchar) + ORDER BY (branch_code = $2::varchar) DESC NULLS LAST + LIMIT 1`, + [sku, branchCode] + ); + const entries = normalizeProcessingBom(result.rows[0]?.processing_bom); + const matched = + (procMethod + ? entries.find((entry) => entry.method.toLowerCase() === procMethod.toLowerCase()) + : null) || + entries.find((entry) => !entry.method) || + // 与 Web 一致:多条都不匹配时也取首条(旧版只在「恰好 1 条」时兜底, + // 导致 Web 显示产出/客户分配、小程序却退回手动选料)。 + entries[0] || + null; + return matched || null; +} + +/** 是否给该成品+加工方式配置了原材料(决定免入库/自动采购是否生效) */ +export async function hasProcessingBomForOutput( + db: Db, + branchCode: string | null, + outputSku: string, + method: string +): Promise { + return Boolean(await loadBomEntry(db, branchCode, trimText(outputSku), trimText(method))); +} + +async function loadMaterialInfo( + db: Db, + materialSku: string, + branchCode: string | null +): Promise<{ name: string; unit: string | null }> { + const row = ( + await db.query( + `SELECT sku_name, unit + FROM skus + WHERE sku_code = $1 + AND ($2::varchar IS NULL OR branch_code = $2::varchar) + ORDER BY (branch_code = $2::varchar) DESC NULLS LAST + LIMIT 1`, + [materialSku, branchCode] + ) + ).rows[0]; + return { name: trimText(row?.sku_name) || materialSku, unit: trimText(row?.unit) || null }; +} + +interface DemandTaskRow { + id: string; + task_code: string | null; + branch_code: string | null; + sku_code: string | null; + processing_method: string | null; + process_status: number; + demand_qty: number; + anchor_order: string | null; +} + +async function listDemandTasks(db: Db, taskIds: string[]): Promise { + const ids = [...new Set(taskIds.map((id) => trimText(id)).filter(Boolean))]; + if (!ids.length) return []; + const result = await db.query( + `SELECT pt.id, + pt.task_code, + pt.branch_code, + pt.sku_code, + pt.processing_method, + COALESCE(pt.process_status, 0) AS process_status, + COALESCE(SUM(di.qty), 0)::float AS demand_qty, + ( + SELECT di2.order_code + FROM processing_demand_items di2 + WHERE di2.task_id = pt.id + ORDER BY di2.created_at ASC + LIMIT 1 + ) AS anchor_order + FROM processing_tasks pt + LEFT JOIN processing_demand_items di ON di.task_id = pt.id + WHERE pt.id = ANY($1::uuid[]) + GROUP BY pt.id, pt.task_code, pt.branch_code, pt.sku_code, pt.processing_method, pt.process_status`, + [ids] + ); + return result.rows as DemandTaskRow[]; +} + +/** 只自动改动「待采购(10)」;其余状态追加人工确认提示。 */ +async function appendRawPurchaseRemark(db: Db, id: string, text: string): Promise { + await db.query( + `UPDATE processing_raw_purchases + SET remark = CASE + WHEN COALESCE(remark, '') = '' THEN $2 + WHEN POSITION($2 IN remark) > 0 THEN remark + ELSE remark || ';' || $2 + END, + updated_at = NOW() + WHERE id = $1::uuid`, + [id, text] + ); +} + +/** + * 订单需求单同步后调用:按加工单维护原料采购草稿。 + * - 无 BOM/无需求/加工单关闭:待采购草稿删除;已提交/已入库仅标提示 + * - 有 BOM:按加工单汇总需求生成/更新一张原料采购草稿(demand_task_id + material_sku 唯一) + */ +export async function syncRawMaterialPurchasesForDemandTasks( + db: Db, + taskIds: string[] +): Promise<{ created: number; updated: number; cancelled: number; flagged: number }> { + const result = { created: 0, updated: 0, cancelled: 0, flagged: 0 }; + const tasks = await listDemandTasks(db, taskIds); + if (!tasks.length) return result; + const enabledByBranch = new Map(); + const isEnabledForBranch = async (branchCode: string | null): Promise => { + const key = trimText(branchCode) || ''; + if (!enabledByBranch.has(key)) { + enabledByBranch.set(key, await isProcessingRawPurchaseEnabled(branchCode)); + } + return enabledByBranch.get(key) === true; + }; + const ids = tasks.map((task) => task.id); + const existingRows = ( + await db.query( + `SELECT r.id, r.demand_task_id, r.material_sku, r.planned_qty::float AS planned_qty, + COALESCE(po.purchase_status, r.purchase_status, 10)::int AS purchase_status, + r.purchase_code, + r.inspection_id::text AS inspection_id + FROM processing_raw_purchases r + LEFT JOIN purchase_orders po + ON po.purchase_code = r.purchase_code + AND po.source_type = 'processing_raw_material' + WHERE r.demand_task_id = ANY($1::uuid[])`, + [ids] + ) + ).rows as Array<{ + id: string; + demand_task_id: string; + material_sku: string; + planned_qty: number; + purchase_status: number; + purchase_code: string; + }>; + const byTask = new Map(); + for (const row of existingRows) { + const list = byTask.get(String(row.demand_task_id)) || []; + list.push(row); + byTask.set(String(row.demand_task_id), list); + } + + for (const task of tasks) { + const taskId = String(task.id); + const pendingRows = byTask.get(taskId) || []; + const branchCode = trimText(task.branch_code) || null; + if (!(await isEnabledForBranch(branchCode))) continue; + const outputSku = trimText(task.sku_code); + const method = trimText(task.processing_method); + const processStatus = Number(task.process_status) || 0; + const demandQty = Number(task.demand_qty) || 0; + // 只有未完工的加工单(10 待加工/20 加工中/30 待验收)才自动生成/更新原料采购; + // 已完工(40)/已拒收(50) 的加工单不再自动改,遗留待采购草稿只标人工确认。 + const bomEntry = + branchCode && outputSku && method && processStatus < 40 && demandQty > 0 + ? await loadBomEntry(db, branchCode, outputSku, method) + : null; + + if (!bomEntry) { + for (const row of pendingRows) { + const rowStatus = Number(row.purchase_status) || 10; + if (rowStatus === 10) { + // 还未提交采购:直接删除草稿及自采列表镜像 + await deleteRawPurchaseOrderMirror(db, String(row.purchase_code)); + await db.query(`DELETE FROM processing_raw_purchases WHERE id = $1::uuid`, [row.id]); + result.cancelled += 1; + continue; + } + if (rowStatus === 20) { + // 已采购但尚未入库:按开发者口径「还未入库可以取消」 + // 删掉其待验单;采购记录标记取消(保留审计痕迹) + await db.query( + `UPDATE processing_raw_purchases + SET purchase_status = 40, + remark = CASE + WHEN COALESCE(remark, '') = '' THEN '取消仓内加工,原料采购取消(未入库)' + WHEN POSITION('取消仓内加工' IN remark) > 0 THEN remark + ELSE remark || ';取消仓内加工,原料采购取消(未入库)' + END, + updated_at = NOW() + WHERE id = $1::uuid`, + [row.id] + ); + const inspectionId = (row as any).inspection_id; + if (inspectionId) { + await db.query( + `DELETE FROM inspections + WHERE id = $1::uuid AND inspection_time IS NULL`, + [inspectionId] + ); + } + // 自采流程完成后的待验单:按 purchase_code 从 processing_details 找并删除(仅未验收) + const mirror = ( + await db.query( + `SELECT purchase_code, purchase_status + FROM purchase_orders + WHERE purchase_code = $1 + AND source_type = 'processing_raw_material' + LIMIT 1`, + [String(row.purchase_code)] + ) + ).rows[0]; + if (mirror && Number(mirror.purchase_status) < 30) { + await db.query( + `DELETE FROM inspections + WHERE inspection_time IS NULL + AND inbound_batch_no IS NULL + AND ( + processing_details->>'purchase_code' = $1 + OR COALESCE(processing_details->'purchase_codes', '[]'::jsonb) ? $1 + )`, + [String(row.purchase_code)] + ); + await db.query( + `DELETE FROM purchase_orders + WHERE purchase_code = $1 + AND source_type = 'processing_raw_material' + AND purchase_status < 30`, + [String(row.purchase_code)] + ); + } + result.cancelled += 1; + continue; + } + // 已入库:按独立入库保留,不再属于加工原料采购的取消范围 + await appendRawPurchaseRemark( + db, + String(row.id), + rowStatus >= 30 + ? '原料已入库,按独立入库保留' + : '加工单已完工/关闭,请人工确认' + ); + result.flagged += 1; + } + continue; + } + + const material = await loadMaterialInfo(db, bomEntry.material_sku, branchCode); + const plannedQty = planRawMaterialPurchaseQty(demandQty, bomEntry.loss_rate); + const existing = pendingRows.find( + (row) => String(row.material_sku) === bomEntry.material_sku + ); + + // 同一加工单换了原料:旧的待采购草稿删掉;已提交/已入库标提示 + for (const row of pendingRows) { + if (String(row.material_sku) === bomEntry.material_sku) continue; + if (Number(row.purchase_status) === 10) { + await deleteRawPurchaseOrderMirror(db, String(row.purchase_code)); + await db.query(`DELETE FROM processing_raw_purchases WHERE id = $1::uuid`, [row.id]); + result.cancelled += 1; + } else { + await appendRawPurchaseRemark(db, String(row.id), '原料配置已改为新原料,请人工确认'); + result.flagged += 1; + } + } + + if (!existing) { + const purchaseCode = newRawPurchaseCode(); + const inserted = await db.query( + `INSERT INTO processing_raw_purchases ( + purchase_code, branch_code, demand_task_id, output_sku, processing_method, + material_sku, material_name, unit, planned_qty, purchase_status, remark, created_by + ) VALUES ($1, $2, $3::uuid, $4, $5, $6, $7, $8, $9, 10, NULL, NULL) + RETURNING id::text AS id`, + [ + purchaseCode, + branchCode, + taskId, + outputSku, + method, + bomEntry.material_sku, + material.name, + material.unit, + plannedQty, + ] + ); + await upsertRawPurchaseOrderMirror(db, { + rawId: String(inserted.rows[0]?.id || ''), + purchaseCode, + branchCode, + materialSku: bomEntry.material_sku, + plannedQty, + }); + result.created += 1; + continue; + } + + const status = Number(existing.purchase_status) || 10; + if (status === 10) { + await db.query( + `UPDATE processing_raw_purchases + SET planned_qty = $2, + material_name = $3, + unit = $4, + remark = CASE + WHEN remark LIKE '加工单 %' AND remark LIKE '%原料预计%' THEN NULL + ELSE remark + END, + updated_at = NOW() + WHERE id = $1::uuid`, + [existing.id, plannedQty, material.name, material.unit] + ); + await upsertRawPurchaseOrderMirror(db, { + rawId: String(existing.id), + purchaseCode: String(existing.purchase_code), + branchCode, + materialSku: bomEntry.material_sku, + plannedQty, + }); + result.updated += 1; + } else if (Math.abs(Number(existing.planned_qty) - plannedQty) > 0.0001) { + await appendRawPurchaseRemark( + db, + String(existing.id), + `加工单需求已变化:预计原料 ${existing.planned_qty} → ${plannedQty},请人工确认` + ); + result.flagged += 1; + } + } + return result; +} + +/** 同步包装:不阻断订单保存/需求单同步(失败只 warning)。 */ +export async function syncRawMaterialPurchasesForDemandTasksSafely( + db: Db, + taskIds: string[] +): Promise { + try { + const summary = await syncRawMaterialPurchasesForDemandTasks(db, taskIds); + if (summary.created || summary.updated || summary.cancelled || summary.flagged) { + console.log('[processing-raw] 原料采购草稿同步', summary); + } + } catch (error: any) { + console.warn('[processing-raw] 原料采购草稿同步失败(不阻断订单)', error?.message || error); + } +} + +/** BOM 配置变更后:同步该成品(按分公司)所有未完工加工单的原料采购草稿 */ +export async function syncRawMaterialPurchasesForOutputSku(input: { + branchCode: string | null; + outputSku?: string | null; +}): Promise<{ created: number; updated: number; cancelled: number; flagged: number }> { + const params: unknown[] = []; + const where: string[] = [ + `pt.source_type = 'demand'`, + `COALESCE(pt.process_status, 0) < 40`, + ]; + if (input.branchCode) { + params.push(input.branchCode); + where.push(`pt.branch_code = $${params.length}`); + } + const outputSku = trimText(input.outputSku); + if (outputSku) { + params.push(outputSku); + where.push(`pt.sku_code = $${params.length}`); + } + const tasks = await pool.query( + `SELECT DISTINCT pt.id + FROM processing_tasks pt + WHERE ${where.join(' AND ')} + LIMIT 2000`, + params + ); + return syncRawMaterialPurchasesForDemandTasks( + pool as unknown as Db, + tasks.rows.map((row: { id: string }) => String(row.id)) + ); +} + +/** 自采列表:加工原料采购草稿/记录 */ +export async function listProcessingRawPurchases(input: { + branchCode: string | null; + statusGroup?: 'pending' | 'completed' | 'all' | null; + search?: string | null; + limit?: number; +}): Promise { + const params: unknown[] = []; + const where: string[] = ['1=1']; + if (input.branchCode) { + params.push(input.branchCode); + where.push(`r.branch_code = $${params.length}`); + } + if (input.statusGroup === 'pending') where.push(`r.purchase_status IN (10, 20)`); + if (input.statusGroup === 'completed') where.push(`r.purchase_status IN (30, 40)`); + const search = trimText(input.search); + if (search) { + params.push(`%${search.replace(/[%_]/g, '\\$&')}%`); + where.push( + `(COALESCE(r.purchase_code, '') ILIKE $${params.length} OR COALESCE(r.material_name, '') ILIKE $${params.length} OR COALESCE(r.output_sku, '') ILIKE $${params.length} OR COALESCE(pt.task_code, '') ILIKE $${params.length})` + ); + } + params.push(Math.min(Math.max(Number(input.limit) || 200, 1), 500)); + const result = await pool.query( + `SELECT r.id, r.purchase_code, r.branch_code, r.demand_task_id, + pt.task_code, r.output_sku, osk.name AS output_name, + r.processing_method, r.material_sku, r.material_name, r.unit, + r.planned_qty::float AS planned_qty, r.actual_qty::float AS actual_qty, + r.unit_cost::float AS unit_cost, r.total_amount::float AS total_amount, + r.purchase_status, r.inspection_id, r.inventory_id, + r.purchaser_code, r.purchaser_name, r.remark, + r.created_at::text AS created_at, r.updated_at::text AS updated_at + FROM processing_raw_purchases r + LEFT JOIN processing_tasks pt ON pt.id = r.demand_task_id + LEFT JOIN product_catalog osk ON osk.item_type = 'product' AND osk.code = r.output_sku + AND osk.branch_code = r.branch_code + WHERE ${where.join(' AND ')} + ORDER BY r.created_at DESC + LIMIT $${params.length}`, + params + ); + return result.rows as ProcessingRawPurchaseRow[]; +} + +/** 修改待采购草稿:数量/成本价/备注 */ +export async function updateProcessingRawPurchase(input: { + id: string; + branchCode: string | null; + plannedQty?: number; + unitCost?: number; + remark?: string | null; +}): Promise { + const id = trimText(input.id); + if (!id) throw Object.assign(new Error('缺少原料采购记录'), { status: 400 }); + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const current = ( + await client.query( + `SELECT id, branch_code, purchase_status, planned_qty::float AS planned_qty, + actual_qty::float AS actual_qty, unit_cost::float AS unit_cost, + inspection_id::text AS inspection_id + FROM processing_raw_purchases + WHERE id = $1::uuid + LIMIT 1 + FOR UPDATE`, + [id] + ) + ).rows[0]; + if (!current) throw Object.assign(new Error('原料采购记录不存在'), { status: 404 }); + if (input.branchCode && String(current.branch_code || '') !== input.branchCode) { + throw Object.assign(new Error('无权操作其他分公司原料采购'), { status: 403 }); + } + const status = Number(current.purchase_status) || 10; + // 待采购(10) 可改;已采购待入库(20) 仅当待验单尚未验收时可改(开发者:已采购待入库到 Web 上改) + if (status !== 10 && status !== 20) { + throw Object.assign(new Error('该原料采购已入库/已取消,不能再修改'), { status: 409 }); + } + if (status === 20) { + if (!current.inspection_id) { + throw Object.assign(new Error('原料采购缺少待验单,不能修改'), { status: 409 }); + } + const inspection = ( + await client.query( + `SELECT inspection_time::text AS inspection_time FROM inspections WHERE id = $1::uuid LIMIT 1`, + [current.inspection_id] + ) + ).rows[0]; + if (!inspection) throw Object.assign(new Error('原料待验单不存在,不能修改'), { status: 409 }); + if (inspection.inspection_time) { + throw Object.assign(new Error('原料已验收入库,不能再修改'), { status: 409 }); + } + } + + const nextQty = + input.plannedQty != null ? roundQty(Number(input.plannedQty)) : Number(current.planned_qty) || 0; + const nextCost = + input.unitCost != null ? roundMoney(Number(input.unitCost)) : Number(current.unit_cost) || 0; + if (input.plannedQty != null && (!Number.isFinite(nextQty) || nextQty <= 0)) { + throw Object.assign(new Error('采购数量须大于 0'), { status: 400 }); + } + if (input.unitCost != null) { + const allowZero = await isZeroSupplyCostAllowed(input.branchCode); + if (!Number.isFinite(nextCost) || nextCost < 0 || (nextCost === 0 && !allowZero)) { + throw Object.assign(new Error('成本价须大于 0(除非开启允许成本为 0)'), { status: 400 }); + } + } + + const sets: string[] = ['updated_at = NOW()']; + const params: unknown[] = [id]; + if (input.plannedQty != null) { + params.push(nextQty); + sets.push(`planned_qty = $${params.length}`); + if (status === 20) { + params.push(nextQty); + sets.push(`actual_qty = $${params.length}`); + } + } + if (input.unitCost != null) { + params.push(nextCost); + sets.push(`unit_cost = $${params.length}`); + } + if (status === 20) { + params.push(roundMoney(nextQty * nextCost)); + sets.push(`total_amount = $${params.length}`); + } + if (input.remark !== undefined) { + params.push(trimText(input.remark) || null); + sets.push(`remark = $${params.length}`); + } + await client.query( + `UPDATE processing_raw_purchases SET ${sets.join(', ')} WHERE id = $1::uuid`, + params + ); + + // 待验单同步:验收按待验数量/单价称重入库 + if (status === 20) { + await client.query( + `UPDATE inspections + SET prepare_qty = $2::numeric, + purchase_price = $3::numeric + WHERE id = $1::uuid + AND inspection_time IS NULL`, + [current.inspection_id, nextQty, nextCost] + ); + } + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + throw error; + } finally { + client.release(); + } +} + +/** 提交采购 → 建独立入库待验单(进入库列表),验收后写库存 */ +export async function submitProcessingRawPurchase(input: { + id: string; + branchCode: string | null; + actualQty?: number; + unitCost?: number; + operatorId?: string | null; +}): Promise<{ inspectionId: string; batchNo: string }> { + const id = trimText(input.id); + if (!id) throw Object.assign(new Error('缺少原料采购记录'), { status: 400 }); + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const row = ( + await client.query( + `SELECT r.*, pt.task_code, pt.branch_code AS task_branch + FROM processing_raw_purchases r + LEFT JOIN processing_tasks pt ON pt.id = r.demand_task_id + WHERE r.id = $1::uuid + FOR UPDATE OF r`, + [id] + ) + ).rows[0]; + if (!row) throw Object.assign(new Error('原料采购记录不存在'), { status: 404 }); + if (Number(row.purchase_status) !== 10) { + throw Object.assign(new Error('该原料采购已提交,不能重复提交'), { status: 409 }); + } + const branchCode = trimText(row.branch_code) || input.branchCode; + if (input.branchCode && branchCode !== input.branchCode) { + throw Object.assign(new Error('无权操作其他分公司原料采购'), { status: 403 }); + } + const qty = roundQty(Number(input.actualQty != null ? input.actualQty : row.planned_qty)); + const unitCost = roundMoney( + Number(input.unitCost != null ? input.unitCost : row.unit_cost) + ); + if (!Number.isFinite(qty) || qty <= 0) { + throw Object.assign(new Error('采购数量须大于 0'), { status: 400 }); + } + const allowZero = await isZeroSupplyCostAllowed(branchCode); + if (!Number.isFinite(unitCost) || unitCost < 0 || (unitCost === 0 && !allowZero)) { + throw Object.assign(new Error('成本价须大于 0(除非开启允许成本为 0)'), { status: 400 }); + } + + const { inspectionId, batchNo } = await createIndependentInboundInspection(client, { + skuCode: String(row.material_sku), + itemName: String(row.material_name || row.material_sku), + qty, + unitCost, + branchCode: String(branchCode), + unit: row.unit ? String(row.unit) : null, + remark: `加工原料采购 ${row.purchase_code}(加工单 ${row.task_code || ''})`, + extraDetails: { processing_raw_purchase_id: id }, + }); + const totalAmount = roundMoney(qty * unitCost); + await client.query( + `UPDATE processing_raw_purchases + SET purchase_status = 20, + planned_qty = $2, + actual_qty = $2, + unit_cost = $3, + total_amount = $4, + inspection_id = $5::uuid, + purchaser_code = COALESCE(purchaser_code, NULL), + updated_at = NOW() + WHERE id = $1::uuid`, + [id, qty, unitCost, totalAmount, inspectionId] + ); + await client.query('COMMIT'); + return { inspectionId, batchNo }; + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + throw error; + } finally { + client.release(); + } +} + +/** 自采列表完成/状态变更后,把状态回写到原料采购行(取消/保护判断以自采流程为准) */ +export async function syncProcessingRawPurchaseFromPurchaseOrder( + client: Db, + purchaseCode: string +): Promise { + const code = trimText(purchaseCode); + if (!code) return; + try { + await client.query( + `UPDATE processing_raw_purchases r + SET purchase_status = po.purchase_status, + actual_qty = COALESCE(po.actual_qty, r.actual_qty), + unit_cost = COALESCE(NULLIF(po.actual_price, 0), po.purchase_price, r.unit_cost), + total_amount = COALESCE(po.total_amount, r.total_amount), + updated_at = NOW() + FROM purchase_orders po + WHERE po.purchase_code = $1 + AND po.source_type = 'processing_raw_material' + AND r.purchase_code = po.purchase_code`, + [code] + ); + } catch (error: any) { + // 迁移未上线/表不存在时不阻断采购流程 + if (!/processing_raw_purchases/i.test(String(error?.message || ''))) throw error; + } +} + +/** 验收入库完成:把原料采购记录标记为已入库(inspection 完成后由 inspectionComplianceService 回调) */ +export async function syncProcessingRawPurchaseInboundFromInspection( + client: Db, + input: { inspectionId: string; actualQty: number; unitCost: number; inventoryId: string | null } +): Promise { + const values = [ + input.inspectionId, + roundQty(input.actualQty), + roundMoney(input.unitCost), + input.inventoryId, + 30, + ]; + await client.query( + `UPDATE processing_raw_purchases + SET purchase_status = $5, + actual_qty = $2, + unit_cost = $3, + total_amount = ROUND($2::numeric * $3::numeric, 2), + inventory_id = $4::uuid, + updated_at = NOW() + WHERE inspection_id = $1::uuid + AND purchase_status < $5`, + values + ).catch((error: any) => { + // 迁移未上线/表不存在时不阻断验收 + if (!/processing_raw_purchases/i.test(String(error?.message || ''))) throw error; + }); + + // 镜像自采单路径:原料行 inspection_id 为空,按 purchase_code 回写原料锚点状态 + try { + const detail = await client.query( + `SELECT processing_details FROM inspections WHERE id = $1::uuid LIMIT 1`, + [input.inspectionId] + ); + const details = (detail.rows[0]?.processing_details || {}) as Record; + const codes = [ + String(details.purchase_code || '').trim(), + ...(Array.isArray(details.purchase_codes) ? details.purchase_codes.map(String) : []), + ].filter(Boolean); + if (codes.length) { + await client.query( + `UPDATE processing_raw_purchases r + SET purchase_status = 30, + actual_qty = $1, + unit_cost = $2, + total_amount = ROUND($1::numeric * $2::numeric, 2), + inventory_id = $3::uuid, + updated_at = NOW() + FROM purchase_orders po + WHERE po.source_type = 'processing_raw_material' + AND po.purchase_code = ANY($4::text[]) + AND r.purchase_code = po.purchase_code + AND r.purchase_status < 30`, + [roundQty(input.actualQty), roundMoney(input.unitCost), input.inventoryId, codes] + ); + } + } catch (error: any) { + if (!/processing_raw_purchases/i.test(String(error?.message || ''))) throw error; + } +} diff --git a/server/src/services/processingRawPurchaseConfigService.ts b/server/src/services/processingRawPurchaseConfigService.ts new file mode 100644 index 0000000..2b195b1 --- /dev/null +++ b/server/src/services/processingRawPurchaseConfigService.ts @@ -0,0 +1,62 @@ +/** + * 仓内加工原料自动采购开关(阶段 1) + * + * 默认开启:只在成品配置了 processing_bom 时才触发,未配置的商品完全无行为变化。 + * 关闭方式:system_configs.config_key='warehouse_processing_raw_purchase_enabled', + * 支持分公司级(branch_code)与全局(branch_code IS NULL)。 + */ +import { pool } from '../db'; + +export const PROCESSING_RAW_PURCHASE_ENABLED_KEY = 'warehouse_processing_raw_purchase_enabled'; + +export interface ProcessingRawPurchaseConfig { + enabled: boolean; +} + +export function parseProcessingRawPurchaseConfig(raw: unknown): ProcessingRawPurchaseConfig { + if (raw == null) return { enabled: true }; + if (typeof raw === 'boolean') return { enabled: raw }; + if (typeof raw === 'object') { + const obj = raw as Record; + if (typeof obj.enabled === 'boolean') return { enabled: obj.enabled }; + } + return { enabled: true }; +} + +export async function getProcessingRawPurchaseConfig( + branchCode?: string | null +): Promise { + const code = String(branchCode || '').trim(); + try { + if (code) { + const branchRow = await pool.query( + `SELECT config_value FROM system_configs + WHERE config_key = $1 AND branch_code = $2 + LIMIT 1`, + [PROCESSING_RAW_PURCHASE_ENABLED_KEY, code] + ); + if (branchRow.rows[0]?.config_value != null) { + return parseProcessingRawPurchaseConfig(branchRow.rows[0].config_value); + } + } + const globalRow = await pool.query( + `SELECT config_value FROM system_configs + WHERE config_key = $1 AND branch_code IS NULL + LIMIT 1`, + [PROCESSING_RAW_PURCHASE_ENABLED_KEY] + ); + if (globalRow.rows[0]?.config_value != null) { + return parseProcessingRawPurchaseConfig(globalRow.rows[0].config_value); + } + } catch (error: any) { + // 配置表不可用时不阻断业务:按默认开启(有 BOM 才触发) + console.warn('[processing-raw] 读取自动采购开关失败,按默认开启处理', error?.message || error); + } + return { enabled: true }; +} + +export async function isProcessingRawPurchaseEnabled( + branchCode?: string | null +): Promise { + return (await getProcessingRawPurchaseConfig(branchCode)).enabled; +} diff --git a/server/src/services/processingTaskService.ts b/server/src/services/processingTaskService.ts index 1d04a7f..7454c83 100644 --- a/server/src/services/processingTaskService.ts +++ b/server/src/services/processingTaskService.ts @@ -769,7 +769,14 @@ export async function listProcessingTasks( item_log.last_net_weight, i.inspection_time IS NOT NULL AS inspection_completed, o.delivery_date, - ${demandSheetLiveLinkCountExpr('pt.id')} AS linked_order_count + o.order_status, + ${demandSheetLiveLinkCountExpr('pt.id')} AS linked_order_count, + ( + SELECT COUNT(*)::int + FROM processing_demand_items di2 + JOIN orders o2 ON o2.order_code = di2.order_code + WHERE di2.task_id = pt.id AND COALESCE(o2.order_status, 0) < 90 + ) AS unfinished_linked_order_count FROM processing_tasks pt ${PROCESSING_TASK_JOINS_SQL} LEFT JOIN LATERAL ( @@ -967,9 +974,12 @@ export async function completeProcessingWork(input: { processUnitPrice?: number; operatorId?: string | null; remark?: string; + /** 需求单人工指定各订单分到的成品数量;不传按默认规则 */ + manualOutputAllocations?: Array<{ orderItemId: string; qty: number }>; }) { const current = await pool.query( `SELECT pt.process_status, pt.order_code, pt.sku_code, pt.processing_method, + pt.source_type, pt.branch_code, COALESCE(pt.material_qty, 0)::float AS material_qty, ${PROCESSING_ITEM_NAME_SQL} AS item_name FROM processing_tasks pt ${PROCESSING_TASK_JOINS_SQL} @@ -982,6 +992,12 @@ export async function completeProcessingWork(input: { if (status !== PROCESS_STATUS.pending && status !== PROCESS_STATUS.inProgress) { throw new Error('当前状态不能提交加工完工'); } + if (String(row.source_type || '') === 'demand' && Number(row.material_qty) <= 0) { + throw Object.assign(new Error('请先领料后再提交加工完工'), { + status: 400, + code: 'material_not_picked', + }); + } const gross = Number(input.grossWeight) || 0; const net = Number(input.netWeight) || 0; @@ -1044,6 +1060,50 @@ export async function completeProcessingWork(input: { ] ); await client.query('COMMIT'); + + // 阶段2:需求单 + 已配置原材料 BOM,完工即分配回写订单行实收/成本。 + if (String(row.source_type || '') === 'demand' && net > 0) { + try { + const { isProcessingFinishedNoInventoryEnabled } = await import( + './processingFinishedNoInventoryConfigService' + ); + const enabled = await isProcessingFinishedNoInventoryEnabled(row.branch_code); + if (enabled) { + const { hasProcessingBomForOutput } = await import('./processingRawMaterialService'); + const hasBom = await hasProcessingBomForOutput( + pool, + row.branch_code || null, + String(row.sku_code || ''), + String(row.processing_method || '') + ); + if (hasBom) { + const { applyFinishedOutputAllocation } = await import( + './processingFinishedOutputService' + ); + await applyFinishedOutputAllocation({ + taskId: input.taskId, + actualQty: net, + operatorId: input.operatorId || null, + receivedStage: 20, + manualAllocations: input.manualOutputAllocations?.length + ? input.manualOutputAllocations + : undefined, + }); + await pool.query( + `UPDATE processing_tasks + SET process_status = $2, updated_at = NOW() + WHERE id = $1 AND source_type = 'demand'`, + [input.taskId, PROCESS_STATUS.completed] + ); + } + } + } catch (phase2Error: any) { + console.warn( + '[processing-finished] 成品免入库回写失败(任务保持待验收,待人工核查)', + phase2Error?.message || phase2Error + ); + } + } } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; diff --git a/server/src/services/purchaseOperationService.ts b/server/src/services/purchaseOperationService.ts index 584a54c..58671a9 100644 --- a/server/src/services/purchaseOperationService.ts +++ b/server/src/services/purchaseOperationService.ts @@ -1,6 +1,7 @@ import type { PoolClient } from 'pg'; import { pool } from '../db'; import { orderReceivedQtyDb, writeOrderItemReceivedQtyWithStockCover } from './orderItemReceivedQtyService'; +import { syncProcessingRawPurchaseFromPurchaseOrder } from './processingRawMaterialService'; import { assertPurchaseOrderInBranch } from './purchaserBranchScope'; import { PURCHASE_STATUS_QUALITY_REJECTED } from './purchaseInboundService'; import { ensurePurchaseInspectionForCompletedPurchase } from './inspectionComplianceService'; @@ -247,6 +248,13 @@ export async function updatePurchaseOrderStatus( } } + // 加工原料采购映射到自采订单:把状态回写原料行 + if (status === 20) { + await syncProcessingRawPurchaseFromPurchaseOrder(client, purchaseCode).catch((error) => { + console.warn('[processing-raw] 回写原料采购状态失败(不阻断采购完成)', error); + }); + } + // 实采价为 0:把「下单采购价」与金额一并清零,避免各处读取点 // (`COALESCE(NULLIF(actual_price,0), purchase_price)`:金额重算 / 倒挂判定 / 列表展示) // 把真实的 0 成本静默回退成下单价。适用两种情形: diff --git a/server/src/services/selfPurchaseStockInboundService.ts b/server/src/services/selfPurchaseStockInboundService.ts index 70a58c3..aab3e9b 100644 --- a/server/src/services/selfPurchaseStockInboundService.ts +++ b/server/src/services/selfPurchaseStockInboundService.ts @@ -81,6 +81,22 @@ export async function bounceIndependentInboundPendingInspection( WHERE id = $1::uuid AND inspection_time IS NULL`, [id] ); + // 加工原料采购:待验单退回后回到待采购 + try { + await client.query( + `UPDATE processing_raw_purchases + SET purchase_status = 10, + inspection_id = NULL, + actual_qty = NULL, + total_amount = 0, + updated_at = NOW() + WHERE inspection_id = $1::uuid + AND purchase_status = 20`, + [id] + ); + } catch (error: any) { + if (!/processing_raw_purchases/i.test(String(error?.message || ''))) throw error; + } if (!deleted.rowCount) { throw Object.assign(new Error('该验收单已提交,不能退回'), { status: 409, diff --git a/server/tests/processingFinishedOutput.test.ts b/server/tests/processingFinishedOutput.test.ts new file mode 100644 index 0000000..e12f221 --- /dev/null +++ b/server/tests/processingFinishedOutput.test.ts @@ -0,0 +1,259 @@ +/** + * 仓内加工成品完工分配(阶段 2 原型)契约测试 + * 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md §4.2 / §12 + */ +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + applyManualFinishedOutputAllocations, + planFinishedOutputAllocation, + type FinishedOutputDemandItem, +} from '../src/services/processingFinishedOutputService'; +import { parseProcessingFinishedNoInventoryConfig } from '../src/services/processingFinishedNoInventoryConfigService'; + +const ROOT = path.join(__dirname, '../..'); +const read = (rel: string) => readFileSync(path.join(ROOT, rel), 'utf8'); + +function item( + orderItemId: string, + orderCode: string, + demandQty: number, + orderCreatedAt: string +): FinishedOutputDemandItem { + return { orderItemId, orderCode, demandQty, orderCreatedAt }; +} + +describe('历史分拣需求数量回填', () => { + it('迁移把已完工成品的未开始分拣行需求改成实收分配量', () => { + const migration = read('migrations/20261109_processing_picking_required_sync.sql'); + expect(migration).toContain('SET required_qty = oi.received_qty'); + expect(migration).toContain("processing_owner, '''')) = ''warehouse''"); + expect(migration).toContain('received_stage'); + expect(migration).toContain('pick_status, 0) < 30'); + }); +}); + +describe('加工完工同步分拣/配送数量', () => { + it('完工分配后把未开始分拣行的 required_qty 改成该客户实际分配量', () => { + const service = read('server/src/services/processingFinishedOutputService.ts'); + expect(service).toContain('UPDATE picking_items pi'); + expect(service).toContain('SET required_qty = $2::numeric'); + expect(service).toContain('COALESCE(pt.pick_status, 0) < 30'); + expect(service).toContain('row.allocatedQty'); + }); +}); + +describe('人工调整各客户成品分配', () => { + const a = item('oi-a', 'ORD_A', 5, '2026-11-02T08:00:00Z'); + const b = item('oi-b', 'ORD_B', 4, '2026-11-02T09:00:00Z'); + + it('产出 10 斤:人工 A 6 / B 4(A 多分 1 斤)', () => { + const plan = applyManualFinishedOutputAllocations([a, b], 10, [ + { orderItemId: 'oi-a', qty: 6 }, + { orderItemId: 'oi-b', qty: 4 }, + ]); + expect(plan.allocations.map((x) => [x.orderCode, x.allocatedQty])).toEqual([ + ['ORD_A', 6], + ['ORD_B', 4], + ]); + }); + + it('人工合计与产出不一致时拒绝', () => { + expect(() => + applyManualFinishedOutputAllocations([a, b], 10, [ + { orderItemId: 'oi-a', qty: 6 }, + { orderItemId: 'oi-b', qty: 3 }, + ]) + ).toThrow(/不一致/); + }); +}); + +describe('成品产出分配:先到先得 + 余量平均分', () => { + const a = item('oi-a', 'ORD_A', 4, '2026-11-02T08:00:00Z'); + const b = item('oi-b', 'ORD_B', 5, '2026-11-02T09:00:00Z'); + + it('产出恰好满足:A 4 / B 5', () => { + const plan = planFinishedOutputAllocation([b, a], 9); + expect(plan.allocations.map((x) => [x.orderCode, x.allocatedQty])).toEqual([ + ['ORD_A', 4], + ['ORD_B', 5], + ]); + expect(plan.shortfallQty).toBe(0); + expect(plan.excessQty).toBe(0); + }); + + it('产出不足:先满足先创建的 A,再给 B', () => { + const plan = planFinishedOutputAllocation([a, b], 7); + expect(plan.allocations.map((x) => [x.orderCode, x.allocatedQty])).toEqual([ + ['ORD_A', 4], + ['ORD_B', 3], + ]); + expect(plan.shortfallQty).toBe(2); + expect(plan.excessQty).toBe(0); + }); + + it('产出有余量:先满足需求,余量按参与订单数平均分(A+1/B+1)', () => { + const plan = planFinishedOutputAllocation([a, b], 11); + expect(plan.allocations.map((x) => [x.orderCode, x.allocatedQty])).toEqual([ + ['ORD_A', 5], + ['ORD_B', 6], + ]); + expect(plan.excessQty).toBe(2); + }); + + it('余量除不尽(0.001 粒度)时尾差按创建时间顺序补', () => { + const c1 = item('oi-1', 'ORD_1', 1, '2026-11-02T08:00:00Z'); + const c2 = item('oi-2', 'ORD_2', 1, '2026-11-02T09:00:00Z'); + const plan = planFinishedOutputAllocation([a, b], 12); + // 余量 3 → A/B 各 1.5(0.001 粒度可整除,直接平均) + expect(plan.allocations.map((x) => [x.orderCode, x.allocatedQty])).toEqual([ + ['ORD_A', 5.5], + ['ORD_B', 6.5], + ]); + + // 余量 0.001 无法分成两个 0.0005 → 整份给先创建的 A + const planTiny = planFinishedOutputAllocation([c1, c2], 2.001); + expect(planTiny.allocations.map((x) => [x.orderCode, x.allocatedQty])).toEqual([ + ['ORD_1', 1.001], + ['ORD_2', 1], + ]); + }); + + it('开发者场景:A 需 5 斤、B 需 4 斤,实际产出 10 斤 → 先满足 5/4,余 1 斤均分 → 5.5/4.5', () => { + const oa = item('oi-a', 'ORD_A', 5, '2026-11-02T08:00:00Z'); + const ob = item('oi-b', 'ORD_B', 4, '2026-11-02T09:00:00Z'); + const plan = planFinishedOutputAllocation([ob, oa], 10); + expect(plan.allocations.map((x) => [x.orderCode, x.allocatedQty])).toEqual([ + ['ORD_A', 5.5], + ['ORD_B', 4.5], + ]); + expect(plan.excessQty).toBe(1); + expect(plan.shortfallQty).toBe(0); + }); + + it('小数按 0.001 精度,分配之和恰好等于实际产出', () => { + const c1 = item('oi-1', 'ORD_1', 1, '2026-11-02T08:00:00Z'); + const c2 = item('oi-2', 'ORD_2', 1, '2026-11-02T09:00:00Z'); + const planInexact = planFinishedOutputAllocation([c1, c2], 2.001); + const sumInexact = planInexact.allocations.reduce((s, x) => s + x.allocatedQty, 0); + expect(Math.round(sumInexact * 1000) / 1000).toBe(2.001); + + const planShort = planFinishedOutputAllocation([c1, c2], 0.5); + expect(planShort.allocations[0].allocatedQty).toBe(0.5); + expect(planShort.allocations[1].allocatedQty).toBe(0); + }); + + it('同一订单多行:订单余量先按行平均,尾差给前面的行', () => { + const a1 = item('oi-a1', 'ORD_A', 2, '2026-11-02T08:00:00Z'); + const a2 = item('oi-a2', 'ORD_A', 2, '2026-11-02T08:00:00Z'); + const b1 = item('oi-b1', 'ORD_B', 3, '2026-11-02T09:00:00Z'); + const plan = planFinishedOutputAllocation([a1, a2, b1], 9); + // 余量 2 → A/B 各 +1;A 的两行再平均分 1 → 各 +0.5 + expect(plan.allocations.map((x) => [x.orderItemId, x.allocatedQty])).toEqual([ + ['oi-a1', 2.5], + ['oi-a2', 2.5], + ['oi-b1', 4], + ]); + }); + + it('无产出/无需求时返回空分配', () => { + expect(planFinishedOutputAllocation([a, b], 0).allocations.every((x) => x.allocatedQty === 0)).toBe(true); + expect(planFinishedOutputAllocation([], 5).allocations).toEqual([]); + }); +}); + +describe('阶段 2 开关:默认开启(kill switch)', () => { + it('未配置按默认开启;显式 enabled=false 才关闭', () => { + expect(parseProcessingFinishedNoInventoryConfig(null).enabled).toBe(true); + expect(parseProcessingFinishedNoInventoryConfig(undefined).enabled).toBe(true); + expect(parseProcessingFinishedNoInventoryConfig({ enabled: 'false' }).enabled).toBe(true); + expect(parseProcessingFinishedNoInventoryConfig({ enabled: true }).enabled).toBe(true); + expect(parseProcessingFinishedNoInventoryConfig({ enabled: false }).enabled).toBe(false); + expect(parseProcessingFinishedNoInventoryConfig(false).enabled).toBe(false); + }); +}); + +describe('阶段 2 原型边界(未接线,不得静默改库存/验收/订单状态)', () => { + const service = read('server/src/services/processingFinishedOutputService.ts'); + + it('免入库路线写履约覆盖并推进订单,不卡订单流程', () => { + expect(service).toContain('order_item_fulfillments'); + expect(service).toContain('stock_cover_qty'); + expect(service).toContain('tryAdvanceOrderToInspection'); + expect(service).toContain('maybeAdvanceOrderAfterFulfillment'); + expect(service).toContain('订单推进失败(不阻断回写)'); + }); + + it('不写库存/流水/成本账本', () => { + expect(service).not.toMatch(/INSERT\s+INTO\s+inventory\b/i); + expect(service).not.toMatch(/INSERT\s+INTO\s+inventory_logs\b/i); + expect(service).not.toMatch(/INSERT\s+INTO\s+cost_details\b/i); + }); + + it('不动验收单、不推订单状态', () => { + expect(service).not.toMatch(/DELETE\s+FROM\s+inspections/i); + expect(service).not.toMatch(/UPDATE\s+orders\s+SET\s+order_status/i); + expect(service).toContain('skipped'); + }); + + it('实收回写走唯一写入口', () => { + expect(service).toContain('writeOrderItemReceivedQty'); + expect(service).toContain('receivedStage'); + }); + + it('免入库条件 = 开关开 + 成品配置了原材料 BOM;未配置 BOM 仍走原待验流程', () => { + const demand = read('server/src/services/processingDemandSheetService.ts'); + expect(demand).toContain('isProcessingFinishedNoInventoryEnabled'); + expect(demand).toContain('hasProcessingBomForOutput'); + expect(demand).toContain('成品免入库,无需操作'); + // 没有 BOM 时仍走原 updatePurchaseOrderStatus(生成待验) + expect(demand).toContain('await updatePurchaseOrderStatus('); + }); + + it('加工单完工自动触发:需求单 + BOM + 开关开 → 分配回写并置完工', () => { + const task = read('server/src/services/processingTaskService.ts'); + expect(task).toContain("String(row.source_type || '') === 'demand'"); + expect(task).toContain('hasProcessingBomForOutput'); + expect(task).toContain('applyFinishedOutputAllocation'); + expect(task).toContain('PROCESS_STATUS.completed'); + expect(task).toContain('成品免入库回写失败'); + }); + + it('已回写任务不被成品验收重算降级', () => { + const demand = read('server/src/services/processingDemandSheetService.ts'); + expect(demand).toContain('finished_output_applied_at'); + expect(demand).toContain('completed: true'); + }); + + it('开关关闭时拒绝执行', () => { + expect(service).toContain('feature_disabled'); + expect(service).toContain('warehouse_processing_finished_no_inventory_enabled'); + }); + + it('重复调用幂等:同产出直接返回,产出变化才重算覆盖', () => { + expect(service).toContain('finished_output_applied_at'); + expect(service).toContain('finished_output_actual_qty'); + expect(service).toContain('alreadyApplied'); + expect(service).toContain('reapplied'); + expect(service).toContain("await client.query('ROLLBACK')"); + }); + + it('成本回写复用既有完工结算(不再自己写 unit_cost)', () => { + expect(service).toContain('settleDemandSheetCostOnCompletion'); + expect(service).toContain('perOrderQty'); + expect(service).not.toMatch(/UPDATE\s+order_items\s+SET\s+unit_cost/i); + const demand = read('server/src/services/processingDemandSheetService.ts'); + expect(demand).toContain('perOrderQty?:'); + // 默认口径不变:未传 perOrderQty 仍走成品验收 actual_qty + expect(demand).toContain('FROM inspections i'); + }); + + it('幂等标记迁移只加列,不新增业务表', () => { + const migration = read('migrations/20261108_processing_finished_output_apply.sql'); + expect(migration).toContain('finished_output_applied_at'); + expect(migration).toContain('finished_output_actual_qty'); + expect(migration).toContain('finished_output_plan'); + expect(migration).not.toContain('CREATE TABLE'); + }); +}); diff --git a/server/tests/processingRawMaterialPurchase.test.ts b/server/tests/processingRawMaterialPurchase.test.ts new file mode 100644 index 0000000..efb765b --- /dev/null +++ b/server/tests/processingRawMaterialPurchase.test.ts @@ -0,0 +1,309 @@ +/** + * 仓内加工原材料采购(阶段 1)契约测试 + * 设计:docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md + */ +import { readFileSync, existsSync } from 'node:fs'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { + estimateRawMaterialQty, + planRawMaterialPurchaseQty, + normalizeProcessingBom, + hasProcessingBomForOutput, +} from '../src/services/processingRawMaterialService'; +import { parseProcessingRawPurchaseConfig } from '../src/services/processingRawPurchaseConfigService'; + +const ROOT = path.join(__dirname, '../..'); +const read = (rel: string) => readFileSync(path.join(ROOT, rel), 'utf8'); + +describe('processing_bom 解析与损耗估算', () => { + it('只接受合法项,按加工方式去重(后者丢弃)', () => { + const entries = normalizeProcessingBom([ + { method: '去皮', material_sku: 'SKU_RAW', loss_rate: 0.11 }, + { method: '去皮', material_sku: 'SKU_OTHER', loss_rate: 0.2 }, + { method: '', material_sku: 'SKU_X', loss_rate: 0.1 }, + { method: '切丝', material_sku: '', loss_rate: 0.1 }, + { method: '切块', material_sku: 'SKU_Y', loss_rate: 1.2 }, + { method: '切丁', material_sku: 'SKU_Z', loss_rate: 0 }, + ]); + expect(entries).toEqual([ + { method: '去皮', material_sku: 'SKU_RAW', loss_rate: 0.11 }, + // method 为空 = 商品级通用原材料(2026-11-02 单原料改版) + { method: '', material_sku: 'SKU_X', loss_rate: 0.1 }, + { method: '切丁', material_sku: 'SKU_Z', loss_rate: 0 }, + ]); + }); + + it('非数组/脏数据返回空数组', () => { + expect(normalizeProcessingBom(null)).toEqual([]); + expect(normalizeProcessingBom('[]')).toEqual([]); + expect(normalizeProcessingBom([null, 1, 'x'])).toEqual([]); + }); + + it('下单后端硬校验仓内加工 BOM(防止接口/小程序绕过前端)', () => { + const submit = read('server/src/services/customerOrderSubmitService.ts'); + expect(submit).toContain('processing_bom_required'); + expect(submit).toContain('hasProcessingBomForOutput'); + expect(submit).toContain('请先在商品管理配置原材料后再下单'); + }); + + it('原料验收入库同步原料锚点状态(镜像自采路径按 purchase_code 回写)', () => { + const service = read('server/src/services/processingRawMaterialService.ts'); + expect(service).toContain('po.purchase_code = ANY($4::text[])'); + expect(service).toContain('r.purchase_status < 30'); + }); + + it('加工成品自采行成本只读,完工后占位单自动关闭', () => { + const finished = read('server/src/services/processingFinishedOutputService.ts'); + expect(finished).toContain('UPDATE purchase_orders'); + expect(finished).toContain('self_processed = true'); + expect(finished).toContain('purchase_status = 30'); + const web = read('src/pages/purchase/PurchaseManagement.tsx'); + expect(web).not.toContain('canZeroWarehouseDemandCost'); + expect(web).toContain('const canEditPurchaseFields = (purchase: PurchaseOrder) =>\n canCompletePurchase(purchase) || canAmendPurchaseActual(purchase);'); + }); + + it('需求单未领料不允许提交加工完工', () => { + const service = read('server/src/services/processingTaskService.ts'); + expect(service).toContain("source_type || '') === 'demand'"); + expect(service).toContain('material_not_picked'); + expect(service).toContain('请先领料后再提交加工完工'); + }); + + it('新订单不再复用已完工/待验收加工单', () => { + const service = read('server/src/services/processingDemandSheetService.ts'); + expect(service).toContain('只复用「未开始/加工中」需求单'); + expect(service).toContain('PROCESS_STATUS.pending'); + expect(service).toMatch(/process_status < \$5[\s\S]{0,200}30,/); + const migration = read('migrations/20261102_processing_demand_reuse_open_only.sql'); + expect(migration).toContain('process_status < 30'); + expect(migration).toContain('idx_processing_demand_sheet_key'); + }); + + it('生成原料采购不写「加工单…成品×…」备注', () => { + const service = read('server/src/services/processingRawMaterialService.ts'); + expect(service).not.toContain('原料预计 ${plannedQty}'); + expect(service).toContain('planRawMaterialPurchaseQty(demandQty, bomEntry.loss_rate)'); + expect(service).toContain('10, NULL, NULL)'); + }); + + it('BOM 读取:按方式 → 通用 method 为空 → 首条兜底(与 Web 同口径)', () => { + const service = read('server/src/services/processingRawMaterialService.ts'); + expect(service).toContain('entries.find((entry) => !entry.method)'); + // 2026-11-03 改判:旧实现的「恰好 1 条才兜底」已删,改为与 Web 一致的 entries[0] + expect(service).not.toContain('entries.length === 1 ? entries[0] : null'); + expect(service).toContain('entries[0] ||'); + // 加工方式为空不再直接判死 + expect(service).not.toContain('if (!sku || !procMethod) return null;'); + }); + + it('生成采购计划量向上取整为整数(不落 15.714 类小数)', () => { + expect(planRawMaterialPurchaseQty(11, 0.3)).toBe(15); // 11×1.3=14.3 → 15 + expect(planRawMaterialPurchaseQty(7.8, 0)).toBe(8); + expect(planRawMaterialPurchaseQty(5, 0)).toBe(5); + expect(planRawMaterialPurchaseQty(0, 0.3)).toBe(0); + }); + + it('损耗率按成品比例估算数量(原料 = 成品 × (1+损耗率))', () => { + expect(estimateRawMaterialQty(32, 0.11)).toBe(35.52); // 32 × 1.11 + expect(estimateRawMaterialQty(32, 0)).toBe(32); + expect(estimateRawMaterialQty(0, 0.2)).toBe(0); + // 极端损耗上限 95%,避免除零 + expect(estimateRawMaterialQty(1, 2)).toBe(1.95); // 损耗上限 95% + }); +}); + +describe('自动采购开关', () => { + it('默认开启,只有显式 enabled=false 才关闭', () => { + expect(parseProcessingRawPurchaseConfig(null).enabled).toBe(true); + expect(parseProcessingRawPurchaseConfig(undefined).enabled).toBe(true); + expect(parseProcessingRawPurchaseConfig(true).enabled).toBe(true); + expect(parseProcessingRawPurchaseConfig({ enabled: true }).enabled).toBe(true); + expect(parseProcessingRawPurchaseConfig({ enabled: false }).enabled).toBe(false); + expect(parseProcessingRawPurchaseConfig({ enabled: 'false' }).enabled).toBe(true); + }); + + it('同步时按分公司开关跳过(关闭时不建/不改草稿)', () => { + const service = read('server/src/services/processingRawMaterialService.ts'); + expect(service).toContain('isProcessingRawPurchaseEnabled'); + expect(service).toContain("if (!(await isEnabledForBranch(branchCode))) continue;"); + }); +}); + +describe('迁移与租户名单', () => { + const migration = read('migrations/20261107_processing_raw_material_purchase.sql'); + + it('新增 processing_bom 列与 processing_raw_purchases 表并登记 tenant_business_tables', () => { + expect(migration).toContain('processing_bom JSONB'); + expect(migration).toContain('processing_raw_purchases'); + expect(migration).toContain('tenant_business_tables()'); + expect(migration).toMatch(/processing_raw_purchases.*tenant_business_tables|tenant_business_tables.*processing_raw_purchases/s); + }); + + it('原料采购唯一键按 加工单 + 原料', () => { + expect(migration).toContain('UNIQUE (demand_task_id, material_sku)'); + }); +}); + +describe('同步/提交/回写规则(源码契约)', () => { + const service = read('server/src/services/processingRawMaterialService.ts'); + + it('只自动改待采购(10),已提交/已入库只标提示', () => { + expect(service).toContain('if (Number(row.purchase_status) === 10)'); + expect(service).toContain('请人工确认'); + expect(service).toContain('需求已变化'); + }); + + it('提交采购走独立入库待验单(正常入库流程)', () => { + expect(service).toContain('createIndependentInboundInspection'); + expect(service).toContain("purchase_status = 20"); + expect(service).toContain('purchase_status = $5'); + }); + + it('成本价 0 守卫:未开允许 0 开关时拒绝', () => { + expect(service).toContain('isZeroSupplyCostAllowed'); + expect(service).toContain('成本价须大于 0(除非开启允许成本为 0)'); + }); + + it('已采购待入库(20):未验收前 Web 可改数量/成本,并同步待验单', () => { + expect(service).toContain('status !== 10 && status !== 20'); + expect(service).toContain('原料已验收入库,不能再修改'); + expect(service).toContain('UPDATE inspections'); + expect(service).toContain('prepare_qty = $2::numeric'); + expect(service).toContain('purchase_price = $3::numeric'); + }); + + it('取消仓内加工:未入库的原料采购取消;已入库按独立入库保留', () => { + expect(service).toContain('取消仓内加工,原料采购取消(未入库)'); + expect(service).toContain('原料已入库,按独立入库保留'); + expect(service).toContain('DELETE FROM inspections'); + expect(service).toContain('purchase_status = 40'); + }); + + it('需求单同步后挂钩,但不阻断订单', () => { + const demand = read('server/src/services/processingDemandSheetService.ts'); + expect(demand).toContain('syncRawMaterialPurchasesForDemandTasksSafely'); + expect(demand).toContain('不阻断订单'); + }); + + it('验收完成后回写原料采购已入库', () => { + const inspection = read('server/src/services/inspectionComplianceService.ts'); + expect(inspection).toContain('syncProcessingRawPurchaseInboundFromInspection'); + }); + + it('不再暴露独立原料采购列表/编辑/提交接口;仅保留 BOM 变更同步入口', () => { + const routes = read('server/src/modules/workflow/routes/purchaseRoutes.ts'); + expect(routes).not.toContain("router.get('/purchase-orders/processing-raw-materials'"); + expect(routes).not.toContain("router.patch('/purchase-orders/processing-raw-materials/:id'"); + expect(routes).not.toContain("router.post('/purchase-orders/processing-raw-materials/:id/submit'"); + expect(routes).toContain('/purchase-orders/processing-raw-materials/sync'); + }); + + it('仓内加工成品不生成待验;原材料独立入库待验才是入库列表来源', () => { + const prep = read('server/src/services/preparationFulfillmentService.ts'); + expect(prep).toContain('requiresWarehouseProcessing(item.processing_method, item.processing_owner)'); + expect(prep).toContain('DELETE FROM inspections i'); + expect(prep).toContain("TRIM(COALESCE(oi.processing_owner, '')) = 'warehouse'"); + expect(prep).toContain("TRIM(oi.processing_method) <> '原材料'"); + const migration = read('migrations/20261111_processing_finished_pending_inspection_cleanup.sql'); + expect(migration).toContain('inspection_time IS NULL'); + expect(migration).toContain("processing_owner, ''"); + }); + + it('仓内加工成品占位自采单不生成待验', () => { + const inspection = read('server/src/services/inspectionComplianceService.ts'); + expect(inspection).toContain('self_processed'); + expect(inspection).toContain('if (Boolean(po.self_processed)) return;'); + }); + + it('原料采购完成的待验是独立入库(入库列表可见)', () => { + const inspection = read('server/src/services/inspectionComplianceService.ts'); + expect(inspection).toContain("'processing_raw_material'"); + expect(inspection).toContain('independent_inbound'); + const migration = read('migrations/20261112_processing_raw_inspection_visibility.sql'); + expect(migration).toContain('independent_inbound'); + expect(migration).toContain('processing_raw_material'); + }); + + it('加工原料镜像到 purchase_orders,小程序/Web 共用自采列表', () => { + const service = read('server/src/services/processingRawMaterialService.ts'); + expect(service).toContain('upsertRawPurchaseOrderMirror'); + expect(service).toContain("'processing_raw_material'"); + expect(service).toContain('INSERT INTO purchase_orders'); + expect(service).toContain('syncProcessingRawPurchaseFromPurchaseOrder'); + expect(read('server/src/services/purchaseOperationService.ts')).toContain( + 'syncProcessingRawPurchaseFromPurchaseOrder' + ); + const migration = read('migrations/20261110_processing_raw_purchase_mirror.sql'); + expect(migration).toContain('processing_raw_material'); + expect(migration).toContain('CEIL(planned_qty)'); + }); + + it('BOM 保存后可同步未完工加工单', () => { + expect(service).toContain('syncRawMaterialPurchasesForOutputSku'); + expect(service).toContain("pt.source_type = 'demand'"); + expect(service).toContain('COALESCE(pt.process_status, 0) < 40'); + }); + + it('加工单删除前保护已提交/已入库的原料采购', () => { + const demand = read('server/src/services/processingDemandSheetService.ts'); + expect(demand).toContain('processing_raw_purchases'); + expect(demand).toContain('purchase_status >= 20'); + }); + + it('待验独立入库被退回时原料采购回到待采购', () => { + const spi = read('server/src/services/selfPurchaseStockInboundService.ts'); + expect(spi).toContain('processing_raw_purchases'); + expect(spi).toContain('purchase_status = 10'); + }); +}); + +describe('设计文档存在', () => { + it('阶段 1/2 设计与验收标准落地', () => { + const doc = path.join(ROOT, 'docs/design/20261102-warehouse-processing-raw-material-auto-purchase.md'); + expect(existsSync(doc)).toBe(true); + const text = readFileSync(doc, 'utf8'); + expect(text).toContain('阶段 1'); + expect(text).toContain('阶段 2'); + }); +}); + +/** + * BOM 命中口径与 Web 对齐(2026-11-03): + * 旧实现要求加工方式非空、且只有「恰好 1 条」才兜底首条 ⇒ 小程序判 has_bom=false 退回旧界面, + * 而 Web 弹窗用 `按方式 → 空方式通用 → entries[0]` 三条序,两边看到的不一样。 + */ +describe('BOM 命中口径与 Web 对齐', () => { + const fakeDb = (processingBom: unknown) => + ({ + query: async () => ({ rows: [{ processing_bom: processingBom }] }), + }) as any; + + it('加工方式为空但商品配了 BOM ⇒ 仍命中(旧实现直接返回 false)', async () => { + const db = fakeDb([{ method: '去皮', material_sku: 'SKU_RAW', loss_rate: 0.1 }]); + expect(await hasProcessingBomForOutput(db, 'BR002', 'SKU_OUT', '')).toBe(true); + }); + + it('多条 BOM 且都不匹配加工方式 ⇒ 取首条(与 Web 的 entries[0] 一致)', async () => { + const db = fakeDb([ + { method: '去皮', material_sku: 'SKU_A', loss_rate: 0.1 }, + { method: '切丝', material_sku: 'SKU_B', loss_rate: 0.2 }, + ]); + expect(await hasProcessingBomForOutput(db, 'BR002', 'SKU_OUT', '切块')).toBe(true); + }); + + it('空方式条目优先于首条', async () => { + const db = fakeDb([ + { method: '去皮', material_sku: 'SKU_A', loss_rate: 0.1 }, + { method: '', material_sku: 'SKU_COMMON', loss_rate: 0.05 }, + ]); + const entry = await hasProcessingBomForOutput(db, 'BR002', 'SKU_OUT', '切块'); + expect(entry).toBe(true); + }); + + it('成品 SKU 为空或 BOM 为空 ⇒ false(不放宽到「什么都没有也算有」)', async () => { + expect(await hasProcessingBomForOutput(fakeDb([]), 'BR002', '', '去皮')).toBe(false); + expect(await hasProcessingBomForOutput(fakeDb([]), 'BR002', 'SKU_OUT', '去皮')).toBe(false); + expect(await hasProcessingBomForOutput(fakeDb(null), 'BR002', 'SKU_OUT', '去皮')).toBe(false); + }); +}); diff --git a/src/components/order/ProcessingBomSetupModal.tsx b/src/components/order/ProcessingBomSetupModal.tsx new file mode 100644 index 0000000..c8ce8a8 --- /dev/null +++ b/src/components/order/ProcessingBomSetupModal.tsx @@ -0,0 +1,330 @@ +/** + * 仓内加工原材料配置弹窗(录单/订单详情内联设置) + * + * 场景:订单行选了仓内加工,但商品未配置该加工方式的原材料 BOM。 + * 不跳商品管理,直接在当前页弹窗里设置原材料 + 损耗率,保存后继续原保存流程。 + */ +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useT } from '../../i18n'; +import { DialogOverlay } from '../ui/DialogOverlay'; +import { SearchableSelect, type SearchableSelectOption } from '../ui/SearchableSelect'; +import { DecimalInput } from '../ui/DecimalInput'; +import { supabase } from '../../supabase/client'; +import { notify } from '../../utils/notify'; +import { useCategoryRows } from '../../hooks/useCategoryRows'; +import { createCatalogProductForOrderLine } from '../../utils/productCatalog'; +import { QuickCreateProductModal, type QuickCreateProductConfirm } from './QuickCreateProductModal'; +import { + loadProductProcessingBom, + saveProductProcessingBom, + type ProcessingBomEntry, + type ProcessingBomSetupTarget, +} from '../../utils/processingBom'; + +export interface ProcessingBomSetupModalProps { + open: boolean; + branchCode: string | null; + targets: ProcessingBomSetupTarget[]; + onClose: () => void; + /** 全部目标保存成功后调用;调用方随后重试原保存动作 */ + onSaved: () => void; +} + +type DraftRow = { + target: ProcessingBomSetupTarget; + existing: ProcessingBomEntry[]; + materialSku: string; + lossPercent: number; +}; + +export function ProcessingBomSetupModal({ + open, + branchCode, + targets, + onClose, + onSaved, +}: ProcessingBomSetupModalProps) { + const t = useT(); + const [rows, setRows] = useState([]); + const [options, setOptions] = useState([]); + const [loading, setLoading] = useState(false); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const [rawCreateRowIndex, setRawCreateRowIndex] = useState(null); + const [rawCreateInitialName, setRawCreateInitialName] = useState(''); + const [rawCreating, setRawCreating] = useState(false); + const [rawCreateError, setRawCreateError] = useState(''); + const { categoryOptions } = useCategoryRows({ enabledOnly: true }); + + const targetKey = useMemo( + () => + targets + .map((item) => `${item.skuCode}::${item.processingMethod}`) + .sort() + .join('|'), + [targets] + ); + + useEffect(() => { + if (!open) return; + let cancelled = false; + setLoading(true); + setError(null); + (async () => { + try { + const bomMap = await loadProductProcessingBom( + targets.map((item) => item.skuCode), + branchCode + ); + let productQuery = supabase + .from('product_catalog') + .select('code,name,unit,branch_code') + .eq('item_type', 'product') + .order('name') + .limit(1000); + if (branchCode) productQuery = productQuery.eq('branch_code', branchCode); + const { data, error: optionsError } = await productQuery; + if (optionsError) throw optionsError; + if (cancelled) return; + setOptions( + (data || []) + .filter((row: any) => String(row.code || '').trim()) + .map((row: any) => ({ + value: String(row.code || ''), + label: `${String(row.name || row.code || '')}${row.unit ? `(${row.unit})` : ''}`, + searchText: String(row.code || ''), + })) + ); + setRows( + targets.map((target) => { + const existing = bomMap.get(target.skuCode) || []; + const current = + existing.find( + (entry) => entry.method.toLowerCase() === target.processingMethod.toLowerCase() + ) || existing.find((entry) => !entry.method) || existing[0]; + return { + target, + existing, + materialSku: current?.material_sku || '', + lossPercent: current ? Math.round(Number(current.loss_rate || 0) * 10000) / 100 : 0, + }; + }) + ); + } catch (err: any) { + if (!cancelled) setError(err?.message || t('orders.processingBomSetup.loadFail')); + } finally { + if (!cancelled) setLoading(false); + } + })(); + return () => { + cancelled = true; + }; + // targetKey 用于目标集合变化时重载;targets 数组引用变化不需要重复请求 + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open, targetKey, branchCode, t]); + + const updateRow = useCallback((index: number, patch: Partial) => { + setRows((prev) => prev.map((row, i) => (i === index ? { ...row, ...patch } : row))); + setError(null); + }, []); + + const openRawMaterialCreate = (index: number, name: string) => { + setRawCreateRowIndex(index); + setRawCreateInitialName(String(name || '').trim()); + setRawCreateError(''); + }; + + const handleCreateRawMaterial = async (payload: QuickCreateProductConfirm) => { + if (rawCreating || rawCreateRowIndex == null) return; + if (!payload.name.trim()) { + setRawCreateError(t('products.form.err.skuNameRequired')); + return; + } + if (!payload.categoryCode) { + setRawCreateError(t('products.form.err.categoryRequired')); + return; + } + setRawCreating(true); + setRawCreateError(''); + try { + const created = await createCatalogProductForOrderLine({ + name: payload.name, + categoryCode: payload.categoryCode, + unit: payload.unit || '斤', + salePrice: payload.salePrice, + costPrice: payload.costPrice, + }); + const label = `${created.name || payload.name}${payload.unit ? `(${payload.unit})` : ''}`; + setOptions((prev) => + prev.some((opt) => opt.value === created.skuCode) + ? prev + : [...prev, { value: created.skuCode, label, searchText: created.skuCode }] + ); + setRows((prev) => + prev.map((row, index) => + index === rawCreateRowIndex + ? { ...row, materialSku: created.skuCode } + : row + ) + ); + setRawCreateRowIndex(null); + notify.success(t('products.toast.createOk')); + } catch (err: any) { + setRawCreateError(err?.message || t('products.toast.saveFail')); + } finally { + setRawCreating(false); + } + }; + + const handleSave = async () => { + if (saving) return; + for (const row of rows) { + if (!row.materialSku.trim()) { + setError(t('orders.processingBomSetup.errMaterial')); + return; + } + if (!Number.isFinite(row.lossPercent) || row.lossPercent < 0 || row.lossPercent > 95) { + setError(t('orders.processingBomSetup.errLoss')); + return; + } + if (row.materialSku.trim() === row.target.skuCode.trim()) { + setError(t('orders.processingBomSetup.errSelf')); + return; + } + } + setSaving(true); + setError(null); + try { + for (const row of rows) { + await saveProductProcessingBom({ + skuCode: row.target.skuCode, + branchCode, + existing: row.existing, + entry: { + method: row.target.processingMethod, + material_sku: row.materialSku.trim(), + loss_rate: Math.round(Number(row.lossPercent) * 100) / 10000, + }, + }); + } + notify.success(t('orders.processingBomSetup.saved')); + onSaved(); + } catch (err: any) { + setError(err?.message || t('orders.processingBomSetup.saveFail')); + } finally { + setSaving(false); + } + }; + + if (!open) return null; + + return ( + <> + +
+
+

{t('orders.processingBomSetup.title')}

+ +
+
+

+ {t('orders.processingBomSetup.hint')} +

+ {loading ?

{t('common.loading')}

: null} + {!loading && + rows.map((row, index) => ( +
+
+ {row.target.skuName || row.target.skuCode} +
+
+
+ + updateRow(index, { materialSku: value })} + placeholder={t('orders.processingBomSetup.materialPh')} + emptyLabel={t('orders.processingBomSetup.materialPh')} + allowCreateFromQuery + alwaysShowCreate + createEmptyLabel={t('products.form.processingBomCreateMaterial')} + createFromQueryLabel={(name) => + name.trim() + ? t('products.form.processingBomCreateMaterialNamed', { name }) + : t('products.form.processingBomCreateMaterial') + } + onCreateFromQuery={(name) => openRawMaterialCreate(index, name)} + /> +
+
+ +
+ updateRow(index, { lossPercent: value })} + className="app-input w-full rounded-lg border border-slate-300 px-2 py-1.5 text-sm dark:border-slate-600" + /> + % +
+
+
+
+ ))} + {error ?

{error}

: null} +
+
+ + +
+
+
+ { + if (rawCreating) return; + setRawCreateRowIndex(null); + setRawCreateError(''); + }} + onConfirm={(payload) => void handleCreateRawMaterial(payload)} + /> + + ); +} diff --git a/src/i18n/locales/en/orders.ts b/src/i18n/locales/en/orders.ts index 1529df3..e20d51d 100644 --- a/src/i18n/locales/en/orders.ts +++ b/src/i18n/locales/en/orders.ts @@ -722,4 +722,16 @@ export const orders: MessageDict = { 'priceQty.submitFailed': '{count} failed to submit', 'priceQty.disabled': 'This feature is not enabled yet', 'priceQty.filterAll': 'All', + 'processingBomSetup.title': 'Set processing raw material', + 'processingBomSetup.hint': 'Select the raw material and loss rate for this in-house processing method; changes apply after saving.', + 'processingBomSetup.material': 'Raw material', + 'processingBomSetup.materialPh': 'Select raw material', + 'processingBomSetup.loss': 'Loss rate', + 'processingBomSetup.save': 'Save', + 'processingBomSetup.saved': 'Processing raw material saved', + 'processingBomSetup.loadFail': 'Failed to load processing raw material', + 'processingBomSetup.saveFail': 'Failed to save processing raw material', + 'processingBomSetup.errMaterial': 'Please select a raw material', + 'processingBomSetup.errLoss': 'Loss rate must be between 0 and 95', + 'processingBomSetup.errSelf': 'Raw material cannot be the product itself', }; diff --git a/src/i18n/locales/en/processing.ts b/src/i18n/locales/en/processing.ts index e26c4dd..8847bde 100644 --- a/src/i18n/locales/en/processing.ts +++ b/src/i18n/locales/en/processing.ts @@ -168,4 +168,16 @@ export const processing: MessageDict = { 'toast.noBranch': 'This account is not bound to a branch', 'toast.dropImage': 'Drop a JPG, PNG, or WEBP image', 'toast.unsupportedAction': 'This page does not support action {action}', + 'historyDelete.title': 'Delete completed processing task', + 'historyDelete.confirm': 'Order {order} is completed. Delete residual task {code}?', + 'historyDelete.ok': 'Completed task deleted', + 'historyDelete.fail': 'Delete failed', + 'modal.pickOutputQty': 'Processed output (net weight)', + 'modal.outputAllocationTitle': 'Customer allocation (total {output})', + 'modal.outputAllocationLoading': 'Calculating allocation…', + 'toast.needPickOutputQty': 'Enter processed output quantity', + 'toast.outputPreviewFail': 'Failed to load allocation preview', + 'toast.outputAllocationNotReady': 'Allocation is not ready yet', + 'toast.outputAllocationMismatch': 'Allocation total must equal processed output', + 'toast.pickOutputExceeds': 'Processed output cannot exceed picked quantity', }; diff --git a/src/i18n/locales/id/orders.ts b/src/i18n/locales/id/orders.ts index e1bf92c..66e8622 100644 --- a/src/i18n/locales/id/orders.ts +++ b/src/i18n/locales/id/orders.ts @@ -723,4 +723,16 @@ export const orders: MessageDict = { 'priceQty.submitFailed': '{count} gagal dikirim', 'priceQty.disabled': 'Fitur ini belum diaktifkan', 'priceQty.filterAll': 'Semua', + 'processingBomSetup.title': 'Atur bahan baku proses', + 'processingBomSetup.hint': 'Pilih bahan baku dan tingkat susut untuk metode proses ini; berlaku setelah disimpan.', + 'processingBomSetup.material': 'Bahan baku', + 'processingBomSetup.materialPh': 'Pilih bahan baku', + 'processingBomSetup.loss': 'Tingkat susut', + 'processingBomSetup.save': 'Simpan', + 'processingBomSetup.saved': 'Bahan baku proses tersimpan', + 'processingBomSetup.loadFail': 'Gagal memuat bahan baku proses', + 'processingBomSetup.saveFail': 'Gagal menyimpan bahan baku proses', + 'processingBomSetup.errMaterial': 'Pilih bahan baku', + 'processingBomSetup.errLoss': 'Tingkat susut harus 0-95', + 'processingBomSetup.errSelf': 'Bahan baku tidak boleh produk itu sendiri', }; diff --git a/src/i18n/locales/id/processing.ts b/src/i18n/locales/id/processing.ts index 9c24f34..7102809 100644 --- a/src/i18n/locales/id/processing.ts +++ b/src/i18n/locales/id/processing.ts @@ -168,4 +168,16 @@ export const processing: MessageDict = { 'toast.noBranch': 'Akun ini tidak terikat cabang', 'toast.dropImage': 'Seret gambar JPG, PNG, atau WEBP', 'toast.unsupportedAction': 'Halaman ini tidak mendukung aksi {action}', + 'historyDelete.title': 'Hapus tugas proses selesai', + 'historyDelete.confirm': 'Pesanan {order} selesai. Hapus tugas sisa {code}?', + 'historyDelete.ok': 'Tugas selesai dihapus', + 'historyDelete.fail': 'Gagal menghapus', + 'modal.pickOutputQty': 'Hasil proses (berat bersih)', + 'modal.outputAllocationTitle': 'Alokasi pelanggan (total {output})', + 'modal.outputAllocationLoading': 'Menghitung alokasi…', + 'toast.needPickOutputQty': 'Isi hasil proses', + 'toast.outputPreviewFail': 'Gagal memuat pratinjau alokasi', + 'toast.outputAllocationNotReady': 'Alokasi belum siap', + 'toast.outputAllocationMismatch': 'Total alokasi harus sama dengan hasil proses', + 'toast.pickOutputExceeds': 'Hasil proses tidak boleh melebihi jumlah pengambilan', }; diff --git a/src/i18n/locales/zh-CN/orders.ts b/src/i18n/locales/zh-CN/orders.ts index c1fcefa..9f0dc7b 100644 --- a/src/i18n/locales/zh-CN/orders.ts +++ b/src/i18n/locales/zh-CN/orders.ts @@ -716,4 +716,16 @@ export const orders: MessageDict = { 'priceQty.submitFailed': '{count} 项提交失败', 'priceQty.disabled': '该功能暂未开启', 'priceQty.filterAll': '全部', + 'processingBomSetup.title': '设置加工原材料', + 'processingBomSetup.hint': '该商品选择了仓内加工;请选择该加工方式所需的原材料与损耗率,保存后生效(不需要跳转商品管理)。', + 'processingBomSetup.material': '原材料商品', + 'processingBomSetup.materialPh': '选择原材料商品', + 'processingBomSetup.loss': '损耗率', + 'processingBomSetup.save': '保存', + 'processingBomSetup.saved': '已保存加工原料配置', + 'processingBomSetup.loadFail': '加载加工原料配置失败', + 'processingBomSetup.saveFail': '保存加工原料配置失败', + 'processingBomSetup.errMaterial': '请选择原材料商品', + 'processingBomSetup.errLoss': '损耗率须在 0-95 之间', + 'processingBomSetup.errSelf': '原材料不能是成品自身', }; diff --git a/src/i18n/locales/zh-CN/processing.ts b/src/i18n/locales/zh-CN/processing.ts index 5c821b7..fd3cac5 100644 --- a/src/i18n/locales/zh-CN/processing.ts +++ b/src/i18n/locales/zh-CN/processing.ts @@ -168,4 +168,16 @@ export const processing: MessageDict = { 'toast.noBranch': '当前账号未绑定分公司', 'toast.dropImage': '请拖拽 JPG、PNG 或 WEBP 图片', 'toast.unsupportedAction': '当前页不支持操作 {action}', + 'historyDelete.title': '删除历史加工单', + 'historyDelete.confirm': '订单 {order} 已完结,确定删除残留加工单 {code} 吗?', + 'historyDelete.ok': '已删除历史加工单', + 'historyDelete.fail': '删除失败', + 'modal.pickOutputQty': '加工产出数量(成品净重)', + 'modal.outputAllocationTitle': '客户分配(合计 {output})', + 'modal.outputAllocationLoading': '正在计算客户分配…', + 'toast.needPickOutputQty': '请填写加工产出数量', + 'toast.outputPreviewFail': '加载客户分配预览失败', + 'toast.outputAllocationNotReady': '客户分配还未加载完成,请稍后再试', + 'toast.outputAllocationMismatch': '客户分配合计必须等于加工产出数量', + 'toast.pickOutputExceeds': '加工产出数量不能大于领料数量', }; diff --git a/src/pages/inspection/ProcessingManagement.tsx b/src/pages/inspection/ProcessingManagement.tsx index b05e15b..1ac58b7 100644 --- a/src/pages/inspection/ProcessingManagement.tsx +++ b/src/pages/inspection/ProcessingManagement.tsx @@ -17,8 +17,8 @@ import { notify } from '../../utils/notify'; import { requestNavBadgeRefresh } from '../../hooks/useNavBadgeCounts'; import { isNavPendingIntent, - NAV_DAYS_QUERY, NAV_PENDING_QUERY, + NAV_DAYS_QUERY, navPendingRange, } from '../../utils/navPendingIntent'; import { supabase } from '../../supabase/client'; @@ -41,9 +41,13 @@ import { useFileDropUpload } from '../../hooks/useFileDropUpload'; import { PROCESS_STATUS } from '../../utils/processingTasks'; import { completeProcessingWorkApi, + previewFinishedOutputAllocationApi, + type FinishedOutputAllocationPreview, createStandaloneProcessingTaskApi, completeStandaloneProcessingTaskApi, deleteStandaloneProcessingTaskApi, + deleteCompletedOrderProcessingTaskApi, + deleteHistoricalDemandSheetApi, listStandaloneLinesApi, pickDemandSheetMaterialApi, amendDemandSheetMaterialQtyApi, @@ -61,6 +65,7 @@ import { import { DecimalTextInput } from '../../components/ui/DecimalInput'; import { QuickCreateProductModal, type QuickCreateProductConfirm } from '../../components/order/QuickCreateProductModal'; import { createCatalogProductForOrderLine } from '../../utils/productCatalog'; +import { loadProductProcessingBom } from '../../utils/processingBom'; import { useCategoryRows } from '../../hooks/useCategoryRows'; import type { DateRangeValue } from '../../components/ui/DateRangeFilterButton'; import { resolveOrderDateRange, type OrderDateField, type OrderDatePreset } from '../../components/ui/OrderDateFilter'; @@ -223,10 +228,10 @@ export const ProcessingManagement: React.FC = () => { ); const [dateField, setDateField] = useState('created_at'); const [datePreset, setDatePreset] = useState(() => - navPendingIntent ? 'custom' : 'today' + isNavPendingIntent(searchParams) ? 'custom' : 'today' ); const [dateRange, setDateRange] = useState(() => - navPendingIntent ? navPendingRange(searchParams) : null + isNavPendingIntent(searchParams) ? navPendingRange(searchParams) : null ); const [workflowEnabled, setWorkflowEnabled] = useState(true); const [loadingWorkflow, setLoadingWorkflow] = useState(false); @@ -237,14 +242,13 @@ export const ProcessingManagement: React.FC = () => { useEffect(() => { if (!navPendingIntent) return; + // 从带角标菜单进入:直接展示全部待处理(工作 Tab + 全部日期) setDatePreset('custom'); setDateRange(navPendingRange(searchParams)); - setSearchParams((prev: URLSearchParams) => { - const next = new URLSearchParams(prev); - next.delete(NAV_PENDING_QUERY); - next.delete(NAV_DAYS_QUERY); - return next; - }, { replace: true }); + const next = new URLSearchParams(searchParams); + next.delete(NAV_PENDING_QUERY); + next.delete(NAV_DAYS_QUERY); + setSearchParams(next, { replace: true }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [navPendingIntent]); const [selectedTask, setSelectedTask] = useState(null); @@ -263,6 +267,11 @@ export const ProcessingManagement: React.FC = () => { // 幂等键:打开弹窗时生成,本次会话内重试/双击复用 requestId: '', }); + const [pickOutputQty, setPickOutputQty] = useState(''); + const [pickHasBom, setPickHasBom] = useState(false); + const [pickOutputPreview, setPickOutputPreview] = useState(null); + const [pickOutputAllocationDrafts, setPickOutputAllocationDrafts] = useState>({}); + const [pickOutputPreviewLoading, setPickOutputPreviewLoading] = useState(false); const [saving, setSaving] = useState(false); const [workForm, setWorkForm] = useState({ grossWeight: '', netWeight: '', processFee: '', remark: '' }); const [createForm, setCreateForm] = useState({ @@ -682,7 +691,7 @@ export const ProcessingManagement: React.FC = () => { if (!outputTask) return; const outputs = outputRows.filter((row) => Number(row.qty) > 0); if (!outputs.length) { - notify(t('processing.toast.needOutputQty')); + notify(t('processing.toast.needPickOutputQty')); return; } const totalOut = outputs.reduce((sum, row) => sum + Number(row.qty), 0); @@ -738,6 +747,48 @@ export const ProcessingManagement: React.FC = () => { } }; + /** 删除订单已完结后残留的加工单(仅管理员;后端只允许待加工/加工中) */ + const handleDeleteHistoricalOrderTask = async (task: TaskView) => { + const ok = await confirmDialog({ + title: t('processing.historyDelete.title'), + message: t('processing.historyDelete.confirm', { + code: task.task_code || task.order_code || '', + order: task.order_code || '', + }), + confirmText: t('common.delete'), + danger: true, + }); + if (!ok) return; + try { + await deleteCompletedOrderProcessingTaskApi(task.id); + notify.success(t('processing.historyDelete.ok')); + fetchTasks(); + } catch (error: any) { + notify(error?.message || t('processing.historyDelete.fail')); + } + }; + + /** 删除关联订单已完结的历史残留仓内需求单(仅管理员) */ + const handleDeleteHistoricalDemand = async (task: TaskView) => { + const ok = await confirmDialog({ + title: t('processing.historyDelete.title'), + message: t('processing.historyDelete.confirm', { + code: task.task_code || '', + order: task.order_code || '', + }), + confirmText: t('common.delete'), + danger: true, + }); + if (!ok) return; + try { + await deleteHistoricalDemandSheetApi(task.id); + notify.success(t('processing.historyDelete.ok')); + fetchTasks(); + } catch (error: any) { + notify(error?.message || t('processing.historyDelete.fail')); + } + }; + /** 成品新增商品:先加载分类(复用快速新建商品的分类下拉) */ const openOutputProductModal = () => { setOutputProductError(''); @@ -766,7 +817,6 @@ export const ProcessingManagement: React.FC = () => { unit: payload.unit || '斤', salePrice: payload.salePrice, costPrice: payload.costPrice, - spec: payload.spec, }); addOutputRow({ sku_code: created.skuCode, @@ -797,36 +847,178 @@ export const ProcessingManagement: React.FC = () => { : `pick-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`, }); setSkuOptions([]); - void fetchSkuOptions('', task.id); + setPickOutputQty(''); + setPickHasBom(false); + setPickOutputPreview(null); + setPickOutputAllocationDrafts({}); + setPickOutputPreviewLoading(false); + void (async () => { + try { + const bomMap = await loadProductProcessingBom( + [String(task.sku_code || '').trim()], + effectiveBranchCode + ); + const entries = bomMap.get(String(task.sku_code || '').trim()) || []; + const method = String(task.processing_method || '').trim(); + const bom = + entries.find((entry) => entry.method.toLowerCase() === method.toLowerCase()) || + entries.find((entry) => !entry.method) || + entries[0]; + if (!bom) { + await fetchSkuOptions('', task.id); + return; + } + setPickHasBom(true); + setPickOutputQty( + Number(task.source_qty) > 0 ? String(Number(task.source_qty)) : '' + ); + const res = await listStandaloneProcessingSkuOptionsApi( + bom.material_sku, + 20, + task.id + ); + const options = res.data || []; + setSkuOptions(options); + const selected = + options.find((opt) => opt.sku_code === bom.material_sku) || options[0] || null; + if (!selected) return; + const loss = Math.min(Math.max(Number(bom.loss_rate) || 0, 0), 0.95); + const sourceQty = Number(task.source_qty) || 0; + const expectedTotal = + sourceQty > 0 ? Math.max(1, Math.ceil(sourceQty * (1 + loss) - 1e-9)) : 0; + const existingMaterialQty = Number(task.material_qty) || 0; + const expectedPick = Math.max(0, expectedTotal - existingMaterialQty); + setPickForm((prev) => ({ + ...prev, + selectedSku: selected, + skuSearch: selected.sku_name, + qty: expectedPick > 0 ? String(expectedPick) : '', + })); + } catch (error) { + console.warn('自动带出加工原材料失败', error); + await fetchSkuOptions('', task.id); + } + })(); }; + // 加工产出输入后:预演各订单客户可分到的数量,供人工调整 + useEffect(() => { + if (!pickTask || !pickHasBom) { + setPickOutputPreview(null); + setPickOutputAllocationDrafts({}); + return; + } + const actualQty = Number(pickOutputQty); + if (!Number.isFinite(actualQty) || actualQty <= 0) { + setPickOutputPreview(null); + setPickOutputAllocationDrafts({}); + return; + } + let alive = true; + setPickOutputPreviewLoading(true); + const timer = window.setTimeout(() => { + void previewFinishedOutputAllocationApi(pickTask.id, actualQty) + .then((res) => { + if (!alive) return; + setPickOutputPreview(res.data); + const drafts: Record = {}; + for (const row of res.data.plan.allocations) { + drafts[row.orderItemId] = String(row.allocatedQty); + } + setPickOutputAllocationDrafts(drafts); + }) + .catch((error: any) => { + if (!alive) return; + setPickOutputPreview(null); + notify(error?.message || t('processing.toast.outputPreviewFail')); + }) + .finally(() => { + if (alive) setPickOutputPreviewLoading(false); + }); + }, 250); + return () => { + alive = false; + window.clearTimeout(timer); + }; + }, [pickTask, pickHasBom, pickOutputQty, t]); + const handlePickDemand = async () => { if (!pickTask) return; if (!pickForm.selectedSku) { notify(t('processing.toast.needStockSku')); return; } - const qty = Number(pickForm.qty); - if (!Number.isFinite(qty) || qty <= 0) { + const existingMaterialQty = Number(pickTask.material_qty) || 0; + const qty = pickForm.qty.trim() === '' ? 0 : Number(pickForm.qty); + if (!Number.isFinite(qty) || qty < 0) { notify(t('processing.toast.needPickQty')); return; } + // 已有领料的在制单:允许不再追加领料,直接填加工产出并完工 + if (qty <= 0 && existingMaterialQty <= 0) { + notify(t('processing.toast.needPickQty')); + return; + } + const outputQty = Number(pickOutputQty); + if (pickHasBom) { + if (!Number.isFinite(outputQty) || outputQty <= 0) { + notify(t('processing.toast.needPickOutputQty')); + return; + } + if (outputQty > existingMaterialQty + qty + 1e-9) { + notify(t('processing.toast.pickOutputExceeds')); + return; + } + } const unitPrice = pickForm.processUnitPrice === '' ? null : Number(pickForm.processUnitPrice); + let manualOutputAllocations: + | Array<{ order_item_id: string; qty: number }> + | undefined; + if (pickHasBom) { + if (!pickOutputPreview || pickOutputPreviewLoading) { + notify(t('processing.toast.outputAllocationNotReady')); + return; + } + manualOutputAllocations = pickOutputPreview.plan.allocations.map((row) => ({ + order_item_id: row.orderItemId, + qty: Number(pickOutputAllocationDrafts[row.orderItemId] ?? row.allocatedQty) || 0, + })); + const allocationSum = manualOutputAllocations.reduce((sum, row) => sum + row.qty, 0); + if (Math.abs(allocationSum - outputQty) > 0.0011) { + notify(t('processing.toast.outputAllocationMismatch')); + return; + } + } setSaving(true); try { - await pickDemandSheetMaterialApi(pickTask.id, { - sku_code: pickForm.selectedSku.sku_code, - qty, - process_unit_price: unitPrice, - remark: pickForm.remark.trim() || undefined, - request_id: pickForm.requestId || undefined, - }); - notify.success(t('processing.toast.pickOk')); + if (qty > 0) { + await pickDemandSheetMaterialApi(pickTask.id, { + sku_code: pickForm.selectedSku.sku_code, + qty, + process_unit_price: unitPrice, + remark: pickForm.remark.trim() || undefined, + request_id: pickForm.requestId || undefined, + }); + } + if (pickHasBom) { + await completeProcessingWorkApi({ + task_id: pickTask.id, + gross_weight: existingMaterialQty + qty, + net_weight: outputQty, + process_unit_price: unitPrice ?? 0, + remark: pickForm.remark.trim() || undefined, + manual_output_allocations: manualOutputAllocations, + }); + notify.success(t('processing.toast.workOk')); + } else { + notify.success(t('processing.toast.pickOk')); + } setPickTask(null); fetchTasks(); + requestNavBadgeRefresh(); } catch (error: any) { - notify(error?.message || t('processing.toast.pickFail')); + notify(error?.message || (pickHasBom ? t('processing.toast.workFail') : t('processing.toast.pickFail'))); } finally { setSaving(false); } @@ -1048,7 +1240,7 @@ export const ProcessingManagement: React.FC = () => { notify.success(t('processing.toast.inspectFailMarked')); } else { notify.success(t('processing.toast.inspectPass')); - requestNavBadgeRefresh(); + requestNavBadgeRefresh(); } setShowInspectModal(false); setSelectedTask(null); @@ -1465,6 +1657,38 @@ export const ProcessingManagement: React.FC = () => { : t('processing.act.submitDone')} )} + {/** + * 仓内需求单关联的订单已全部完结:历史残留,仅管理员可删除。 + * 后端二次校验 unfinished_link_count=0。 + */} + {task.source_type === 'demand' && + Number(task.linked_order_count) > 0 && + Number(task.unfinished_linked_order_count) === 0 && + canDeleteOrphanDemand && ( + + )} + {/** + * 订单已完结但加工单仍残留:仅管理员可删除; + * 后端还会二次校验订单状态 >= 90 且任务仍是待加工/加工中。 + */} + {task.source_type === 'order' && + Number(task.order_status) >= 90 && + Number(task.process_status) < PROCESS_STATUS.completed && + canDeleteStandalone && ( + + )} {/** * 独立加工单删除(2026-10-23 开发者:「提交完工的单子可以点击删除」): * 只有**独立加工单**显示;已完工/待验收都可删,后端在成品被领用时拒绝并说明。 @@ -1808,7 +2032,7 @@ export const ProcessingManagement: React.FC = () => {
- + @@ -2019,6 +2243,58 @@ export const ProcessingManagement: React.FC = () => { className="app-input app-focus-ring w-full border rounded-lg px-3 py-2" />
+ {pickHasBom ? ( +
+ + + {pickOutputPreviewLoading ? ( +

+ {t('processing.modal.outputAllocationLoading')} +

+ ) : pickOutputPreview?.plan.allocations.length ? ( +
+
+ {t('processing.modal.outputAllocationTitle', { + output: String(Number(pickOutputQty) || 0), + })} +
+
+ {pickOutputPreview.plan.allocations.map((row) => ( +
+
+
+ {row.customerName || row.orderCode} +
+
+ {row.orderCode} · 需求 {row.demandQty} +
+
+ + setPickOutputAllocationDrafts((prev) => ({ + ...prev, + [row.orderItemId]: value, + })) + } + className="app-input w-24 rounded border px-2 py-1 text-sm" + /> +
+ ))} +
+
+ ) : null} +
+ ) : null}
{ const [isParsing, setIsParsing] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false); const submitInFlightRef = useRef(false); + const [bomSetupOpen, setBomSetupOpen] = useState(false); + const [bomSetupTargets, setBomSetupTargets] = useState([]); /** * 解析重入锁:解析结果是 append 写入(setParsedItems(prev => [...prev, ...])), * 重复解析会产生重复明细行。按钮 disabled 之外再补一层函数内同步守卫, @@ -1936,6 +1945,37 @@ export const CustomerOrder: React.FC = () => { clearSubmitError(); try { + // 仓内加工商品若未配置原材料:原页面弹窗设置,保存后自动继续提交。 + try { + const warehouseRows = parsedItems + .filter( + (item) => + item.skuCode && + requiresWarehouseProcessing(item.processingMethod, item.processingOwner) + ) + .map((item) => ({ + skuCode: item.skuCode, + skuName: item.skuName || resolveOrderEntryNameForSubmit(item), + processingMethod: item.processingMethod, + })); + if (warehouseRows.length) { + const bomMap = await loadProductProcessingBom( + warehouseRows.map((row) => row.skuCode || ''), + effectiveBranchCode + ); + const missing = findMissingProcessingBomTargets(warehouseRows, bomMap); + if (missing.length) { + setBomSetupTargets(missing); + setBomSetupOpen(true); + submitInFlightRef.current = false; + setIsSubmitting(false); + return; + } + } + } catch (bomError) { + console.warn('检查加工原材料配置失败', bomError); + } + const productInputs = parsedItems.map((item) => ({ key: item.id, name: resolveOrderEntryNameForSubmit(item), @@ -2763,6 +2803,21 @@ export const CustomerOrder: React.FC = () => {
+ { + setBomSetupOpen(false); + setBomSetupTargets([]); + }} + onSaved={() => { + setBomSetupOpen(false); + setBomSetupTargets([]); + void confirmSubmitOrder(); + }} + /> + { const [editItems, setEditItems] = useState([]); /** 打开详情时实收数量快照;保存时只提交用户改过的行(20260829-save-received-qty-merge) */ const [receivedQtyBaseline, setReceivedQtyBaseline] = useState>(new Map()); + const [bomSetupOpen, setBomSetupOpen] = useState(false); + const [bomSetupTargets, setBomSetupTargets] = useState([]); const [activeQuoteSheetCode, setActiveQuoteSheetCode] = useState(null); const [quoteCostBySku, setQuoteCostBySku] = useState>(new Map()); const [supplierCategories, setSupplierCategories] = useState([]); @@ -2430,6 +2438,39 @@ export const OrderManagement: React.FC = () => { savingOrderRef.current = true; setIsSavingOrder(true); try { + // 仓内加工商品未配置原材料:原页面弹窗设置,保存后自动继续保存订单 + if (selectedOrder && canEditItemsForOrder(selectedOrder)) { + try { + const warehouseRows = editItems + .filter((item) => + requiresWarehouseProcessing( + item.processing_method, + resolveOrderManageProcessingOwner(item.processing_method, item.processing_owner) + ) + ) + .map((item) => ({ + skuCode: item.sku_code, + skuName: item.sku_name || item.item_name, + processingMethod: item.processing_method, + })); + if (warehouseRows.length) { + const bomMap = await loadProductProcessingBom( + warehouseRows.map((row) => row.skuCode || ''), + selectedOrder?.branch_code || operatingBranchCode || null + ); + const missing = findMissingProcessingBomTargets(warehouseRows, bomMap); + if (missing.length) { + setBomSetupTargets(missing); + setBomSetupOpen(true); + savingOrderRef.current = false; + setIsSavingOrder(false); + return; + } + } + } catch (bomError) { + console.warn('检查加工原材料配置失败', bomError); + } + } if (selectedOrder && canEditItemsForOrder(selectedOrder)) { const inboundSwitch = editItems.some((item) => { if (!item.inbound_done || item.is_returned) return false; @@ -5141,6 +5182,21 @@ export const OrderManagement: React.FC = () => { )} + { + setBomSetupOpen(false); + setBomSetupTargets([]); + }} + onSaved={() => { + setBomSetupOpen(false); + setBomSetupTargets([]); + void saveOrderChanges(); + }} + /> + ); }; diff --git a/src/utils/processingBom.ts b/src/utils/processingBom.ts new file mode 100644 index 0000000..7fabc02 --- /dev/null +++ b/src/utils/processingBom.ts @@ -0,0 +1,157 @@ +/** + * 仓内加工原材料 BOM:录单/订单详情内联设置用。 + * + * BOM 存在 product_catalog.processing_bom: + * [{ method, material_sku, loss_rate }] + * 与商品管理编辑页使用同一份数据。 + */ +import { supabase } from '../supabase/client'; + +export interface ProcessingBomEntry { + method: string; + material_sku: string; + loss_rate: number; +} + +export interface ProcessingBomSetupTarget { + skuCode: string; + skuName: string; + processingMethod: string; +} + +function trimText(value: unknown): string { + return String(value ?? '').trim(); +} + +export function normalizeProcessingBomEntries(raw: unknown): ProcessingBomEntry[] { + if (!Array.isArray(raw)) return []; + const out: ProcessingBomEntry[] = []; + const seen = new Set(); + for (const item of raw) { + if (!item || typeof item !== 'object') continue; + const row = item as Record; + // method 允许为空:空 = 该商品所有加工方式通用(2026-11-02 商品级单原料) + const method = trimText(row.method); + const materialSku = trimText(row.material_sku ?? row.materialSku); + const loss = Number(row.loss_rate ?? row.lossRate ?? 0); + if (!materialSku) continue; + if (!Number.isFinite(loss) || loss < 0 || loss >= 1) continue; + const key = method.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push({ method, material_sku: materialSku, loss_rate: loss }); + } + return out; +} + +/** 按 SKU 批量读取 BOM;优先匹配指定分公司行。 */ +export async function loadProductProcessingBom( + skuCodes: string[], + branchCode: string | null +): Promise> { + const codes = [...new Set(skuCodes.map(trimText).filter(Boolean))]; + const map = new Map(); + if (!codes.length) return map; + const { data, error } = await supabase + .from('product_catalog') + .select('code,branch_code,processing_bom') + .eq('item_type', 'product') + .in('code', codes); + if (error) throw error; + const rows = data || []; + for (const code of codes) { + const exact = branchCode + ? rows.find((row: any) => row.code === code && row.branch_code === branchCode) + : undefined; + const fallback = rows.find((row: any) => row.code === code); + const row = exact || fallback; + if (row) map.set(code, normalizeProcessingBomEntries(row.processing_bom)); + } + return map; +} + +/** 找出仓内加工行里「缺该加工方式 BOM」的商品(同商品+方式去重)。 */ +export function findMissingProcessingBomTargets( + items: Array<{ skuCode?: string | null; skuName?: string | null; processingMethod?: string | null }>, + bomMap: Map +): ProcessingBomSetupTarget[] { + // 商品级只维护一份原材料:同一商品只需检查一次,加工方式不影响是否已配置 + const seen = new Set(); + const targets: ProcessingBomSetupTarget[] = []; + for (const item of items) { + const skuCode = trimText(item.skuCode); + const method = trimText(item.processingMethod); + if (!skuCode || !method) continue; + if (seen.has(skuCode)) continue; + const entries = bomMap.get(skuCode) || []; + // 商品级只维护一份原材料:只要配置过任意一条,就视为已配置(加工方式由录单填写) + const configured = entries.length > 0; + seen.add(skuCode); + if (configured) continue; + targets.push({ + skuCode, + skuName: trimText(item.skuName) || skuCode, + processingMethod: method, + }); + } + return targets; +} + +/** 保存/合并某个商品的 BOM 条目(按加工方式覆盖)。 */ +export async function saveProductProcessingBom(input: { + skuCode: string; + branchCode: string | null; + existing: ProcessingBomEntry[]; + entry: ProcessingBomEntry; +}): Promise { + const skuCode = trimText(input.skuCode); + const method = trimText(input.entry.method); + const materialSku = trimText(input.entry.material_sku); + // method 为空 = 商品级单原料,不再要求加工方式 + if (!skuCode || !materialSku) { + throw new Error('缺少商品或原材料信息'); + } + // 商品级单原料:method 为空时直接替换为唯一通用配置;保留兼容旧的按加工方式数据 + const merged = method + ? [ + ...input.existing.filter((entry) => entry.method.toLowerCase() !== method.toLowerCase()), + { method, material_sku: materialSku, loss_rate: Number(input.entry.loss_rate) || 0 }, + ] + : [{ method: '', material_sku: materialSku, loss_rate: Number(input.entry.loss_rate) || 0 }]; + // 数据网关会把 JS 数组按 PostgreSQL 数组字面量传参,jsonb 列会报 + // `invalid input syntax for type json`;jsonb 值必须显式 JSON 字符串。 + let query = supabase + .from('product_catalog') + .update({ processing_bom: JSON.stringify(merged) as unknown as ProcessingBomEntry[] }) + .eq('item_type', 'product') + .eq('code', skuCode); + if (input.branchCode) query = query.eq('branch_code', input.branchCode); + const { error } = await query; + if (error) throw error; +} + + +/** 批量取商品名称(用于行内显示原材料名) */ +export async function loadProductNameMap( + skuCodes: string[], + branchCode: string | null +): Promise> { + const codes = [...new Set(skuCodes.map(trimText).filter(Boolean))]; + const map = new Map(); + if (!codes.length) return map; + const { data, error } = await supabase + .from('product_catalog') + .select('code,name,branch_code') + .eq('item_type', 'product') + .in('code', codes); + if (error) throw error; + const rows = data || []; + for (const code of codes) { + const exact = branchCode + ? rows.find((row: any) => row.code === code && row.branch_code === branchCode) + : undefined; + const row = exact || rows.find((r: any) => r.code === code); + if (row?.name) map.set(code, String(row.name)); + } + return map; +} diff --git a/src/utils/processingTasks.ts b/src/utils/processingTasks.ts index 80afd10..39c1f67 100644 --- a/src/utils/processingTasks.ts +++ b/src/utils/processingTasks.ts @@ -41,6 +41,9 @@ export interface ProcessingTaskRow { started_at?: string | null; completed_at?: string | null; created_at?: string | null; + linked_order_count?: number; + unfinished_linked_order_count?: number; + order_status?: number | null; } export async function resolveOrderItemProcessingContext( diff --git a/src/utils/workflowApi.ts b/src/utils/workflowApi.ts index 6bf6cf2..399f138 100644 --- a/src/utils/workflowApi.ts +++ b/src/utils/workflowApi.ts @@ -1982,6 +1982,10 @@ export interface ProcessingTaskRow { task_code?: string | null; /** 仓内需求单仍挂着的未退货订单行数 */ linked_order_count?: number | null; + /** 仍关联未完结订单数 */ + unfinished_linked_order_count?: number | null; + /** 订单状态(需求单删除判定用) */ + order_status?: number | null; } export interface StandaloneProcessingSkuOption { @@ -2151,6 +2155,62 @@ export async function listStandaloneLinesApi(taskId: string) { } /** 删除独立加工单(仅管理员;成品未被领用时自动退回原料) */ + +export interface FinishedOutputAllocationPreview { + task: { + id: string; + taskCode: string | null; + outputSku: string | null; + processingMethod: string | null; + netWeight: number; + materialCost: number; + }; + plan: { + actualQty: number; + totalDemandQty: number; + shortfallQty: number; + excessQty: number; + allocations: Array<{ + orderItemId: string; + orderCode: string; + customerName?: string | null; + demandQty: number; + allocatedQty: number; + orderCreatedAt: string | null; + }>; + }; + unitCost: number; + totalCost: number; +} + +export async function previewFinishedOutputAllocationApi(taskId: string, actualQty: number) { + const query = new URLSearchParams({ actual_qty: String(actualQty) }); + return workflowFetch<{ data: FinishedOutputAllocationPreview }>( + `/processing/demand/${encodeURIComponent(taskId)}/finished-output-preview?${query.toString()}` + ); +} + +export async function deleteHistoricalDemandSheetApi(taskId: string) { + return workflowFetch<{ success: boolean; data: { id: string; task_code: string; returned_material: boolean } }>( + `/processing/demand-history/${encodeURIComponent(taskId)}`, + { method: 'DELETE' } + ); +} + +export async function deleteCompletedOrderProcessingTaskApi(taskId: string) { + return workflowFetch<{ success: boolean; data: { id: string; task_code: string; order_code: string } }>( + `/processing/order/${encodeURIComponent(taskId)}`, + { method: 'DELETE' } + ); +} + +export async function syncProcessingRawMaterialPurchasesApi(outputSku?: string) { + return workflowFetch<{ data: { created: number; updated: number; cancelled: number; flagged: number } }>( + '/purchase-orders/processing-raw-materials/sync', + { method: 'POST', body: JSON.stringify({ output_sku: outputSku || null }) } + ); +} + export async function deleteStandaloneProcessingTaskApi(taskId: string) { return workflowFetch<{ success: boolean; @@ -2190,6 +2250,7 @@ export async function completeProcessingWorkApi(body: { process_fee?: number; process_unit_price?: number; remark?: string; + manual_output_allocations?: Array<{ order_item_id: string; qty: number }>; }) { return workflowFetch<{ success: boolean }>('/processing/complete', { method: 'POST',