feat(订单列表): 主系统分配单加「库存抵扣」小按钮(补录库存后重跑抵扣)
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

开发者原话:「这块分配来的订单补一个小按钮『库存抵扣』,点击后走库存抵扣的路线。应对就是我的订单
已经分配过来了,但是**库存忘记上新了**这种情况 —— 因为库存抵扣在分配过来、创建订单时就执行过了。」

问题:库存抵扣只在**分配那一刻**跑(`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 用例全绿;门禁同基线。
This commit is contained in:
Ubuntu
2026-10-10 13:59:13 +08:00
parent 6e4eedf2cc
commit e54c2c7ec1
9 changed files with 310 additions and 1 deletions
@@ -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` 过宽判据)**他们也已核实成立**,列为"另案";
@@ -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);
@@ -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<number> => {
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;
@@ -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');
});
});
+3
View File
@@ -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',
+3
View File
@@ -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',
+3
View File
@@ -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': '历史结案',
@@ -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<string | null>(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')}
</button>
{canApplyInventoryOffset(o) ? (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
void handleInventoryOffset(o);
}}
disabled={inventoryOffsetCode === o.order_code}
className="px-2 py-1 text-xs font-medium text-sky-700 hover:bg-sky-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{t('orders.list.inventoryOffset')}
</button>
) : null}
{canHistoricalFinalize(o) ? (
<button
type="button"
+23
View File
@@ -5280,6 +5280,29 @@ export async function historicalFinalizeOrderApi(orderCode: string) {
);
}
/**
* 手动补一次「库存抵扣」(2026-10-10 开发者要求)。
* 场景:主系统分配单在分配那一刻**库存还没上新** ⇒ 抵扣 0、缺口全转采购;补录库存后点这个按钮重跑分配路线。
* 后端复用既有 `reprocessOrderAllocation`(行锁 + 幂等 + 重规划采购),返回 `message` 直接给界面提示。
*/
export async function applyInventoryOffsetApi(orderCode: string) {
return workflowFetch<{
data: {
itemsProcessed: number;
purchaseOrdersCreated: number;
preparationsCreated: number;
coveredBefore: number;
coveredAfter: number;
coveredDelta: number;
message: string;
errors: string[];
};
}>(`/orders/${encodeURIComponent(orderCode)}/inventory-offset`, {
method: 'POST',
body: JSON.stringify({}),
});
}
/** 待补录订单「确认入账」:校验补录完成后结案 90 并入账 */
export async function confirmOrderBackfillApi(orderCode: string) {
return workflowFetch<{ success: boolean; data: { orderCode: string; completed: boolean } }>(