From e54c2c7ec19d02c701b2e86557e5b88edbdbc7d2 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Sat, 10 Oct 2026 13:59:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=AE=A2=E5=8D=95=E5=88=97=E8=A1=A8):=20?= =?UTF-8?q?=E4=B8=BB=E7=B3=BB=E7=BB=9F=E5=88=86=E9=85=8D=E5=8D=95=E5=8A=A0?= =?UTF-8?q?=E3=80=8C=E5=BA=93=E5=AD=98=E6=8A=B5=E6=89=A3=E3=80=8D=E5=B0=8F?= =?UTF-8?q?=E6=8C=89=E9=92=AE=EF=BC=88=E8=A1=A5=E5=BD=95=E5=BA=93=E5=AD=98?= =?UTF-8?q?=E5=90=8E=E9=87=8D=E8=B7=91=E6=8A=B5=E6=89=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 开发者原话:「这块分配来的订单补一个小按钮『库存抵扣』,点击后走库存抵扣的路线。应对就是我的订单 已经分配过来了,但是**库存忘记上新了**这种情况 —— 因为库存抵扣在分配过来、创建订单时就执行过了。」 问题:库存抵扣只在**分配那一刻**跑(`reprocessOrderAllocation` 内的 `applyStockCoverForOrder`); 主系统单导入/分配时若库存还没上新 ⇒ 抵扣 0、缺口全转采购,事后补库存没有任何入口重跑。 做法(不新造抵扣逻辑,复用既有分配路线): · 服务:`orderAllocationService.applyInventoryOffsetForMainSystemOrder()` —— 只允许**主系统分配过来的单** (台账 `main_system_order_imports` 有对照)、状态 `< 50`(配送/出库阶段拒绝)、 然后调用既有 `reprocessOrderAllocation`(行锁 + 事务 + 幂等,并按新抵扣**重规划采购/备货**); 返回抵扣增量与可展示文案(`本次新增抵扣 N` / `当前库存没有可新抵扣的量`)。 ⚠️ 逻辑放 service 而非路由:路由层不得内嵌 SQL(`routeLayerBoundary.test.ts` 棘轮), 且不能只调 `applyStockCoverForOrder`(那会留下"既抵扣又采购"的双记)。 · 路由:`POST /orders/:orderCode/inventory-offset`(薄壳,权限 allocation_manage/order_manage/order_edit)。 · 界面:订单管理列表行操作区加小按钮「库存抵扣」(中/英/印尼),只在 `is_main_system_order === true && order_status < 50` 时出现,带在途锁,成功后刷新列表 (列表本身会显示「库存抵扣:…」提示)。 真库端到端(跑完已还原:删除探针库存行 + 重跑抵扣 ⇒ 抵扣量回 0、活动预留 0、无残留库存行): ① 无库存时点一次 ⇒ 200「当前库存没有可新抵扣的量」(幂等无副作用) ② 给「苹果」补 10 斤库存后再点 ⇒ 200「本次新增抵扣 10」,该行 stock_cover_qty 0 → 10, 并生成 `inventory_reservations`(qty 10 / status 10),采购需求按新抵扣重规划。 测试:新增 `server/tests/inventoryOffsetButton.test.ts`(5 条)+ 设计文档 §7.1; 服务端全量失败集与基线**逐文件一致(24,零新增)**;前端 142 文件 / 707 用例全绿;门禁同基线。 --- ...261009-供应商侧库存抵扣与免入库推进方案.md | 23 +++++ .../modules/workflow/routes/orderRoutes.ts | 60 ++++++++++++- server/src/services/orderAllocationService.ts | 71 +++++++++++++++ server/tests/inventoryOffsetButton.test.ts | 89 +++++++++++++++++++ src/i18n/locales/en/orders.ts | 3 + src/i18n/locales/id/orders.ts | 3 + src/i18n/locales/zh-CN/orders.ts | 3 + .../orderManagement/OrderManagementPage.tsx | 36 ++++++++ src/utils/workflowApi.ts | 23 +++++ 9 files changed, 310 insertions(+), 1 deletion(-) create mode 100644 server/tests/inventoryOffsetButton.test.ts diff --git a/docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md b/docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md index 02ba07e..b34a609 100644 --- a/docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md +++ b/docs/design/20261009-供应商侧库存抵扣与免入库推进方案.md @@ -105,6 +105,29 @@ 分拣完成时订单在 45 ⇒ 必须先走既有边 **45→50 再结案**(已按此实现;直接传 45 会报「订单当前状态 45,不能按商品直送结案」)。 另发现 `completePickingOutbound` 收尾**无条件**建配送任务,会给已结案订单留孤儿任务 ⇒ 加了 `>= 90` 守卫(本方案 §3.2 附带修复)。 +## 7.1 手动补一次「库存抵扣」(2026-10-10 开发者要求) + +> 开发者原话:「这块分配来的订单补一个小按钮『库存抵扣』,点击后走库存抵扣的路线。 +> 应对就是我的订单已经分配过来了,但是**库存忘记上新了**这种情况 —— +> 因为库存抵扣在分配过来、创建订单时就执行过了。」 + +**问题**:库存抵扣只在**分配那一刻**跑(`reprocessOrderAllocation` 内的 `applyStockCoverForOrder`)。 +主系统订单在导入/分配时如果**库存还没上新**(忘记录入库),抵扣就是 0,缺口全部转了采购; +事后补了库存也没有任何入口重跑,只能等下一次批量重新分配。 + +**做法**(不新造抵扣逻辑,直接复用既有分配路线): + +| 层 | 落点 | +|---|---| +| 后端 | 新路由 `POST /orders/:orderCode/inventory-offset`:权限 `allocation_manage / order_manage / order_edit`;只允许**主系统分配过来的单**(台账 `main_system_order_imports` 有对照);状态窗口 `< 50`(发车/配送中已扣库,拒绝);然后调用**既有** `reprocessOrderAllocation(orderCode, customerCode, branchCode)`(行锁 + 幂等 + 重规划采购/备货:抵扣掉的部分会把先前生成的采购需求收掉) | +| 前端 | 订单管理列表行操作区新增小按钮「**库存抵扣**」,只在 `is_main_system_order && order_status < 50` 时出现;带在途锁(同 `historicalFinalizingCode` 的做法),成功后刷新列表(列表本就会显示「库存抵扣:…」提示) | + +**为什么不直接调 `applyStockCoverForOrder`**:那只会改 `stock_cover_qty`/预留,**不会收掉**当初按缺口生成的采购单与备货行 +⇒ 会出现"既抵扣又采购"的双记。`reprocessOrderAllocation` 是分配的唯一正规路线,重跑幂等且会重规划缺口。 + +**幂等与安全**:`reprocessOrderAllocation` 自身行锁 + 事务 + 幂等检查;已入库/已拣货的行由 +`loadLockedStockCoverIfInboundOrPicking` 守住(不会被二次抵扣或清零)。重复点击不会翻倍。 + ## 8. 遗留 - 主系统侧那条同源缺陷(`tryAdvanceOrderToInspection` 过宽判据)**他们也已核实成立**,列为"另案"; diff --git a/server/src/modules/workflow/routes/orderRoutes.ts b/server/src/modules/workflow/routes/orderRoutes.ts index ed65ac8..4e1429b 100644 --- a/server/src/modules/workflow/routes/orderRoutes.ts +++ b/server/src/modules/workflow/routes/orderRoutes.ts @@ -73,7 +73,7 @@ import { isNowWithinOrderSubmitWindow, setOrderSubmitWindowConfig, } from '../../../services/orderSubmitWindowConfigService'; -import { reprocessOrderAllocation } from '../../../services/orderAllocationService'; +import { applyInventoryOffsetForMainSystemOrder, reprocessOrderAllocation } from '../../../services/orderAllocationService'; import { getAllocationRulesConfig, setAllocationRulesConfig, @@ -639,6 +639,64 @@ router.patch('/orders/:orderCode/delivery-address', authMiddleware, async (req: } }); +/** + * 手动补一次「**库存抵扣**」(2026-10-10 开发者要求)。 + * + * 场景:「主系统分配过来的订单,**库存忘记上新了**」—— 库存抵扣只在分配那一刻跑过 + * (`reprocessOrderAllocation` 内的 `applyStockCoverForOrder`),当时没库存 ⇒ 抵扣 0、缺口全转采购; + * 事后补录库存却没有任何入口重跑。本路由就是那个入口。 + * + * 逻辑全在 `orderAllocationService.applyInventoryOffsetForMainSystemOrder`(路由层不得内嵌 SQL): + * 只给主系统分配单用、配送阶段(>=50)拒绝、复用既有分配路线(行锁 + 幂等 + 重规划采购/备货)。 + */ +router.post('/orders/:orderCode/inventory-offset', authMiddleware, async (req: AuthRequest, res: Response) => { + try { + const ctx = await getWorkflowCtx(req); + requireWorkflowPermission(ctx, ['allocation_manage', 'order_manage', 'order_edit']); + const orderCode = String(req.params.orderCode || '').trim(); + if (!orderCode) { + return res.status(400).json({ error: 'invalid_request', error_description: '缺少订单号' }); + } + const order = await assertOrderCodeAccess(orderCode, ctx!); + const branchCode = order.branch_code || getEffectiveBranchCode(ctx, readOperatingBranchCode(req)) || ''; + const outcome = await applyInventoryOffsetForMainSystemOrder({ + orderCode, + customerCode: order.customer_code ?? null, + branchCode, + orderStatus: Number(order.order_status) || 0, + }); + if (outcome.kind === 'not_main_system_order') { + return res.status(400).json({ + error: 'not_main_system_order', + error_description: '该订单不是主系统分配过来的,无需手动库存抵扣', + }); + } + if (outcome.kind === 'too_late') { + return res.status(409).json({ + error: 'inventory_offset_too_late', + error_description: `订单已进入配送/出库阶段(状态 ${outcome.status}),不能再重跑库存抵扣`, + }); + } + if (outcome.kind === 'invalid') { + return res.status(400).json({ error: 'invalid_request', error_description: outcome.reason }); + } + return res.json({ + data: { + ...outcome.allocation, + coveredBefore: outcome.coveredBefore, + coveredAfter: outcome.coveredAfter, + coveredDelta: outcome.coveredDelta, + message: outcome.message, + }, + }); + } catch (error: any) { + return res.status(error?.status || 500).json({ + error: error?.code || 'server_error', + error_description: error?.message || '库存抵扣失败', + }); + } +}); + router.post('/orders/reprocess-allocation', authMiddleware, async (req: AuthRequest, res: Response) => { try { const ctx = await getWorkflowCtx(req); diff --git a/server/src/services/orderAllocationService.ts b/server/src/services/orderAllocationService.ts index b81c44c..f55ab27 100644 --- a/server/src/services/orderAllocationService.ts +++ b/server/src/services/orderAllocationService.ts @@ -2557,6 +2557,77 @@ async function reprocessOrderAllocationUnlocked( * - supplier_code 为空或 INTERNAL → 生成自采采购单 * - supplier_code 为真实供应商 → 生成供应商备货 */ +/** + * 手动补一次「库存抵扣」(2026-10-10 开发者要求)。 + * + * 场景:主系统分配过来的订单,**分配那一刻库存还没上新**(忘记录入库)⇒ 库存抵扣 = 0、缺口全转采购; + * 事后补录库存却没有任何入口重跑。本函数就是那个入口。 + * + * 为什么放在 service 而不是路由里:① 路由层不得内嵌 SQL(`routeLayerBoundary.test.ts` 棘轮); + * ② 必须复用既有分配路线 `reprocessOrderAllocation`(行锁 + 事务 + 幂等,并按新抵扣**重规划采购/备货** + * —— 只调 `applyStockCoverForOrder` 会留下"既抵扣又采购"的双记)。 + * 安全:已入库/已拣货的行由 `loadLockedStockCoverIfInboundOrPicking` 守住,重复点不会翻倍或清零。 + */ +export async function applyInventoryOffsetForMainSystemOrder(input: { + orderCode: string; + customerCode?: string | null; + branchCode: string; + /** 调用方已取到的订单状态(避免重复查询) */ + orderStatus: number; +}): Promise< + | { + kind: 'ok'; + coveredBefore: number; + coveredAfter: number; + coveredDelta: number; + message: string; + allocation: ReprocessOrderResult; + } + | { kind: 'not_main_system_order' } + | { kind: 'too_late'; status: number } + | { kind: 'invalid'; reason: string } +> { + const orderCode = String(input.orderCode || '').trim(); + const branchCode = String(input.branchCode || '').trim(); + if (!orderCode || !branchCode) return { kind: 'invalid', reason: '缺少订单号或分公司' }; + + // 只给**主系统分配过来的单**用:自建单在录单/分配时就走过了这条路线,不需要这个补丁入口 + const ledger = await pool.query( + `SELECT 1 FROM public.main_system_order_imports + WHERE branch_code = $1 AND our_order_code = $2 + LIMIT 1`, + [branchCode, orderCode] + ); + if (!ledger.rowCount) return { kind: 'not_main_system_order' }; + + const status = Number(input.orderStatus) || 0; + // 发车/配送中(>=50)已在扣库与出库,重跑抵扣会与在途库存打架 + if (status >= 50) return { kind: 'too_late', status }; + + const sumCover = async (): Promise => { + const res = await pool.query<{ n: number }>( + `SELECT COALESCE(SUM(stock_cover_qty), 0)::float AS n FROM order_items WHERE order_code = $1`, + [orderCode] + ); + return Number(res.rows[0]?.n) || 0; + }; + const before = await sumCover(); + const allocation = await reprocessOrderAllocation(orderCode, input.customerCode ?? null, branchCode); + const after = await sumCover(); + const coveredDelta = Math.round((after - before) * 1000) / 1000; + return { + kind: 'ok', + coveredBefore: before, + coveredAfter: after, + coveredDelta, + message: + coveredDelta > 0 + ? `库存抵扣完成:本次新增抵扣 ${coveredDelta}` + : '库存抵扣完成:当前库存没有可新抵扣的量(缺口仍需采购)', + allocation, + }; +} + export async function purchaserDirectAllocation( params: { orderCode: string; diff --git a/server/tests/inventoryOffsetButton.test.ts b/server/tests/inventoryOffsetButton.test.ts new file mode 100644 index 0000000..90e6c37 --- /dev/null +++ b/server/tests/inventoryOffsetButton.test.ts @@ -0,0 +1,89 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +/** + * 订单管理列表的「库存抵扣」小按钮(2026-10-10 开发者要求): + * 「这块分配来的订单补一个小按钮『库存抵扣』,点击后走库存抵扣的路线。 + * 应对就是我的订单已经分配过来了,但是**库存忘记上新了**这种情况 —— + * 因为库存抵扣在分配过来、创建订单时就执行过了。」 + * + * 钉三件事: + * ① 按钮只在**主系统分配过来的单**且未进入配送阶段(<50)时出现; + * ② 点击调的是**既有分配路线**(后端 `reprocessOrderAllocation`),不是自己新写抵扣; + * ③ 有在途锁(防连点)。 + */ +const route = readFileSync( + new URL('../src/modules/workflow/routes/orderRoutes.ts', import.meta.url), + 'utf8' +); +/** 逻辑落在 service(路由层不得内嵌 SQL —— `routeLayerBoundary.test.ts` 棘轮) */ +const allocSvc = readFileSync( + new URL('../src/services/orderAllocationService.ts', import.meta.url), + 'utf8' +); +const page = readFileSync( + new URL('../../src/pages/orders/orderManagement/OrderManagementPage.tsx', import.meta.url), + 'utf8' +); +const api = readFileSync(new URL('../../src/utils/workflowApi.ts', import.meta.url), 'utf8'); +const zh = readFileSync(new URL('../../src/i18n/locales/zh-CN/orders.ts', import.meta.url), 'utf8'); + +describe('后端:POST /orders/:orderCode/inventory-offset', () => { + it('只给主系统分配单用,且配送阶段(>=50)拒绝', () => { + const svcIdx = allocSvc.indexOf('export async function applyInventoryOffsetForMainSystemOrder'); + expect(svcIdx, '未找到库存抵扣服务函数').toBeGreaterThan(-1); + const svc = allocSvc.slice(svcIdx, svcIdx + 3200); + expect(svc).toContain('main_system_order_imports'); + expect(svc).toContain("kind: 'not_main_system_order'"); + expect(svc).toContain("kind: 'too_late'"); + expect(svc).toContain('status >= 50'); + // 路由只是薄壳:错误码映射 + 调用服务(SQL 一律在 service 里) + const idx = route.indexOf("'/orders/:orderCode/inventory-offset'"); + expect(idx).toBeGreaterThan(-1); + // 只取本路由自己的函数体(到下一个 router.post 为止),别把邻座路由的 SQL 算进来 + const next = route.indexOf('router.post(', idx + 10); + const body = route.slice(idx, next > idx ? next : idx + 3200); + expect(body).toContain('applyInventoryOffsetForMainSystemOrder({'); + expect(body).toContain("error: 'inventory_offset_too_late'"); + expect(body).not.toContain('SELECT '); + }); + + it('走既有分配路线(reprocessOrderAllocation),不自己实现抵扣', () => { + const svcIdx = allocSvc.indexOf('export async function applyInventoryOffsetForMainSystemOrder'); + const svc = allocSvc.slice(svcIdx, svcIdx + 3200); + expect(svc).toContain('await reprocessOrderAllocation(orderCode, input.customerCode ?? null, branchCode)'); + // 不直接调 applyStockCoverForOrder(那会留下"既抵扣又采购"的双记) + expect(svc).not.toContain('applyStockCoverForOrder('); + // 返回可展示的结果(抵扣增量) + expect(svc).toContain('coveredDelta'); + expect(svc).toContain('message:'); + }); +}); + +describe('前端:按钮的出现条件与在途锁', () => { + it('只在主系统分配单且状态 < 50 时出现', () => { + const idx = page.indexOf('const canApplyInventoryOffset'); + expect(idx, '未找到出现条件').toBeGreaterThan(-1); + const fn = page.slice(idx, idx + 240); + expect(fn).toContain('order.is_main_system_order === true'); + expect(fn).toContain('Number(order.order_status) < 50'); + // 列表行里用它包住按钮(不是无条件渲染) + expect(page).toMatch(/canApplyInventoryOffset\(o\) \? \(/); + }); + + it('有在途锁:点击期间禁用、结束后释放', () => { + const idx = page.indexOf('const handleInventoryOffset'); + expect(idx).toBeGreaterThan(-1); + const body = page.slice(idx, idx + 800); + expect(body).toContain('setInventoryOffsetCode(order.order_code)'); + expect(body).toContain('finally'); + expect(body).toContain('setInventoryOffsetCode(null)'); + expect(page).toContain('disabled={inventoryOffsetCode === o.order_code}'); + }); + + it('文案:按钮「库存抵扣」中文为开发者原话,三语键齐', () => { + expect(zh).toContain("'list.inventoryOffset': '库存抵扣'"); + expect(api).toContain('applyInventoryOffsetApi'); + expect(api).toContain('/inventory-offset'); + }); +}); diff --git a/src/i18n/locales/en/orders.ts b/src/i18n/locales/en/orders.ts index 92850ec..0bfd63c 100644 --- a/src/i18n/locales/en/orders.ts +++ b/src/i18n/locales/en/orders.ts @@ -258,6 +258,9 @@ export const orders: MessageDict = { 'list.stockPrefix': 'Stock cover: {items}', 'list.view': 'View', 'list.viewTitle': 'View details', + 'list.inventoryOffset': 'Offset stock', + 'list.inventoryOffsetDone': 'Stock offset applied', + 'list.inventoryOffsetFailed': 'Stock offset failed', 'list.jumpDelivery': 'Open delivery tasks', 'list.noDeliveryAccess': 'No access to delivery management', 'list.histFinalize': 'Historical close', diff --git a/src/i18n/locales/id/orders.ts b/src/i18n/locales/id/orders.ts index 9163166..5818ce2 100644 --- a/src/i18n/locales/id/orders.ts +++ b/src/i18n/locales/id/orders.ts @@ -258,6 +258,9 @@ export const orders: MessageDict = { 'list.stockPrefix': 'Tutup stok: {items}', 'list.view': 'Lihat', 'list.viewTitle': 'Lihat detail', + 'list.inventoryOffset': 'Potong stok', + 'list.inventoryOffsetDone': 'Potongan stok selesai', + 'list.inventoryOffsetFailed': 'Potongan stok gagal', 'list.jumpDelivery': 'Buka tugas pengiriman', 'list.noDeliveryAccess': 'Tidak berwenang membuka pengiriman', 'list.histFinalize': 'Tutup historis', diff --git a/src/i18n/locales/zh-CN/orders.ts b/src/i18n/locales/zh-CN/orders.ts index c09fce5..11026e7 100644 --- a/src/i18n/locales/zh-CN/orders.ts +++ b/src/i18n/locales/zh-CN/orders.ts @@ -250,6 +250,9 @@ export const orders: MessageDict = { 'list.stockPrefix': '库存抵扣:{items}', 'list.view': '查看', 'list.viewTitle': '查看详情', + 'list.inventoryOffset': '库存抵扣', + 'list.inventoryOffsetDone': '库存抵扣完成', + 'list.inventoryOffsetFailed': '库存抵扣失败', 'list.jumpDelivery': '打开配送任务', 'list.noDeliveryAccess': '无权打开配送管理', 'list.histFinalize': '历史结案', diff --git a/src/pages/orders/orderManagement/OrderManagementPage.tsx b/src/pages/orders/orderManagement/OrderManagementPage.tsx index b54454c..e8606c5 100644 --- a/src/pages/orders/orderManagement/OrderManagementPage.tsx +++ b/src/pages/orders/orderManagement/OrderManagementPage.tsx @@ -101,6 +101,7 @@ import { runOrderAutoAdvanceApi, getHistoricalFinalizeAllowlistApi, historicalFinalizeOrderApi, + applyInventoryOffsetApi, } from '../../../utils/workflowApi'; import { useCategoryRows } from '../../../hooks/useCategoryRows'; import { useRowClickOrDoubleClick } from '../../../hooks/useRowClickOrDoubleClick'; @@ -2770,6 +2771,28 @@ export const OrderManagement: React.FC = () => { } }; + /** + * 手动补一次「库存抵扣」(2026-10-10 开发者要求): + * 主系统分配单在分配那一刻如果**库存还没上新**,抵扣就是 0、缺口全转采购;补录库存后点这里重跑。 + * 只对**主系统分配过来的单**且未进入配送阶段(<50)出现;带在途锁,成功后刷新列表。 + */ + const [inventoryOffsetCode, setInventoryOffsetCode] = useState(null); + const canApplyInventoryOffset = (order: Order) => + order.is_main_system_order === true && Number(order.order_status) < 50; + const handleInventoryOffset = async (order: Order) => { + if (!canApplyInventoryOffset(order) || inventoryOffsetCode === order.order_code) return; + setInventoryOffsetCode(order.order_code); + try { + const res = await applyInventoryOffsetApi(order.order_code); + notify.success(res?.data?.message || t('orders.list.inventoryOffsetDone')); + await fetchOrders({ silent: true }); + } catch (error: any) { + notify(error instanceof Error ? error.message : t('orders.list.inventoryOffsetFailed')); + } finally { + setInventoryOffsetCode(null); + } + }; + const openAutoAdvanceConfig = async () => { setShowAutoAdvanceConfig(true); setAutoAdvanceEligibleCount(null); @@ -3689,6 +3712,19 @@ export const OrderManagement: React.FC = () => { > {t('orders.list.view')} + {canApplyInventoryOffset(o) ? ( + + ) : null} {canHistoricalFinalize(o) ? (