feat(独立加工): 后端 P0——多行原料 + 多行成品回仓(processing_in) + 损耗自动差额可覆盖 + 成品成本默认均分可设置 + 报告继承(批次只复制关联/检验复制引用) + 请求号幂等;真库跑通
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
# 独立加工单 P0:多行原料 / 多行成品 / 成品回仓 / 损耗 / 报告继承
|
||||
|
||||
- 日期:2026-10-23
|
||||
- 来源:开发者「独立加工需要优化…先领取原料橘子 然后选择加工出来了什么商品 加工出来了多少斤 损耗了多少 加工好的重新落回仓库 需要一个按钮表示是否继承原材料的报告(没有报告就没有)」
|
||||
+ 「web 与小程序独立加工单界面需要优化」,并要求 **Web 先行**、测试通过后再同步小程序。
|
||||
|
||||
## 1. 本轮已确认的口径(开发者逐条回答)
|
||||
|
||||
| # | 决策 |
|
||||
|---|---|
|
||||
| 1 | **原料可多行** |
|
||||
| 2 | **成品多行**:一个原料可加工出多个商品 |
|
||||
| 3 | 损耗:自动差额为主,**允许人工覆盖**;**不允许产出 > 投入** |
|
||||
| 5 | 成品入库成本 **可人工设置**,默认按原料成本**按产出数量均分** |
|
||||
| 6 | 损耗成本 **只留痕、不进账本**(沿用 2026-10-15 裁决) |
|
||||
| 7 | 报告继承 **可选**:库存批次报告 / 检验报告 各自勾选(没有就不显示可继承) |
|
||||
| 8 | 沿用现有 `processing_tasks` 单据与状态链;作废入口由实施方判断(本轮未做,见 §6) |
|
||||
| 9 | 无老单;**只读保留**、不迁移 |
|
||||
| 10 | **Web 先行**,小程序随后 |
|
||||
|
||||
## 2. 数据模型(迁移 `20261074_standalone_processing_outputs.sql`)
|
||||
|
||||
| 对象 | 内容 |
|
||||
|---|---|
|
||||
| `processing_task_materials`(新) | `task_id, sku_code, sku_name, spec, unit, qty, material_cost, deducted_batches JSONB` |
|
||||
| `processing_task_outputs`(新) | `task_id, sku_code, sku_name, spec, unit, qty, unit_cost, cost_amount, batch_no, inventory_id, inherit_batch_report, inherit_inspection_report` |
|
||||
| `processing_tasks.client_request_no`(新列 + 唯一索引) | 幂等键:同分公司 + 同请求号只建一张单 |
|
||||
| `inventory_batch_report_matches.match_source` | 约束放宽为 `auto / manual / inherit`(加工继承) |
|
||||
|
||||
迁移纪律:只 DDL + 名单登记(`tenant_business_tables()` 119 项)、逐 schema 补列/补索引、末尾 `ensure_tenant_schemas_match_template()` + `ensure_all_tenant_core_rls()`,幂等可重跑。
|
||||
|
||||
## 3. 后端行为
|
||||
|
||||
### 3.1 创建 `createStandaloneProcessingTask`
|
||||
- `materials: [{skuCode, qty}]`(老调用 `skuCode+qty` 仍按单行处理 ⇒ 旧前端/小程序不回归)
|
||||
- 同 SKU 多行**合并**成一行
|
||||
- 逐行:查商品 → `getClaimableStockQty` 校验(毛可用 − 全部在用预留)→ `fifoDeductInventory(operationType='processing_out')` → 落原料行(含抵减批次 JSON)→ 按行冲减库存持有
|
||||
- 单据头:`source_qty/material_qty = 原料合计`、`material_cost = 各行成本之和`
|
||||
- **幂等**:`client_request_no` 命中即返回既有单(不重复扣库存)
|
||||
- **原子性**:任一行失败 → 整单回滚(无单、无流水、无成本行)
|
||||
|
||||
### 3.2 完工 `completeStandaloneProcessingTask`(新)
|
||||
- 校验:单据存在、`source_type='standalone'`、属于当前分公司、未完成(40)
|
||||
- 读取原料行(老单无原料行时用单据头兜底)
|
||||
- 校验:产出合计 ≤ 原料合计;`损耗 = 人工值 ?? (原料合计 − 产出合计)`;`产出 + 损耗 ≤ 原料合计`
|
||||
- 成本:`默认单价 = 原料成本合计 ÷ 产出合计`(按数量均分),允许每行 `unitCost` 覆盖;`金额 = 数量 × 单价`
|
||||
- 回仓:每行成品生成**新批次** `PG-<加工单号>-<行号>`(撞号加随机后缀),写 `inventory` + `inventory_logs(operation_type='processing_in')` + 库存持有成本(`cost_source='processing_output'`)
|
||||
- 报告继承(可选):
|
||||
- 批次报告:按原料抵减批次的 `inventory_batch_report_matches.report_id` **只复制关联**(`match_source='inherit'`),不新增报告本体;
|
||||
- 检验报告:从原料批次的 `inspections.inspection_photos` 复制**文件引用**,新建一条 `report_type='inspection_inherit'` 报告并挂到成品批次;
|
||||
- 继承不到(原料无报告)时不建空报告,返回 `inherit_* = false`
|
||||
- 收口:`process_status=40`、`loss_qty`、`gross_weight=原料合计`、`net_weight=产出合计`、`completed_at`
|
||||
|
||||
### 3.3 路由
|
||||
`POST /processing/standalone/create`(扩展 materials / client_request_no)、
|
||||
`POST /processing/standalone/:taskId/complete`(新)、
|
||||
`GET /processing/standalone/:taskId/lines`(新,详情渲染用)。
|
||||
|
||||
## 4. 前端(Web 先行)
|
||||
- 客户端 API:`createStandaloneProcessingTaskApi`(多行)、`completeStandaloneProcessingTaskApi`、`listStandaloneLinesApi`
|
||||
- 界面改造(下一步实施):创建弹窗「多行原料(含可用量)」、完工弹窗由「毛重/净重」改为「成品行 + 损耗 + 报告继承勾选」
|
||||
|
||||
## 5. 真库验证(dev `tenant_br002`,本轮已跑)
|
||||
|
||||
| 验证 | 结果 |
|
||||
|---|---|
|
||||
| 创建 2 行原料(苹果666 30 / 精瘦肉 20) | 单号 `SPG-20261023-0003`,原料合计 50,材料成本 **440** |
|
||||
| 完工 2 行成品(20 / 10) | 产出 30,**损耗 20(自动差额)**,默认均分单价 **14.6667** |
|
||||
| 成品回仓 | `PG-SPG-20261023-0003-1/2` 两批次,`quantity=20/10`,`cost_price=14.67` |
|
||||
| 加工入库流水 | 两条 `processing_in`(20 / 10) |
|
||||
| 库存持有成本 | 两条 `inventory_holding / processing_output`(293.33 / 146.67) |
|
||||
| 报告继承 | `inventory_batch_report_matches` 两条 `match_source=inherit` |
|
||||
| 行数 | 原料行 2 / 成品行 2 |
|
||||
| 重复完成 | 被拒:`该加工单已完成,不能重复申报成品` |
|
||||
| 产出 > 投入 | 被拒:`产出合计(11)不能大于原料投入合计(10)` |
|
||||
| 第 2 行原料不足 | 整单回滚:精瘦肉可用量 **前 96 / 后 96**(无变化) |
|
||||
|
||||
## 6. 未做 / 待决策
|
||||
|
||||
1. **Web 界面**(创建弹窗多行原料、完工弹窗成品行)尚未改造 —— 本轮只交付后端契约与 API 客户端,界面是下一步(本轮 commit 不含 UI 行为变更)。
|
||||
2. **小程序**按开发者要求等 Web 验证通过后再同步。
|
||||
3. **作废入口**(反向退回原料库存)本轮未做:需要独立设计(涉及已产出的成品批次回滚),建议 P1。
|
||||
4. **加工费是否计入成品成本**:当前默认**不计入**(只记录 `process_unit_price`),若需计入需批准。
|
||||
5. 损耗**不产生**库存流水与账本行(沿用既有裁决)。
|
||||
@@ -154,6 +154,7 @@ AI 提示词清理已停用条目(7 条归档不删、清单过滤 archived、
|
||||
**库存抵扣弹窗:批次成本就地设置 + 明确「保存」按钮**:开发者「抵扣的批次我没有设置成本价 能否在图一的弹窗位置就进行设置」「当前能改 但是没有给确定按钮」。改前编辑区只有「查看影响 → 确认修改」两步(首屏显示"查看影响",读不出这就是保存),批次成本与「改成本」混在密排灰字里。改法(纯前端、复用既有接口):编辑区新增主按钮**「保存」**直接调 `applyBatchCostChangeApi`(与确认修改同一接口、备注必填、重算未结算账本的既有口径不变,已结算不回改);成本为空时入口文案改为**「设置成本价」**;编辑区加「保存影响」小字;批次成本从灰字拆成独立 **chip**(未设置用琥珀色)。财务口径/预览接口/分配逻辑一行未动。证据:契约测试 5 项(**把保存按钮 onClick 改空后确认变红**)+ 全量 1374 passed(4 项既有红灯无关),见 [20261023-抵扣弹窗就地设置批次成本.md](./20261023-抵扣弹窗就地设置批次成本.md)。
|
||||
**抵扣批次弹窗的列表入口 + 全额抵扣行不再要求采购成本价**:开发者「这个库存抵扣弹窗必须要先打开订单详情页才能打开」「最好是无需打开订单详情」+「完全库存抵扣状态下 哪怕抵扣的库存批次成本价为0 按理说也不能出现 采购成本价需要输入的情况」(附红框 0 截图)。两处修:① 列表**操作列**新增「抵扣批次」直达入口(`canViewCoverBatches && stock_cover_items 非空` 才显示,点击 `stopPropagation` 直接开弹窗,不必展开详情);② 页面把 `cover_qty` 从账本成本闭包里解耦——原来 `if (coverUnit == null) return {}` 会让「批次成本 0 ⇒ 无账本 ⇒ cover_qty 丢失 ⇒ 判不出全额抵扣 ⇒ 采购成本价又要求输入」,现改为 `cover_qty` 无条件挂载、`cover_unit_cost/cover_cost_amount` 仍只在账本有值时返回(不拿 0 冒充)。成本口径/账本/分配逻辑一行未动。证据:契约测试 4 项(**把旧写法注入回去确认变红**)+ 全量 1386 passed(4 项既有红灯无关),见 [20261023-抵扣批次入口与全额抵扣不要求采购成本价.md](./20261023-抵扣批次入口与全额抵扣不要求采购成本价.md)。
|
||||
**「选择抵扣的库存商品」弹窗可就地改被抵扣批次成本**:开发者「订单详情里面的选择抵扣商品 这块看看能否也加一个修改入库成本价的入口」「如果是被抵扣的批次 那么关闭弹窗后记得刷新一下 打开的订单详情的界面」。改前读侧 `listOrderItemDeductedBatches()` 不返回 `cost_price`(只查生产日期),弹窗里只见批次号/数量,改成本只能去另一个弹窗;且关闭只走 `onClose()`,改完成本不刷新明细。改法:① 读侧查询补 `cost_price`(附加字段);② 弹窗每个被抵扣批次显示「成本价 X」(无则琥珀色「未设置」)并给「设置成本价 / 改成本」内联编辑(保存复用既有 `applyBatchCostChangeApi`,备注选填);③ 改过成本置脏标记,`closeModal()` 里 `if (dirty) onSaved()` 刷新订单明细;④ 保存后重拉一次批次接口让弹窗内显示立即更新。分配/重算口径未动。证据:契约测试 4 项(**把关闭刷新注空后确认变红**)+ 既有渲染用例 9 项 + 全量 1390 passed(4 项既有红灯无关),见 [20261023-抵扣商品弹窗改批次成本.md](./20261023-抵扣商品弹窗改批次成本.md)。
|
||||
**独立加工单 P0:多行原料 / 多行成品 / 成品回仓 / 损耗 / 报告继承**:开发者「先领取原料橘子 然后选择加工出来了什么商品 加工出来了多少斤 损耗了多少 加工好的重新落回仓库 需要一个按钮表示是否继承原材料的报告」+「web 与小程序独立加工单界面需要优化」,并确认:原料多行、成品多行(一原料可出多成品)、损耗自动差额可人工覆盖且不允许产出>投入、成品入库成本默认按产出**均分**可人工设置、损耗只留痕不进账本、报告继承**可选**(批次报告/检验报告)、老单只读保留、**Web 先行**。已落地:迁移 `20261074`(`processing_task_materials` / `processing_task_outputs` / `processing_tasks.client_request_no` 幂等键 / `match_source` 允许 `inherit`,名单 119 项),后端 `createStandaloneProcessingTask` 多行原料(老调用兼容、同 SKU 合并、逐行 FIFO 与可用量校验、原子回滚、请求号幂等)+ 新增 `completeStandaloneProcessingTask`(成品新批次回仓 `processing_in`、持有成本 `cost_source=processing_output`、默认均分/可覆盖、损耗留痕、批次报告只复制关联、检验报告复制文件引用)+ 三个路由。**真库实跑证据**:2 行原料→材料成本 440;2 行成品 20/10→产出 30、损耗 20、单价 14.6667;成品批次 `PG-…-1/2` 成本 14.67;两条 `processing_in`;两条持有成本 293.33/146.67;两条 `match_source=inherit`;重复完成被拒、产出>投入被拒、原料不足整单回滚(可用量前后均 96)。**Web 界面改造与小程序同步为下一步**,见 [20261023-独立加工多产出与成品回仓.md](./20261023-独立加工多产出与成品回仓.md)。
|
||||
**存储租户分支根放行 `SUP…` 编码(修上传批次报告弹英文 `Invalid file name`)**:开发者报障「点击解析触发的问题」——库存 → 上传报告点「上传并解析」直接弹英文 `Invalid file name`。根因是存储形状白名单把租户分支根写死成主系统的 `/^BR…$/`,而本系统分公司编码是 `SUP35143228` 这类形状 ⇒ `buildStorageObjectKey` 直接抛错;同一份 `BR…` 正则还重复出现在归属判定与 `stripStorageBranchPrefix` 里(只修一处会出现「上传成功但读/签名 403」)。现收敛为**唯一定义** `TENANT_BRANCH_ROOT_RE = /^[A-Z0-9][A-Z0-9_-]{1,29}$/`(= `branch_code` 创建时统一大写的实际契约),三处使用点同口径;未知**小写**目录(`other`/`free-cost`/`quality-reports`/`releases`…)仍一律拒绝,层级上限、穿越拒收、`<branch>/` 前缀策略与存储布局均未动,见 [20261021-存储分支根白名单放行SUP编码.md](./20261021-存储分支根白名单放行SUP编码.md)。
|
||||
**库存「修改批次」弹窗:报告按当前批次直传 + 可修改**:开发者「编辑某一个批次……上传批次报告就是上传,因为都找到这个批次了,还用啥匹配呀……也可能是农残这些」——调整弹窗里的「上传报告」不再打开**页级匹配弹窗**(解析商品名 → 猜候选批次 → 人工确认),改为新弹窗 `BatchReportBindModal`:报告类型(批次/农残/检疫/年度)、报告编号(选填)、文件(可多选)→ `POST /inventory/batch-reports/bind` **直接绑定当前 `inventory_id`**,落库即 `status=30` 并写 `match_source='manual'` 的关联行(OCR 仍跑一次只留商品名/生产日期等元数据,失败降级不阻断);每份报告新增「编辑」(`PATCH /inventory/batch-reports/:id`,只改类型/编号,换文件走删除+重传)与已有的「删除」。同时修掉 `report_type` 断层:页级上传前端早就在传、路由未转发、服务端硬编码 `'batch'`,选农残也存成批次。页级匹配流程、表结构、库存写入与冻结面无改动,见 [20261021-库存批次报告按批次直传与修改.md](./20261021-库存批次报告按批次直传与修改.md)。
|
||||
**小程序分拣「调整批次」弹窗展示生产日期**:开发者附截图「小程序这块调整展示时需要展示出这批货的生产日期」——批次行原先只显示「区域 · 入库 · 效期 · 可用」。后端 `pickingService` 早已返回 `production_date`、小程序 `loadBatchInfo` 也已映射,但两个**弹窗行构造器**(`buildEditorState` / `resetBatchEditorFifo`)把该字段丢了,模板也没渲染;现三处补齐,并在「入库」后、「效期」前插入「生产」(空值显示 `—`,不拿入库日顶替)。同时把 `batch-row-meta` 从 `nowrap + ellipsis` 改成允许换行——否则多一段会把尾部的「可用」截掉。行内批次摘要(区域+入库日+数量)、后端接口与 FIFO/抵扣口径未动,见 [20261021-小程序分拣批次行展示生产日期.md](./20261021-小程序分拣批次行展示生产日期.md)。
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
-- 独立加工单 P0:多行原料 + 多行成品 + 成品回仓(2026-10-23 开发者裁决)
|
||||
-- 决策(本轮已确认):原料多行、成品多行(一个原料可产出多个成品)、损耗自动差额可人工覆盖、
|
||||
-- 成品入库成本默认「原料成本按产出均分」且允许人工设置、损耗成本只留痕不进账本、
|
||||
-- 报告继承为**可选**(库存批次报告 / 检验报告 各自勾选)、老单只读保留、Web 先行。
|
||||
-- 纪律:仅 DDL + 名单登记,不做数据修复;幂等可重跑。
|
||||
-- 见 docs/design/20261023-独立加工多产出与成品回仓.md
|
||||
|
||||
-- ① 两张子表建在 tenant_template(其余分公司由 ensure_tenant_schemas_match_template 克隆)
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text := 'tenant_template';
|
||||
BEGIN
|
||||
IF to_regclass('tenant_template.processing_tasks') IS NULL THEN
|
||||
RAISE NOTICE 'tenant_template.processing_tasks 不存在,跳过建表';
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
EXECUTE format(
|
||||
'CREATE TABLE IF NOT EXISTS %I.processing_task_materials (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
task_id UUID NOT NULL REFERENCES %I.processing_tasks(id) ON DELETE CASCADE,
|
||||
sku_code VARCHAR(50) NOT NULL,
|
||||
sku_name VARCHAR(200),
|
||||
spec VARCHAR(60),
|
||||
unit VARCHAR(20),
|
||||
qty NUMERIC(12,3) NOT NULL DEFAULT 0,
|
||||
material_cost NUMERIC(14,2) NOT NULL DEFAULT 0,
|
||||
-- 本行实际扣减的批次([{batch_no, qty, cost_price}]):报告继承与对账要用,JSON 省掉第三张表
|
||||
deducted_batches JSONB NOT NULL DEFAULT ''[]''::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)',
|
||||
sch, sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'CREATE INDEX IF NOT EXISTS idx_processing_task_materials_task
|
||||
ON %I.processing_task_materials (task_id)',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.processing_task_materials ADD COLUMN IF NOT EXISTS deducted_batches JSONB NOT NULL DEFAULT ''[]''::jsonb',
|
||||
sch
|
||||
);
|
||||
|
||||
EXECUTE format(
|
||||
'CREATE TABLE IF NOT EXISTS %I.processing_task_outputs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
task_id UUID NOT NULL REFERENCES %I.processing_tasks(id) ON DELETE CASCADE,
|
||||
sku_code VARCHAR(50) NOT NULL,
|
||||
sku_name VARCHAR(200),
|
||||
spec VARCHAR(60),
|
||||
unit VARCHAR(20),
|
||||
qty NUMERIC(12,3) NOT NULL DEFAULT 0,
|
||||
unit_cost NUMERIC(14,4) NOT NULL DEFAULT 0,
|
||||
cost_amount NUMERIC(14,2) NOT NULL DEFAULT 0,
|
||||
batch_no VARCHAR(80),
|
||||
inventory_id UUID,
|
||||
inherit_batch_report BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
inherit_inspection_report BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)',
|
||||
sch, sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'CREATE INDEX IF NOT EXISTS idx_processing_task_outputs_task
|
||||
ON %I.processing_task_outputs (task_id)',
|
||||
sch
|
||||
);
|
||||
|
||||
END $$;
|
||||
|
||||
-- ①a2 抵减批次 JSON 列:逐 schema 补(克隆只补表,不同步新增列)
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
LOOP
|
||||
IF to_regclass(format('%I.processing_task_materials', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.processing_task_materials ADD COLUMN IF NOT EXISTS deducted_batches JSONB NOT NULL DEFAULT ''[]''::jsonb',
|
||||
sch
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- ①a3 报告关联来源:允许 'inherit'(加工产出继承原料批次报告)
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
LOOP
|
||||
IF to_regclass(format('%I.inventory_batch_report_matches', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.inventory_batch_report_matches DROP CONSTRAINT IF EXISTS inventory_batch_report_matches_source_chk',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.inventory_batch_report_matches
|
||||
ADD CONSTRAINT inventory_batch_report_matches_source_chk
|
||||
CHECK (match_source IN (''auto'', ''manual'', ''inherit''))',
|
||||
sch
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- ①b 幂等键(客户端重试/双击只建一张单):**逐 schema** 加列 + 唯一索引
|
||||
-- (克隆函数只补表结构,不同步新增列 ⇒ 必须自己遍历)
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
LOOP
|
||||
IF to_regclass(format('%I.processing_tasks', sch)) IS NOT NULL THEN
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.processing_tasks ADD COLUMN IF NOT EXISTS client_request_no VARCHAR(100)',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'CREATE UNIQUE INDEX IF NOT EXISTS idx_processing_tasks_client_request
|
||||
ON %I.processing_tasks (branch_code, client_request_no)
|
||||
WHERE client_request_no IS NOT NULL',
|
||||
sch
|
||||
);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- ② 名单登记(双向守卫要求 tenant_template 表集合 == tenant_business_tables())
|
||||
CREATE OR REPLACE FUNCTION public.tenant_business_tables()
|
||||
RETURNS TEXT[]
|
||||
LANGUAGE sql
|
||||
IMMUTABLE
|
||||
AS $$
|
||||
SELECT ARRAY[
|
||||
'main_system_sku_mappings',
|
||||
'after_sale_returns',
|
||||
'after_sales',
|
||||
'ai_prompt_overrides',
|
||||
'ai_prompt_revisions',
|
||||
'ai_prompt_templates',
|
||||
'alias_recognition_logs',
|
||||
'allocation_tasks',
|
||||
'assistant_conversations',
|
||||
'assistant_messages',
|
||||
'assistant_turns',
|
||||
'bid_awards',
|
||||
'bid_invitations',
|
||||
'bid_prices',
|
||||
'bid_quotes',
|
||||
'bid_round_items',
|
||||
'bid_rounds',
|
||||
'categories',
|
||||
'cost_adjustments',
|
||||
'cost_details',
|
||||
'customer_alias_stats',
|
||||
'customer_delivery_assignments',
|
||||
'customer_portal_users',
|
||||
'customer_processing_aliases',
|
||||
'customer_quote_sheet_customers',
|
||||
'customer_quote_sheet_items',
|
||||
'customer_quote_sheets',
|
||||
'customer_quote_versions',
|
||||
'customer_recipients',
|
||||
'customer_sku_aliases',
|
||||
'customer_sku_remarks',
|
||||
'customer_skus',
|
||||
'customer_statements',
|
||||
'customers',
|
||||
'delivery_location_history',
|
||||
'delivery_person_locations',
|
||||
'delivery_person_users',
|
||||
'delivery_persons',
|
||||
'delivery_schedules',
|
||||
'delivery_signatures',
|
||||
'delivery_tasks',
|
||||
'exception_tickets',
|
||||
'fixed_costs',
|
||||
'free_cost_invoice_links',
|
||||
'free_cost_invoices',
|
||||
'free_cost_payment_vouchers',
|
||||
'import_mapping_memories',
|
||||
'inspection_loss_confirmations',
|
||||
'inspection_photo_archive_entries',
|
||||
'inspection_photo_archives',
|
||||
'inspection_returns',
|
||||
'inspection_review_logs',
|
||||
'inspections',
|
||||
'inventory',
|
||||
'inventory_batch_report_matches',
|
||||
'inventory_batch_reports',
|
||||
'inventory_logs',
|
||||
'inventory_reservations',
|
||||
'invoice_statement_links',
|
||||
'invoices',
|
||||
'market_compare_exclusions',
|
||||
'market_external_catalog',
|
||||
'market_price_history',
|
||||
'market_price_indices',
|
||||
'market_prices',
|
||||
'market_sku_external_bindings',
|
||||
'notifications',
|
||||
'operation_logs',
|
||||
'order_allocation_batches',
|
||||
'order_item_fulfillments',
|
||||
'order_item_returns',
|
||||
'order_items',
|
||||
'orders',
|
||||
'parse_session_items',
|
||||
'parse_sessions',
|
||||
'picking_assign_rules',
|
||||
'picking_containers',
|
||||
'picking_items',
|
||||
'picking_scan_logs',
|
||||
'picking_tasks',
|
||||
'price_invert_events',
|
||||
'print_jobs',
|
||||
'processing_demand_items',
|
||||
'processing_demand_picks',
|
||||
'processing_logs',
|
||||
'processing_tasks',
|
||||
'product_catalog',
|
||||
'product_substitutions',
|
||||
'purchase_orders',
|
||||
'purchaser_users',
|
||||
'quality_report_prep_links',
|
||||
'quality_reports',
|
||||
'quote_price_proposals',
|
||||
'seasonal_recommendations',
|
||||
'self_purchase_stock_inbounds',
|
||||
'sign_records',
|
||||
'sku_direct_delivery_customers',
|
||||
'sku_suppliers',
|
||||
'skus',
|
||||
'smart_classification_rules',
|
||||
'statement_disputes',
|
||||
'statement_lines',
|
||||
'statement_payments',
|
||||
'supplier_categories',
|
||||
'supplier_prep_amend_requests',
|
||||
'supplier_preparations',
|
||||
'supplier_rating_snapshots',
|
||||
'supplier_statements',
|
||||
'supplier_users',
|
||||
'suppliers',
|
||||
'system_configs',
|
||||
'unit_conversions',
|
||||
'user_preferences',
|
||||
'voice_recognition_logs',
|
||||
'warehouse_locations',
|
||||
'warehouses',
|
||||
'weigh_devices',
|
||||
'processing_task_materials',
|
||||
'processing_task_outputs'
|
||||
];
|
||||
$$;
|
||||
|
||||
-- ③ 克隆到各分公司 schema(新表 + 新列),再跑 RLS 与双向断言
|
||||
DO $$
|
||||
BEGIN
|
||||
PERFORM public.ensure_tenant_schemas_match_template();
|
||||
EXCEPTION WHEN undefined_function THEN
|
||||
RAISE NOTICE 'ensure_tenant_schemas_match_template 不存在,跳过';
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
PERFORM public.ensure_all_tenant_core_rls();
|
||||
EXCEPTION WHEN undefined_function THEN
|
||||
RAISE NOTICE 'ensure_all_tenant_core_rls 不存在,跳过';
|
||||
END $$;
|
||||
@@ -453,7 +453,16 @@ router.post('/processing/standalone/create', authMiddleware, async (req: AuthReq
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '请选择当前操作分公司' });
|
||||
}
|
||||
/** 多行原料(2026-10-23):`materials: [{sku_code, qty}]`;老调用仍可只传 sku_code + qty */
|
||||
const rawMaterials = Array.isArray(req.body?.materials) ? (req.body.materials as unknown[]) : null;
|
||||
const materials = (rawMaterials || [])
|
||||
.map((row) => {
|
||||
const r = row as { sku_code?: unknown; qty?: unknown };
|
||||
return { skuCode: String(r?.sku_code ?? ''), qty: Number(r?.qty) };
|
||||
})
|
||||
.filter((row) => row.skuCode || Number.isFinite(row.qty));
|
||||
const data = await createStandaloneProcessingTask({
|
||||
...(materials.length ? { materials } : {}),
|
||||
skuCode: String(req.body?.sku_code || ''),
|
||||
qty: Number(req.body?.qty),
|
||||
processingMethod: String(req.body?.processing_method || ''),
|
||||
@@ -461,6 +470,7 @@ router.post('/processing/standalone/create', authMiddleware, async (req: AuthReq
|
||||
processUnitPrice: req.body?.process_unit_price === undefined ? null : Number(req.body.process_unit_price),
|
||||
operatorId: req.userId || null,
|
||||
remark: req.body?.remark ? String(req.body.remark) : null,
|
||||
clientRequestNo: req.body?.client_request_no ? String(req.body.client_request_no) : null,
|
||||
});
|
||||
return res.json({ success: true, data });
|
||||
} catch (error: any) {
|
||||
@@ -471,6 +481,63 @@ router.post('/processing/standalone/create', authMiddleware, async (req: AuthReq
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 独立加工**完工**:申报成品(多行)→ 成品新批次回仓 → 损耗留痕 → 可选继承原料报告。
|
||||
* 见 docs/design/20261023-独立加工多产出与成品回仓.md
|
||||
*/
|
||||
router.post('/processing/standalone/:taskId/complete', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['processing_manage']);
|
||||
const branchCode = getEffectiveBranchCode(ctx, readOperatingBranchCode(req));
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '请选择当前操作分公司' });
|
||||
}
|
||||
const { completeStandaloneProcessingTask } = await import('../../../services/processingStandaloneOutputService');
|
||||
const data = await completeStandaloneProcessingTask({
|
||||
taskId: String(req.params.taskId || ''),
|
||||
branchCode,
|
||||
outputs: (Array.isArray(req.body?.outputs) ? req.body.outputs : []).map((row: unknown) => {
|
||||
const r = row as Record<string, unknown>;
|
||||
return {
|
||||
skuCode: String(r?.sku_code ?? ''),
|
||||
qty: Number(r?.qty),
|
||||
unitCost: r?.unit_cost === undefined || r?.unit_cost === '' || r?.unit_cost === null ? null : Number(r.unit_cost),
|
||||
inheritBatchReport: r?.inherit_batch_report === true,
|
||||
inheritInspectionReport: r?.inherit_inspection_report === true,
|
||||
};
|
||||
}),
|
||||
lossQty:
|
||||
req.body?.loss_qty === undefined || req.body?.loss_qty === '' || req.body?.loss_qty === null
|
||||
? null
|
||||
: Number(req.body.loss_qty),
|
||||
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.get('/processing/standalone/:taskId/lines', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
requireWorkflowPermission(ctx, ['processing_manage']);
|
||||
const { listStandaloneMaterialsAndOutputs } = await import('../../../services/processingStandaloneOutputService');
|
||||
const data = await listStandaloneMaterialsAndOutputs(String(req.params.taskId || ''));
|
||||
return res.json({ success: true, data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({
|
||||
error: error?.code || 'server_error',
|
||||
error_description: error?.message || '读取加工单行失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/processing/demand/:taskId/pick', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await getWorkflowCtx(req);
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
/**
|
||||
* 独立加工单**完工**:申报成品(多行)→ 成品新批次回仓 → 损耗留痕 → 可选继承原料报告。
|
||||
*
|
||||
* 2026-10-23 开发者裁决(本轮已确认):
|
||||
* · 原料多行、成品多行(一个原料可产出多个成品);
|
||||
* · 损耗 = 原料投入合计 − 成品产出合计,**允许人工覆盖**(留痕),**不允许产出 > 投入**;
|
||||
* · 成品**新批次**入库,入库成本**默认按原料成本按产出数量均分**,允许人工按行设置;
|
||||
* · 损耗成本**只留痕、不进账本**(沿用 2026-10-15 裁决);
|
||||
* · 报告继承**可选**:库存批次报告 / 检验报告 各自勾选;原料没有报告就继承不到(不造空报告)。
|
||||
*
|
||||
* 见 docs/design/20261023-独立加工多产出与成品回仓.md
|
||||
*/
|
||||
import type { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { upsertInventoryHoldingCost } from './inventorySurplusCostService';
|
||||
|
||||
const PROCESS_STATUS_COMPLETED = 40;
|
||||
|
||||
function trimText(v: unknown): string {
|
||||
return String(v || '').trim();
|
||||
}
|
||||
function roundQty(n: number): number {
|
||||
return Math.round(n * 1000) / 1000;
|
||||
}
|
||||
function roundMoney(n: number): number {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
function currentCycleCode(): string {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export interface StandaloneOutputInput {
|
||||
skuCode: string;
|
||||
qty: number;
|
||||
/** 人工设置的单位成本;空 ⇒ 按原料成本均分 */
|
||||
unitCost?: number | null;
|
||||
/** 继承库存批次报告 */
|
||||
inheritBatchReport?: boolean;
|
||||
/** 继承检验报告(原料批次有检验记录时) */
|
||||
inheritInspectionReport?: boolean;
|
||||
}
|
||||
|
||||
export interface CompleteStandaloneProcessingInput {
|
||||
taskId: string;
|
||||
branchCode: string;
|
||||
outputs: StandaloneOutputInput[];
|
||||
/** 人工覆盖损耗;不填 ⇒ 自动差额 */
|
||||
lossQty?: number | null;
|
||||
operatorId?: string | null;
|
||||
}
|
||||
|
||||
export interface CompleteStandaloneProcessingResult {
|
||||
task_id: string;
|
||||
task_code: string;
|
||||
material_qty: number;
|
||||
material_cost: number;
|
||||
output_qty: number;
|
||||
loss_qty: number;
|
||||
/** 损耗是否人工覆盖 */
|
||||
loss_manual: boolean;
|
||||
outputs: Array<{
|
||||
id: string;
|
||||
sku_code: string;
|
||||
sku_name: string | null;
|
||||
qty: number;
|
||||
unit: string | null;
|
||||
unit_cost: number;
|
||||
cost_amount: number;
|
||||
batch_no: string;
|
||||
inherit_batch_report: boolean;
|
||||
inherit_inspection_report: boolean;
|
||||
}>;
|
||||
}
|
||||
|
||||
function businessError(message: string, code: string, status = 400) {
|
||||
return Object.assign(new Error(message), { status, code });
|
||||
}
|
||||
|
||||
export async function completeStandaloneProcessingTask(
|
||||
input: CompleteStandaloneProcessingInput
|
||||
): Promise<CompleteStandaloneProcessingResult> {
|
||||
const taskId = trimText(input.taskId);
|
||||
const branchCode = trimText(input.branchCode);
|
||||
if (!taskId) throw businessError('缺少加工单 id', 'invalid_request');
|
||||
if (!branchCode) throw businessError('请选择当前操作分公司', 'branch_required');
|
||||
|
||||
const rawOutputs = Array.isArray(input.outputs) ? input.outputs : [];
|
||||
if (!rawOutputs.length) throw businessError('请至少添加一行成品', 'invalid_request');
|
||||
const outputs = rawOutputs.map((row, idx) => {
|
||||
const skuCode = trimText(row?.skuCode);
|
||||
const qty = roundQty(Number(row?.qty));
|
||||
const unitCost =
|
||||
row?.unitCost == null || String(row.unitCost).trim() === '' ? null : Number(row.unitCost);
|
||||
if (!skuCode) throw businessError(`第 ${idx + 1} 行成品未选择商品`, 'invalid_request');
|
||||
if (!Number.isFinite(qty) || qty <= 0) throw businessError(`第 ${idx + 1} 行成品数量须大于 0`, 'invalid_request');
|
||||
if (unitCost != null && (!Number.isFinite(unitCost) || unitCost < 0)) {
|
||||
throw businessError(`第 ${idx + 1} 行成品成本价无效`, 'invalid_request');
|
||||
}
|
||||
return {
|
||||
skuCode,
|
||||
qty,
|
||||
unitCost: unitCost == null ? null : Math.round(unitCost * 10000) / 10000,
|
||||
inheritBatchReport: row?.inheritBatchReport === true,
|
||||
inheritInspectionReport: row?.inheritInspectionReport === true,
|
||||
};
|
||||
});
|
||||
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
const taskRes = await client.query<{
|
||||
id: string;
|
||||
task_code: string;
|
||||
source_type: string | null;
|
||||
process_status: number;
|
||||
branch_code: string | null;
|
||||
}>(
|
||||
`SELECT id, task_code, source_type, process_status, branch_code
|
||||
FROM processing_tasks WHERE id = $1 FOR UPDATE`,
|
||||
[taskId]
|
||||
);
|
||||
const task = taskRes.rows[0];
|
||||
if (!task) throw businessError('加工单不存在', 'not_found', 404);
|
||||
if (String(task.source_type || '') !== 'standalone') {
|
||||
throw businessError('只有独立加工单可以在这里申报成品', 'invalid_source');
|
||||
}
|
||||
if (String(task.branch_code || '') !== branchCode) {
|
||||
throw businessError('加工单不属于当前分公司', 'branch_mismatch', 403);
|
||||
}
|
||||
if (Number(task.process_status) >= PROCESS_STATUS_COMPLETED) {
|
||||
throw businessError('该加工单已完成,不能重复申报成品', 'already_completed');
|
||||
}
|
||||
const taskCode = String(task.task_code || '');
|
||||
|
||||
const materialRes = await client.query<{
|
||||
sku_code: string;
|
||||
sku_name: string | null;
|
||||
qty: string;
|
||||
material_cost: string;
|
||||
deducted_batches: unknown;
|
||||
}>(
|
||||
`SELECT sku_code, sku_name, qty, material_cost, deducted_batches
|
||||
FROM processing_task_materials WHERE task_id = $1 ORDER BY created_at ASC`,
|
||||
[taskId]
|
||||
);
|
||||
if (!materialRes.rowCount) {
|
||||
// 老单(改造前只存单据头,没有原料行)⇒ 用单据头兜底
|
||||
const header = await client.query<{ sku_code: string; source_qty: string; material_cost: string }>(
|
||||
`SELECT sku_code, COALESCE(material_qty, source_qty, 0) AS source_qty,
|
||||
COALESCE(material_cost, 0) AS material_cost
|
||||
FROM processing_tasks WHERE id = $1`,
|
||||
[taskId]
|
||||
);
|
||||
const h = header.rows[0];
|
||||
materialRes.rows.push({
|
||||
sku_code: String(h?.sku_code || ''),
|
||||
sku_name: null,
|
||||
qty: String(h?.source_qty || 0),
|
||||
material_cost: String(h?.material_cost || 0),
|
||||
deducted_batches: [],
|
||||
} as never);
|
||||
}
|
||||
|
||||
const materialQty = roundQty(
|
||||
materialRes.rows.reduce((sum, row) => sum + (Number(row.qty) || 0), 0)
|
||||
);
|
||||
const materialCost = roundMoney(
|
||||
materialRes.rows.reduce((sum, row) => sum + (Number(row.material_cost) || 0), 0)
|
||||
);
|
||||
const outputQty = roundQty(outputs.reduce((sum, row) => sum + row.qty, 0));
|
||||
if (outputQty > materialQty + 1e-6) {
|
||||
throw businessError(
|
||||
`产出合计(${outputQty})不能大于原料投入合计(${materialQty})`,
|
||||
'output_exceeds_input'
|
||||
);
|
||||
}
|
||||
const autoLoss = roundQty(materialQty - outputQty);
|
||||
const lossManual = input.lossQty != null && String(input.lossQty).trim() !== '';
|
||||
const lossQty = lossManual ? roundQty(Number(input.lossQty)) : autoLoss;
|
||||
if (!Number.isFinite(lossQty) || lossQty < -1e-6) {
|
||||
throw businessError('损耗数量不能为负数', 'invalid_loss');
|
||||
}
|
||||
if (outputQty + lossQty > materialQty + 1e-6) {
|
||||
throw businessError(
|
||||
`产出 + 损耗(${roundQty(outputQty + lossQty)})不能大于原料投入(${materialQty})`,
|
||||
'loss_over_input'
|
||||
);
|
||||
}
|
||||
|
||||
/** 默认成本:原料成本按**产出数量**均分(开发者:默认展示均分,可自行设置) */
|
||||
const defaultUnitCost = outputQty > 0 ? materialCost / outputQty : 0;
|
||||
|
||||
const inserted: CompleteStandaloneProcessingResult['outputs'] = [];
|
||||
const materialBatchNos = [
|
||||
...new Set(
|
||||
materialRes.rows.flatMap((row) => {
|
||||
const list = Array.isArray(row.deducted_batches) ? (row.deducted_batches as unknown[]) : [];
|
||||
return list
|
||||
.map((x) => trimText((x as { batch_no?: unknown })?.batch_no))
|
||||
.filter(Boolean);
|
||||
})
|
||||
),
|
||||
];
|
||||
const materialSkuCodes = [...new Set(materialRes.rows.map((r) => trimText(r.sku_code)).filter(Boolean))];
|
||||
|
||||
for (const [idx, output] of outputs.entries()) {
|
||||
const skuRes = await client.query<{ sku_code: string; sku_name: string | null; unit: string | null; spec: string | null }>(
|
||||
`SELECT sku_code, sku_name, unit, spec FROM skus WHERE sku_code = $1 LIMIT 1`,
|
||||
[output.skuCode]
|
||||
);
|
||||
if (!skuRes.rowCount) throw businessError(`第 ${idx + 1} 行成品商品不存在`, 'not_found', 404);
|
||||
const sku = skuRes.rows[0];
|
||||
const unitCost = output.unitCost == null ? Math.round(defaultUnitCost * 10000) / 10000 : output.unitCost;
|
||||
const costAmount = roundMoney(output.qty * unitCost);
|
||||
|
||||
// 新批次号:PG-<加工单号>-<行号>,撞号则加后缀(幂等重试也不复用旧批次)
|
||||
let batchNo = `PG-${taskCode}-${idx + 1}`;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
const exists = await client.query(`SELECT 1 FROM inventory WHERE batch_no = $1 LIMIT 1`, [batchNo]);
|
||||
if (!exists.rowCount) break;
|
||||
batchNo = `PG-${taskCode}-${idx + 1}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
}
|
||||
|
||||
const invRes = await client.query<{ id: string }>(
|
||||
`INSERT INTO inventory (
|
||||
batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status,
|
||||
branch_code, production_date, spec
|
||||
) VALUES ($1, $2, $3, $3, NULL, $4, 10, $5, NULL, NULLIF(TRIM($6), ''))
|
||||
RETURNING id`,
|
||||
[batchNo, output.skuCode, output.qty, unitCost, branchCode, String(sku.spec || '')]
|
||||
);
|
||||
const inventoryId = String(invRes.rows[0]?.id || '');
|
||||
|
||||
await client.query(
|
||||
`INSERT INTO inventory_logs (
|
||||
batch_no, sku_code, operation_type, quantity, before_qty, after_qty,
|
||||
related_order_code, operator_id, remark, branch_code
|
||||
) VALUES ($1, $2, 'processing_in', $3, 0, $3, NULL, $4, $5, $6)`,
|
||||
[batchNo, output.skuCode, output.qty, input.operatorId || null, `独立加工产出 ${taskCode}`, branchCode]
|
||||
);
|
||||
|
||||
// 库存持有成本(有货就得有值;与独立入库同一桶)
|
||||
await upsertInventoryHoldingCost(client, {
|
||||
cycleCode: currentCycleCode(),
|
||||
branchCode,
|
||||
skuCode: output.skuCode,
|
||||
amount: costAmount,
|
||||
referenceId: inventoryId,
|
||||
operatorId: input.operatorId || null,
|
||||
unitPrice: unitCost,
|
||||
surplusQty: output.qty,
|
||||
costSource: 'processing_output',
|
||||
referenceType: 'processing_output',
|
||||
costSubtype: 'processing_output',
|
||||
remarkPrefix: `独立加工产出 ${taskCode}`,
|
||||
});
|
||||
|
||||
/** 报告继承(可选):只复制**关联**,不复制报告本体 */
|
||||
let inheritedBatchReports = 0;
|
||||
let inheritedInspectionReports = 0;
|
||||
if (output.inheritBatchReport && materialBatchNos.length) {
|
||||
const reports = await client.query<{ report_id: string }>(
|
||||
`SELECT DISTINCT report_id FROM inventory_batch_report_matches
|
||||
WHERE batch_no = ANY($1::text[]) AND sku_code = ANY($2::text[])`,
|
||||
[materialBatchNos, materialSkuCodes]
|
||||
);
|
||||
for (const row of reports.rows) {
|
||||
await client.query(
|
||||
`INSERT INTO inventory_batch_report_matches
|
||||
(report_id, inventory_id, sku_code, product_name, batch_no, production_date, match_source, confirmed_at)
|
||||
VALUES ($1, $2, $3, $4, $5, NULL, 'inherit', NOW())
|
||||
ON CONFLICT DO NOTHING`,
|
||||
[row.report_id, inventoryId, output.skuCode, sku.sku_name || null, batchNo]
|
||||
);
|
||||
inheritedBatchReports += 1;
|
||||
}
|
||||
}
|
||||
if (output.inheritInspectionReport && materialBatchNos.length) {
|
||||
const photos = await client.query<{ photos: unknown }>(
|
||||
`SELECT inspection_photos AS photos FROM inspections
|
||||
WHERE inbound_batch_no = ANY($1::text[])
|
||||
AND COALESCE(array_length(inspection_photos, 1), 0) > 0`,
|
||||
[materialBatchNos]
|
||||
);
|
||||
const files = [
|
||||
...new Set(
|
||||
photos.rows.flatMap((r) => (Array.isArray(r.photos) ? r.photos.map((x) => String(x)) : []))
|
||||
),
|
||||
].filter(Boolean);
|
||||
if (files.length) {
|
||||
const reportRes = await client.query<{ id: string }>(
|
||||
`INSERT INTO inventory_batch_reports
|
||||
(branch_code, report_no, report_type, file_paths, product_names, status, uploaded_by, uploaded_at)
|
||||
VALUES ($1, $2, 'inspection_inherit', $3::text[], $4::text[], 20, $5, NOW())
|
||||
RETURNING id`,
|
||||
[branchCode, `INH-${taskCode}-${idx + 1}`, files, [String(sku.sku_name || '')], input.operatorId || null]
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO inventory_batch_report_matches
|
||||
(report_id, inventory_id, sku_code, product_name, batch_no, production_date, match_source, confirmed_at)
|
||||
VALUES ($1, $2, $3, $4, $5, NULL, 'inherit', NOW())
|
||||
ON CONFLICT DO NOTHING`,
|
||||
[reportRes.rows[0]?.id, inventoryId, output.skuCode, sku.sku_name || null, batchNo]
|
||||
);
|
||||
inheritedInspectionReports += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const outRes = await client.query<{ id: string }>(
|
||||
`INSERT INTO processing_task_outputs
|
||||
(task_id, sku_code, sku_name, spec, unit, qty, unit_cost, cost_amount, batch_no, inventory_id,
|
||||
inherit_batch_report, inherit_inspection_report)
|
||||
VALUES ($1, $2, $3, NULLIF(TRIM($4), ''), NULLIF(TRIM($5), ''), $6, $7, $8, $9, $10, $11, $12)
|
||||
RETURNING id`,
|
||||
[
|
||||
taskId,
|
||||
output.skuCode,
|
||||
sku.sku_name || null,
|
||||
String(sku.spec || ''),
|
||||
String(sku.unit || ''),
|
||||
output.qty,
|
||||
unitCost,
|
||||
costAmount,
|
||||
batchNo,
|
||||
inventoryId,
|
||||
output.inheritBatchReport,
|
||||
output.inheritInspectionReport,
|
||||
]
|
||||
);
|
||||
|
||||
inserted.push({
|
||||
id: String(outRes.rows[0]?.id || ''),
|
||||
sku_code: output.skuCode,
|
||||
sku_name: sku.sku_name || null,
|
||||
qty: output.qty,
|
||||
unit: sku.unit || null,
|
||||
unit_cost: unitCost,
|
||||
cost_amount: costAmount,
|
||||
batch_no: batchNo,
|
||||
inherit_batch_report: output.inheritBatchReport && inheritedBatchReports > 0,
|
||||
inherit_inspection_report: output.inheritInspectionReport && inheritedInspectionReports > 0,
|
||||
});
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`UPDATE processing_tasks
|
||||
SET process_status = $2,
|
||||
loss_qty = $3,
|
||||
gross_weight = $4,
|
||||
net_weight = $5,
|
||||
completed_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[taskId, PROCESS_STATUS_COMPLETED, lossQty, materialQty, outputQty]
|
||||
);
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
return {
|
||||
task_id: taskId,
|
||||
task_code: taskCode,
|
||||
material_qty: materialQty,
|
||||
material_cost: materialCost,
|
||||
output_qty: outputQty,
|
||||
loss_qty: lossQty,
|
||||
loss_manual: lossManual,
|
||||
outputs: inserted,
|
||||
};
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
/** 读侧:单据的原料行与成品行(详情/列表渲染用) */
|
||||
export async function listStandaloneMaterialsAndOutputs(taskId: string): Promise<{
|
||||
materials: Array<{ sku_code: string; sku_name: string | null; qty: number; material_cost: number }>;
|
||||
outputs: Array<{
|
||||
sku_code: string;
|
||||
sku_name: string | null;
|
||||
qty: number;
|
||||
unit: string | null;
|
||||
unit_cost: number;
|
||||
cost_amount: number;
|
||||
batch_no: string | null;
|
||||
inherit_batch_report: boolean;
|
||||
inherit_inspection_report: boolean;
|
||||
}>;
|
||||
}> {
|
||||
const id = trimText(taskId);
|
||||
if (!id) return { materials: [], outputs: [] };
|
||||
const [m, o] = await Promise.all([
|
||||
pool.query(
|
||||
`SELECT sku_code, sku_name, qty, material_cost FROM processing_task_materials
|
||||
WHERE task_id = $1 ORDER BY created_at ASC`,
|
||||
[id]
|
||||
),
|
||||
pool.query(
|
||||
`SELECT sku_code, sku_name, qty, unit, unit_cost, cost_amount, batch_no,
|
||||
inherit_batch_report, inherit_inspection_report
|
||||
FROM processing_task_outputs WHERE task_id = $1 ORDER BY created_at ASC`,
|
||||
[id]
|
||||
),
|
||||
]);
|
||||
return {
|
||||
materials: m.rows.map((r) => ({
|
||||
sku_code: String(r.sku_code),
|
||||
sku_name: r.sku_name ? String(r.sku_name) : null,
|
||||
qty: Number(r.qty) || 0,
|
||||
material_cost: Number(r.material_cost) || 0,
|
||||
})),
|
||||
outputs: o.rows.map((r) => ({
|
||||
sku_code: String(r.sku_code),
|
||||
sku_name: r.sku_name ? String(r.sku_name) : null,
|
||||
qty: Number(r.qty) || 0,
|
||||
unit: r.unit ? String(r.unit) : null,
|
||||
unit_cost: Number(r.unit_cost) || 0,
|
||||
cost_amount: Number(r.cost_amount) || 0,
|
||||
batch_no: r.batch_no ? String(r.batch_no) : null,
|
||||
inherit_batch_report: r.inherit_batch_report === true,
|
||||
inherit_inspection_report: r.inherit_inspection_report === true,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -29,15 +29,25 @@ function roundMoney(n: number): number {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
export interface CreateStandaloneProcessingInput {
|
||||
export interface StandaloneMaterialInput {
|
||||
skuCode: string;
|
||||
qty: number;
|
||||
}
|
||||
|
||||
export interface CreateStandaloneProcessingInput {
|
||||
/** 兼容旧调用:单原料。给了 `materials` 时忽略本字段 */
|
||||
skuCode?: string;
|
||||
qty?: number;
|
||||
/** **多行原料**(2026-10-23 开发者:原料可以多行) */
|
||||
materials?: StandaloneMaterialInput[];
|
||||
processingMethod: string;
|
||||
branchCode: string;
|
||||
/** 加工单价:仅记录,不入账 */
|
||||
processUnitPrice?: number | null;
|
||||
operatorId?: string | null;
|
||||
remark?: string | null;
|
||||
/** 幂等键:同一分公司 + 同一请求号只建一张单(客户端重试/双击) */
|
||||
clientRequestNo?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateStandaloneProcessingResult {
|
||||
@@ -45,6 +55,8 @@ export interface CreateStandaloneProcessingResult {
|
||||
task_code: string;
|
||||
sku_code: string;
|
||||
sku_name: string | null;
|
||||
/** 多行原料的逐行结果(金额按各行实际扣减批次成本汇总) */
|
||||
materials?: Array<{ sku_code: string; sku_name: string | null; qty: number; material_cost: number }>;
|
||||
processing_method: string;
|
||||
source_qty: number;
|
||||
material_qty: number;
|
||||
@@ -58,30 +70,47 @@ export interface CreateStandaloneProcessingResult {
|
||||
export async function createStandaloneProcessingTask(
|
||||
input: CreateStandaloneProcessingInput
|
||||
): Promise<CreateStandaloneProcessingResult> {
|
||||
const skuCode = trimText(input.skuCode);
|
||||
const branchCode = trimText(input.branchCode);
|
||||
const processingMethod = trimText(input.processingMethod);
|
||||
const qty = roundQty(Number(input.qty));
|
||||
const unitPrice =
|
||||
input.processUnitPrice == null
|
||||
? null
|
||||
: roundMoney(Number(input.processUnitPrice));
|
||||
input.processUnitPrice == null ? null : roundMoney(Number(input.processUnitPrice));
|
||||
const clientRequestNo = trimText(input.clientRequestNo) || null;
|
||||
if (unitPrice != null && (unitPrice < 0 || !Number.isFinite(unitPrice))) {
|
||||
throw Object.assign(new Error('加工单价不能为负数'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
|
||||
if (!skuCode) {
|
||||
throw Object.assign(new Error('请选择商品'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!branchCode) {
|
||||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||||
}
|
||||
if (!processingMethod) {
|
||||
throw Object.assign(new Error('请选择加工方式'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!Number.isFinite(qty) || qty <= 0) {
|
||||
throw Object.assign(new Error('数量须大于 0'), { status: 400, code: 'invalid_request' });
|
||||
|
||||
/**
|
||||
* **多行原料**归一化(2026-10-23 开发者:「原料可以多行」):
|
||||
* 老调用(只给 skuCode+qty)仍按单行处理 ⇒ 旧接口/小程序老版本不受影响。
|
||||
* 同一 SKU 重复出现时合并成一行(避免同一商品被重复校验/重复记录,扣减仍是一次 FIFO)。
|
||||
*/
|
||||
const rawMaterials =
|
||||
Array.isArray(input.materials) && input.materials.length
|
||||
? input.materials
|
||||
: [{ skuCode: input.skuCode, qty: input.qty }];
|
||||
const merged = new Map<string, number>();
|
||||
for (const [idx, row] of rawMaterials.entries()) {
|
||||
const code = trimText(row?.skuCode);
|
||||
const qty = roundQty(Number(row?.qty));
|
||||
if (!code) {
|
||||
throw Object.assign(new Error(`第 ${idx + 1} 行原料未选择商品`), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!Number.isFinite(qty) || qty <= 0) {
|
||||
throw Object.assign(new Error(`第 ${idx + 1} 行原料数量须大于 0`), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
merged.set(code, roundQty((merged.get(code) || 0) + qty));
|
||||
}
|
||||
if (!merged.size) {
|
||||
throw Object.assign(new Error('请至少添加一行原料'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
const materials = [...merged.entries()].map(([skuCode, qty]) => ({ skuCode, qty }));
|
||||
const totalQty = roundQty(materials.reduce((sum, m) => sum + m.qty, 0));
|
||||
|
||||
try {
|
||||
await healOrphanIndependentInboundsAfterPass(branchCode);
|
||||
@@ -93,27 +122,48 @@ export async function createStandaloneProcessingTask(
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
const skuRow = await client.query(
|
||||
`SELECT sku_code, sku_name, unit FROM skus WHERE sku_code = $1 LIMIT 1`,
|
||||
[skuCode]
|
||||
);
|
||||
if (!skuRow.rowCount) {
|
||||
throw Object.assign(new Error('商品不存在'), { status: 404, code: 'not_found' });
|
||||
}
|
||||
const skuName = String(skuRow.rows[0]?.sku_name || '');
|
||||
|
||||
// 与需求单领料同口径:只能领「毛可用 − 全部在用预留」
|
||||
// 见 docs/design/20260922-processing-pick-respect-reservations.md
|
||||
const availableQty = await getClaimableStockQty(client, skuCode, branchCode, null);
|
||||
if (availableQty + 1e-9 < qty) {
|
||||
throw Object.assign(
|
||||
new Error(`库存不足:可用 ${availableQty},需要 ${qty}`),
|
||||
{ status: 400, code: 'insufficient_stock' }
|
||||
/** 幂等:同一分公司 + 同一请求号 → 直接返回上次建好的单(不重复扣库存) */
|
||||
if (clientRequestNo) {
|
||||
const existing = await client.query(
|
||||
`SELECT id, task_code, processing_method, source_qty, material_qty, material_cost,
|
||||
process_unit_price, process_status, branch_code, created_at
|
||||
FROM processing_tasks
|
||||
WHERE branch_code = $1 AND client_request_no = $2
|
||||
LIMIT 1`,
|
||||
[branchCode, clientRequestNo]
|
||||
);
|
||||
if (existing.rowCount) {
|
||||
const row = existing.rows[0];
|
||||
const mats = await client.query(
|
||||
`SELECT sku_code, sku_name, qty, material_cost
|
||||
FROM processing_task_materials WHERE task_id = $1 ORDER BY created_at ASC`,
|
||||
[row.id]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return {
|
||||
id: String(row.id),
|
||||
task_code: String(row.task_code || ''),
|
||||
sku_code: String(mats.rows[0]?.sku_code || ''),
|
||||
sku_name: mats.rows[0]?.sku_name ? String(mats.rows[0].sku_name) : null,
|
||||
materials: mats.rows.map((m) => ({
|
||||
sku_code: String(m.sku_code),
|
||||
sku_name: m.sku_name ? String(m.sku_name) : null,
|
||||
qty: Number(m.qty) || 0,
|
||||
material_cost: Number(m.material_cost) || 0,
|
||||
})),
|
||||
processing_method: String(row.processing_method || ''),
|
||||
source_qty: Number(row.source_qty) || 0,
|
||||
material_qty: Number(row.material_qty) || 0,
|
||||
material_cost: Number(row.material_cost) || 0,
|
||||
process_unit_price: row.process_unit_price == null ? null : Number(row.process_unit_price),
|
||||
process_status: Number(row.process_status) || PROCESS_STATUS.pending,
|
||||
branch_code: String(row.branch_code || branchCode),
|
||||
created_at: row.created_at ? new Date(row.created_at).toISOString() : new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// task_code 为 MAX+1 取号,同日并发会撞唯一索引:SAVEPOINT + 换号重试
|
||||
// (事务内普通 catch 后连接已 aborted,必须回滚到保存点)
|
||||
let taskId = '';
|
||||
let taskCodeReturn = '';
|
||||
let lastErr: unknown = null;
|
||||
@@ -124,10 +174,21 @@ export async function createStandaloneProcessingTask(
|
||||
const taskResult = await client.query(
|
||||
`INSERT INTO processing_tasks (
|
||||
order_code, inspection_id, task_code, source_type, sku_code, processing_method,
|
||||
source_qty, process_status, branch_code, process_unit_price, remark, created_at, updated_at
|
||||
) VALUES (NULL, NULL, $1, 'standalone', $2, $3, $4, $5, $6, $7, $8, NOW(), NOW())
|
||||
source_qty, process_status, branch_code, process_unit_price, remark,
|
||||
client_request_no, created_at, updated_at
|
||||
) VALUES (NULL, NULL, $1, 'standalone', $2, $3, $4, $5, $6, $7, $8, $9, NOW(), NOW())
|
||||
RETURNING id, task_code`,
|
||||
[taskCode, skuCode, processingMethod, qty, PROCESS_STATUS.pending, branchCode, unitPrice, trimText(input.remark) || null]
|
||||
[
|
||||
taskCode,
|
||||
materials[0].skuCode,
|
||||
processingMethod,
|
||||
totalQty,
|
||||
PROCESS_STATUS.pending,
|
||||
branchCode,
|
||||
unitPrice,
|
||||
trimText(input.remark) || null,
|
||||
clientRequestNo,
|
||||
]
|
||||
);
|
||||
await client.query('RELEASE SAVEPOINT standalone_task_insert');
|
||||
taskId = String(taskResult.rows[0].id);
|
||||
@@ -140,61 +201,102 @@ export async function createStandaloneProcessingTask(
|
||||
}
|
||||
if (!taskId) throw lastErr;
|
||||
|
||||
// 扣库存,同时采集批次成本
|
||||
const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = [];
|
||||
await fifoDeductInventory(
|
||||
client,
|
||||
{
|
||||
skuCode,
|
||||
qty,
|
||||
branchCode,
|
||||
orderCode: null,
|
||||
pickCode: taskCodeReturn,
|
||||
operatorId: input.operatorId || null,
|
||||
itemName: skuName,
|
||||
operationType: 'processing_out',
|
||||
remark: `独立加工领料 ${taskCodeReturn}`,
|
||||
},
|
||||
(batch, deductedQty) => {
|
||||
deductedBatches.push({ ...batch, deductedQty });
|
||||
/** 逐行领料:校验可用量 → FIFO 扣减 → 落原料行 → 汇总材料成本 */
|
||||
const materialRows: Array<{ sku_code: string; sku_name: string | null; qty: number; material_cost: number }> = [];
|
||||
let totalMaterialCost = 0;
|
||||
for (const [idx, material] of materials.entries()) {
|
||||
const skuRow = await client.query(`SELECT sku_code, sku_name, unit FROM skus WHERE sku_code = $1 LIMIT 1`, [
|
||||
material.skuCode,
|
||||
]);
|
||||
if (!skuRow.rowCount) {
|
||||
throw Object.assign(new Error(`第 ${idx + 1} 行原料商品不存在`), { status: 404, code: 'not_found' });
|
||||
}
|
||||
const skuName = String(skuRow.rows[0]?.sku_name || '');
|
||||
// 与需求单领料同口径:只能领「毛可用 − 全部在用预留」
|
||||
const availableQty = await getClaimableStockQty(client, material.skuCode, branchCode, null);
|
||||
if (availableQty + 1e-9 < material.qty) {
|
||||
throw Object.assign(
|
||||
new Error(`第 ${idx + 1} 行(${skuName || material.skuCode})库存不足:可用 ${availableQty},需要 ${material.qty}`),
|
||||
{ status: 400, code: 'insufficient_stock' }
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
const materialCost = roundMoney(
|
||||
deductedBatches.reduce((sum, b) => sum + b.deductedQty * b.costPrice, 0)
|
||||
);
|
||||
const costBatches: InventoryDeductBatch[] = deductedBatches.map((b) => ({
|
||||
batchNo: b.batchNo,
|
||||
deductedQty: b.deductedQty,
|
||||
costPrice: b.costPrice,
|
||||
}));
|
||||
const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = [];
|
||||
await fifoDeductInventory(
|
||||
client,
|
||||
{
|
||||
skuCode: material.skuCode,
|
||||
qty: material.qty,
|
||||
branchCode,
|
||||
orderCode: null,
|
||||
pickCode: taskCodeReturn,
|
||||
operatorId: input.operatorId || null,
|
||||
itemName: skuName,
|
||||
operationType: 'processing_out',
|
||||
remark: `独立加工领料 ${taskCodeReturn}`,
|
||||
},
|
||||
(batch, deductedQty) => {
|
||||
deductedBatches.push({ ...batch, deductedQty });
|
||||
}
|
||||
);
|
||||
|
||||
const lineCost = roundMoney(deductedBatches.reduce((sum, b) => sum + b.deductedQty * b.costPrice, 0));
|
||||
totalMaterialCost = roundMoney(totalMaterialCost + lineCost);
|
||||
await client.query(
|
||||
`INSERT INTO processing_task_materials
|
||||
(task_id, sku_code, sku_name, spec, unit, qty, material_cost, deducted_batches)
|
||||
VALUES ($1, $2, $3, NULLIF(TRIM($4), ''), NULLIF(TRIM($5), ''), $6, $7, $8::jsonb)`,
|
||||
[
|
||||
taskId,
|
||||
material.skuCode,
|
||||
skuName || null,
|
||||
String(skuRow.rows[0]?.spec || ''),
|
||||
String(skuRow.rows[0]?.unit || ''),
|
||||
material.qty,
|
||||
lineCost,
|
||||
JSON.stringify(
|
||||
deductedBatches.map((b) => ({
|
||||
batch_no: b.batchNo,
|
||||
qty: b.deductedQty,
|
||||
cost_price: b.costPrice,
|
||||
}))
|
||||
),
|
||||
]
|
||||
);
|
||||
materialRows.push({ sku_code: material.skuCode, sku_name: skuName || null, qty: material.qty, material_cost: lineCost });
|
||||
|
||||
const costBatches: InventoryDeductBatch[] = deductedBatches.map((b) => ({
|
||||
batchNo: b.batchNo,
|
||||
deductedQty: b.deductedQty,
|
||||
costPrice: b.costPrice,
|
||||
}));
|
||||
await postProcessingStandaloneMaterialCost(client, {
|
||||
taskId,
|
||||
skuCode: material.skuCode,
|
||||
branchCode,
|
||||
materialCost: lineCost,
|
||||
deductedBatches: costBatches,
|
||||
operatorId: input.operatorId || null,
|
||||
});
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`UPDATE processing_tasks
|
||||
SET material_qty = $2, material_cost = $3
|
||||
WHERE id = $1`,
|
||||
[taskId, qty, materialCost]
|
||||
`UPDATE processing_tasks SET material_qty = $2, material_cost = $3 WHERE id = $1`,
|
||||
[taskId, totalQty, totalMaterialCost]
|
||||
);
|
||||
|
||||
await postProcessingStandaloneMaterialCost(client, {
|
||||
taskId,
|
||||
skuCode,
|
||||
branchCode,
|
||||
materialCost,
|
||||
deductedBatches: costBatches,
|
||||
operatorId: input.operatorId || null,
|
||||
});
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
return {
|
||||
id: taskId,
|
||||
task_code: taskCodeReturn,
|
||||
sku_code: skuCode,
|
||||
sku_name: skuName || null,
|
||||
sku_code: materials[0].skuCode,
|
||||
sku_name: materialRows[0]?.sku_name ?? null,
|
||||
materials: materialRows,
|
||||
processing_method: processingMethod,
|
||||
source_qty: qty,
|
||||
material_qty: qty,
|
||||
material_cost: materialCost,
|
||||
source_qty: totalQty,
|
||||
material_qty: totalQty,
|
||||
material_cost: totalMaterialCost,
|
||||
process_unit_price: unitPrice,
|
||||
process_status: PROCESS_STATUS.pending,
|
||||
branch_code: branchCode,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* 独立加工 P0 契约(2026-10-23 开发者裁决):
|
||||
* 原料多行 / 成品多行 / 损耗自动差额可人工覆盖 / 成品新批次回仓 / 成本默认均分可人工设置 /
|
||||
* 损耗只留痕不进账本 / 报告继承可选 / 幂等请求号 / 老调用(单原料)不回归。
|
||||
*
|
||||
* 这里只钉**行为契约**(源码级),真实数据路径由 dev 库端到端验证(见设计文档 §5 证据)。
|
||||
*/
|
||||
const createSvc = readFileSync(new URL('../src/services/processingStandaloneService.ts', import.meta.url), 'utf8');
|
||||
const outSvc = readFileSync(new URL('../src/services/processingStandaloneOutputService.ts', import.meta.url), 'utf8');
|
||||
const routes = readFileSync(
|
||||
new URL('../src/modules/workflow/routes/inspectionRoutes.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('创建:多行原料 + 幂等', () => {
|
||||
it('支持 materials 多行,且老调用(skuCode+qty)仍按单行处理', () => {
|
||||
expect(createSvc).toContain('Array.isArray(input.materials) && input.materials.length');
|
||||
expect(createSvc).toContain('[{ skuCode: input.skuCode, qty: input.qty }]');
|
||||
expect(createSvc).toContain('merged.set(code, roundQty((merged.get(code) || 0) + qty))');
|
||||
});
|
||||
|
||||
it('逐行校验可用量与 FIFO 扣减(每行独立)', () => {
|
||||
expect(createSvc).toContain('for (const [idx, material] of materials.entries())');
|
||||
expect(createSvc).toContain('getClaimableStockQty(client, material.skuCode, branchCode, null)');
|
||||
expect(createSvc).toContain("operationType: 'processing_out'");
|
||||
});
|
||||
|
||||
it('幂等:同分公司 + 同请求号直接返回既有单,不重复扣库存', () => {
|
||||
expect(createSvc).toContain('WHERE branch_code = $1 AND client_request_no = $2');
|
||||
expect(createSvc).toContain('client_request_no');
|
||||
});
|
||||
|
||||
it('原料行落库含抵减批次 JSON(报告继承与对账要用)', () => {
|
||||
expect(createSvc).toContain('deducted_batches');
|
||||
expect(createSvc).toContain('JSON.stringify(');
|
||||
});
|
||||
});
|
||||
|
||||
describe('完工:成品回仓 / 损耗 / 成本 / 报告继承', () => {
|
||||
it('产出 > 投入 一律拒绝', () => {
|
||||
expect(outSvc).toContain("'output_exceeds_input'");
|
||||
expect(outSvc).toContain('不能大于原料投入合计');
|
||||
});
|
||||
|
||||
it('损耗默认自动差额,允许人工覆盖并留痕(loss_manual)', () => {
|
||||
expect(outSvc).toContain('const autoLoss = roundQty(materialQty - outputQty)');
|
||||
expect(outSvc).toContain('loss_manual: lossManual');
|
||||
});
|
||||
|
||||
it('产出+损耗 不得大于投入', () => {
|
||||
expect(outSvc).toContain("'loss_over_input'");
|
||||
});
|
||||
|
||||
it('成品新批次入库 + 加工入库流水(processing_in)', () => {
|
||||
expect(outSvc).toContain('PG-${taskCode}-${idx + 1}');
|
||||
expect(outSvc).toContain("'processing_in'");
|
||||
expect(outSvc).toContain('INSERT INTO inventory (');
|
||||
});
|
||||
|
||||
it('成本默认按产出数量均分,允许人工 unitCost 覆盖', () => {
|
||||
expect(outSvc).toContain('const defaultUnitCost = outputQty > 0 ? materialCost / outputQty : 0');
|
||||
expect(outSvc).toContain('output.unitCost == null ? Math.round(defaultUnitCost');
|
||||
});
|
||||
|
||||
it('成品入库同时写库存持有成本(不写采购成本,损耗不新开账本行)', () => {
|
||||
expect(outSvc).toContain('upsertInventoryHoldingCost');
|
||||
expect(outSvc).toContain("costSource: 'processing_output'");
|
||||
expect(outSvc).not.toContain('purchase');
|
||||
});
|
||||
|
||||
it('批次报告继承:只复制关联(match_source=inherit),不新增报告行', () => {
|
||||
expect(outSvc).toContain("'inherit'");
|
||||
expect(outSvc).toContain('inventory_batch_report_matches');
|
||||
// 批次报告路径里不允许出现"新建报告本体"的插入(报告本体共享)
|
||||
const batchBlock = outSvc.slice(
|
||||
outSvc.indexOf('if (output.inheritBatchReport'),
|
||||
outSvc.indexOf('if (output.inheritInspectionReport')
|
||||
);
|
||||
expect(batchBlock).not.toContain('INSERT INTO inventory_batch_reports');
|
||||
});
|
||||
|
||||
it('检验报告继承:原料批次有检验照片时,新建一条「继承」报告并挂到成品批次', () => {
|
||||
const inspectBlock = outSvc.slice(outSvc.indexOf('if (output.inheritInspectionReport'));
|
||||
expect(inspectBlock).toContain("report_type, file_paths");
|
||||
expect(inspectBlock).toContain("'inspection_inherit'");
|
||||
expect(inspectBlock).toContain('inspection_photos');
|
||||
});
|
||||
|
||||
it('已完成单不能重复申报', () => {
|
||||
expect(outSvc).toContain("'already_completed'");
|
||||
});
|
||||
});
|
||||
|
||||
describe('路由:多行原料入参 + 完工 + 行查询', () => {
|
||||
it('create 接受 materials 与 client_request_no', () => {
|
||||
expect(routes).toContain('req.body?.materials');
|
||||
expect(routes).toContain('clientRequestNo');
|
||||
});
|
||||
it('新增完工与行查询路由', () => {
|
||||
expect(routes).toContain("/processing/standalone/:taskId/complete");
|
||||
expect(routes).toContain("/processing/standalone/:taskId/lines");
|
||||
});
|
||||
});
|
||||
@@ -2024,11 +2024,16 @@ export async function deleteOrphanDemandSheetApi(taskId: string) {
|
||||
}
|
||||
|
||||
export async function createStandaloneProcessingTaskApi(body: {
|
||||
sku_code: string;
|
||||
qty: number;
|
||||
/** 兼容旧调用(单原料);多行原料用 materials */
|
||||
sku_code?: string;
|
||||
qty?: number;
|
||||
/** **多行原料**(2026-10-23):[{sku_code, qty}] */
|
||||
materials?: Array<{ sku_code: string; qty: number }>;
|
||||
processing_method: string;
|
||||
process_unit_price?: number | null;
|
||||
remark?: string;
|
||||
/** 幂等键:客户端重试/双击时同一请求号只建一张单 */
|
||||
client_request_no?: string;
|
||||
}) {
|
||||
return workflowFetch<{ success: boolean; data: ProcessingTaskRow }>('/processing/standalone/create', {
|
||||
method: 'POST',
|
||||
@@ -2036,6 +2041,72 @@ export async function createStandaloneProcessingTaskApi(body: {
|
||||
});
|
||||
}
|
||||
|
||||
/** 独立加工**完工**:申报成品(多行)→ 成品新批次回仓 → 损耗留痕 → 可选继承原料报告 */
|
||||
export async function completeStandaloneProcessingTaskApi(
|
||||
taskId: string,
|
||||
body: {
|
||||
outputs: Array<{
|
||||
sku_code: string;
|
||||
qty: number;
|
||||
/** 空 ⇒ 按原料成本均分 */
|
||||
unit_cost?: number | null;
|
||||
inherit_batch_report?: boolean;
|
||||
inherit_inspection_report?: boolean;
|
||||
}>;
|
||||
/** 不填 ⇒ 自动差额(原料投入 − 成品产出) */
|
||||
loss_qty?: number | null;
|
||||
}
|
||||
) {
|
||||
return workflowFetch<{
|
||||
success: boolean;
|
||||
data: {
|
||||
task_id: string;
|
||||
task_code: string;
|
||||
material_qty: number;
|
||||
material_cost: number;
|
||||
output_qty: number;
|
||||
loss_qty: number;
|
||||
loss_manual: boolean;
|
||||
outputs: Array<{
|
||||
id: string;
|
||||
sku_code: string;
|
||||
sku_name: string | null;
|
||||
qty: number;
|
||||
unit: string | null;
|
||||
unit_cost: number;
|
||||
cost_amount: number;
|
||||
batch_no: string;
|
||||
inherit_batch_report: boolean;
|
||||
inherit_inspection_report: boolean;
|
||||
}>;
|
||||
};
|
||||
}>(`/processing/standalone/${encodeURIComponent(taskId)}/complete`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
/** 独立加工单的原料行 / 成品行 */
|
||||
export async function listStandaloneLinesApi(taskId: string) {
|
||||
return workflowFetch<{
|
||||
success: boolean;
|
||||
data: {
|
||||
materials: Array<{ sku_code: string; sku_name: string | null; qty: number; material_cost: number }>;
|
||||
outputs: Array<{
|
||||
sku_code: string;
|
||||
sku_name: string | null;
|
||||
qty: number;
|
||||
unit: string | null;
|
||||
unit_cost: number;
|
||||
cost_amount: number;
|
||||
batch_no: string | null;
|
||||
inherit_batch_report: boolean;
|
||||
inherit_inspection_report: boolean;
|
||||
}>;
|
||||
};
|
||||
}>(`/processing/standalone/${encodeURIComponent(taskId)}/lines`);
|
||||
}
|
||||
|
||||
export async function listProcessingTasksApi(
|
||||
tab: 'work' | 'inspect' | 'done' = 'work',
|
||||
options?: {
|
||||
|
||||
Reference in New Issue
Block a user