Files
SupplierSystem/server/tests/warehouseProcessingDemandSheet.test.ts
Ubuntu 5fa2bbfd55
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
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

663 lines
29 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { readFileSync } from 'node:fs';
import path from 'path';
import { describe, expect, it } from 'vitest';
import {
allocateProcessingCostByWeight,
isWarehouseProcessingLine,
} from '../src/services/processingDemandSheetService';
import { requiresWarehouseProcessing, seedOrderItemUnitCost } from '../src/services/processingMethodUtils';
import { normalizeDateOnly } from '../src/services/orderDeliveryDate';
describe('仓内加工需求单', () => {
it('配送日按日历日规范化,禁止截 Date.toString', () => {
expect(normalizeDateOnly(new Date('2026-08-24T00:00:00+08:00'))).toBe('2026-08-24');
expect(String(new Date('2026-08-24T00:00:00+08:00')).slice(0, 10)).not.toMatch(/^\d{4}-\d{2}-\d{2}$/);
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
expect(demand).toContain('normalizeDateOnly(order.delivery_date)');
expect(demand).not.toContain("String(order.delivery_date).slice(0, 10)");
});
it('仓内加工判定与现网闸门一致', () => {
expect(isWarehouseProcessingLine('切丝', 'warehouse')).toBe(true);
expect(requiresWarehouseProcessing('切丝', 'warehouse')).toBe(true);
expect(isWarehouseProcessingLine('切丝', 'supplier')).toBe(false);
expect(isWarehouseProcessingLine('原材料', 'warehouse')).toBe(false);
});
it('仓内加工成品改实采允许把成本写成 0,数量单位仍只读', () => {
const amend = readFileSync(
path.join(__dirname, '../src/services/purchaseAmendService.ts'),
'utf8'
);
expect(amend).toContain('warehouseDemand');
expect(amend).toContain('仓内加工成品成本须为 0,请另采原料入库');
expect(amend).toContain('pt.process_status < 40');
const page = readFileSync(
path.join(__dirname, '../../src/pages/purchase/PurchaseManagement.tsx'),
'utf8'
);
expect(page).toContain('canZeroWarehouseDemandCost');
});
it('仓内加工行录单不种子报价成本,其它行照旧', () => {
expect(
seedOrderItemUnitCost({
processingMethod: '切块',
processingOwner: 'warehouse',
computedCost: 0.87,
})
).toBe(0);
expect(
seedOrderItemUnitCost({
processingMethod: '切块',
processingOwner: 'warehouse',
computedCost: 0.87,
demandCompleted: true,
existingUnitCost: 1.25,
})
).toBe(1.25);
expect(
seedOrderItemUnitCost({
processingMethod: '切块',
processingOwner: 'supplier',
computedCost: 0.87,
})
).toBe(0.87);
expect(
seedOrderItemUnitCost({
processingMethod: '原材料',
processingOwner: 'warehouse',
computedCost: 6,
})
).toBe(6);
const submit = readFileSync(
path.join(__dirname, '../src/services/customerOrderSubmitService.ts'),
'utf8'
);
const items = readFileSync(
path.join(__dirname, '../src/services/orderManageItemsService.ts'),
'utf8'
);
expect(submit).toContain('seedOrderItemUnitCost');
expect(items).toContain('seedOrderItemUnitCost');
expect(items).toContain('listCompletedWarehouseDemandItemIds');
expect(items).toContain('if (requiresWarehouseProcessing(method, owner)) continue');
expect(items).not.toContain('setOrderItemUnitCostByOrderSku');
// `server-go/internal/orderentry/submit.go` 不在本仓库(T7 AC-T7.1.3),Go 侧断言移除;
// Node 侧同一接线由上面 submit/items 断言覆盖。
});
it('分配强制自采并在建任务三处跳过需求单行', () => {
const alloc = readFileSync(
path.join(__dirname, '../src/services/orderAllocationService.ts'),
'utf8'
);
const processing = readFileSync(
path.join(__dirname, '../src/services/processingTaskService.ts'),
'utf8'
);
const submit = readFileSync(
path.join(__dirname, '../src/services/customerOrderSubmitService.ts'),
'utf8'
);
const items = readFileSync(
path.join(__dirname, '../src/services/orderManageItemsService.ts'),
'utf8'
);
expect(alloc).toContain('stampWarehouseProcessingAsSelfPurchase');
expect(alloc).toContain('requiresWarehouseProcessing');
expect(processing).toContain('orderSkuHasWarehouseDemand');
expect(processing).toContain("source_type || '') === 'demand'");
expect(submit).toContain('syncWarehouseProcessingDemandForOrder');
expect(items).toContain('syncWarehouseProcessingDemandForOrder');
expect(items).toContain('warehouse_processing_self_purchase_only');
const firstAlloc = submit.indexOf('allocation = await reprocessOrderAllocation(');
const syncAfterAlloc = submit.indexOf('await syncWarehouseProcessingDemandForOrder(orderCode, client)');
expect(firstAlloc).toBeGreaterThan(-1);
expect(syncAfterAlloc).toBeGreaterThan(firstAlloc);
});
it('分配后自动完成仓内加工成品自采,采购员不再跳过', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
expect(demand).toContain('findOrCreateDemandSheet');
expect(demand).toContain('PROCESS_STATUS.rejected');
expect(demand).toContain('autoSkipOpenWarehouseDemandPurchases');
expect(demand).toContain('skipWarehouseProcessingPurchase');
expect(demand).toContain('healOpenWarehouseDemandPurchases');
expect(demand).toContain('healWarehousePurchaseZeroCosts');
// 该「自采/未分配合并」排除谓词已从 preparationFulfillmentService 迁到
// orderAllocationService 的 forceCover 选行 SQL(T7 对照实现更新,语义不变)。
const alloc = readFileSync(
path.join(__dirname, '../src/services/orderAllocationService.ts'),
'utf8'
);
expect(alloc).toMatch(/IN \('UNASSIGNED', 'INTERNAL'\)/);
const mobile = readFileSync(
path.join(__dirname, '../src/routes/mobile/mobilePurchaseRoutes.ts'),
'utf8'
);
expect(mobile).toContain('WAREHOUSE_DEMAND_PURCHASE_EXISTS_SQL');
expect(mobile).toContain('healOpenWarehouseDemandPurchases');
expect(mobile).toContain('healWarehousePurchaseZeroCosts');
const wxml = readFileSync(
path.join(__dirname, '../../miniprogram/components/purchase-today-panel/index.wxml'),
'utf8'
);
expect(wxml).toContain('无需操作');
expect(wxml).toContain('需求');
expect(wxml).toContain('product.planQtyText');
expect(wxml).not.toContain('bindtap="skipProductGroup"');
const web = readFileSync(
path.join(__dirname, '../../src/pages/purchase/PurchaseManagement.tsx'),
'utf8'
);
// 文案已迁 i18n(zh-CN/purchase.ts: whNoAction='仓内加工 · 无需操作'),页面用 key
const zhPurchase = readFileSync(
path.join(__dirname, '../../src/i18n/locales/zh-CN/purchase.ts'),
'utf8'
);
expect(web).toContain('purchase.whNoAction');
expect(zhPurchase).toContain('仓内加工 · 无需操作');
expect(web).toContain('const canSkipWarehouseDemand = (_purchase: PurchaseOrder) => false');
});
it('自采跳过与领料接口已挂 Web/小程序', () => {
const purchaseRoutes = readFileSync(
path.join(__dirname, '../src/modules/workflow/routes/purchaseRoutes.ts'),
'utf8'
);
const inspectionRoutes = readFileSync(
path.join(__dirname, '../src/modules/workflow/routes/inspectionRoutes.ts'),
'utf8'
);
const mobile = readFileSync(
path.join(__dirname, '../src/routes/mobile/mobilePurchaseRoutes.ts'),
'utf8'
);
const purchaseOp = readFileSync(
path.join(__dirname, '../src/services/purchaseOperationService.ts'),
'utf8'
);
expect(purchaseRoutes).toContain("router.post('/purchase/skip-warehouse-demand'");
expect(inspectionRoutes).toContain("router.post('/processing/demand/:taskId/pick'");
expect(mobile).not.toContain("router.post('/purchase/skip-warehouse-demand'");
expect(mobile).toContain("router.post('/processing/demand/:taskId/pick'");
expect(purchaseOp).toContain('assertWarehouseDemandPurchaseNotFinishedAsProduct');
expect(purchaseOp).toContain('warehouse_demand_no_cancel');
});
it('自采转供应商接口拒绝仓内加工成品行', () => {
const assign = readFileSync(
path.join(__dirname, '../src/services/purchaseSupplierAssignService.ts'),
'utf8'
);
expect(assign).toContain('warehouse_processing_self_purchase_only');
expect(assign).toContain('requiresWarehouseProcessing');
});
it('竞价范围排除仓内加工行', () => {
const bid = readFileSync(path.join(__dirname, '../src/services/bidRoundService.ts'), 'utf8');
expect(bid).toContain("LOWER(TRIM(COALESCE(oi.processing_owner, ''))) = 'warehouse'");
});
it('领料不要求净重,入库后回写并完工', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
const pickStart = demand.indexOf('export async function pickDemandSheetMaterial');
const pickEnd = demand.indexOf('export async function recalcDemandSheetFromInspections');
const pickSrc = demand.slice(pickStart, pickEnd);
expect(pickSrc).toContain('qty: number');
expect(pickSrc).not.toContain('netWeight');
expect(pickSrc).toContain('await recalcDemandSheetFromInspections(taskId, client)');
expect(pickSrc).toContain('PROCESS_STATUS.rejected');
expect(pickSrc).toContain('const newStatus = PROCESS_STATUS.inProgress');
expect(demand).toContain('loss_qty = $3');
expect(demand).toContain('inventory_cover_qty');
expect(demand).toContain('await recalcDemandSheetFromInspections(taskId, client)');
expect(demand).toContain('WHEN process_status >= $5::int THEN $6::int');
expect(demand).toContain('const completed = allFulfilled && hasPick');
expect(demand).not.toContain('inspection_result');
expect(demand).not.toContain("NOT IN ('D'");
expect(demand).not.toContain('INSPECTION_RESULT_FAIL');
const taskList = readFileSync(
path.join(__dirname, '../src/services/processingTaskService.ts'),
'utf8'
);
expect(taskList).toContain('recalcDemandSheetFromInspections');
expect(taskList).toContain('row.loss_qty = refreshed.loss_qty');
const compliance = readFileSync(
path.join(__dirname, '../src/services/inspectionComplianceService.ts'),
'utf8'
);
expect(compliance).toContain('recalcDemandSheetsForOrder');
expect(compliance).toContain('warehouseFinishedNoStock');
expect(compliance).toContain('WAREHOUSE_FINISHED_LEDGER_SKIP_REMARK');
expect(compliance).toContain('isWarehouseProcessingFinishedSku');
expect(demand).toContain('export async function isWarehouseProcessingFinishedSku');
});
it('领料不提前费用化:只冲减持有行,完工时按净重分摊入账', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
const pickStart = demand.indexOf('export async function pickDemandSheetMaterial');
const pickEnd = demand.indexOf('export async function recalcDemandSheetFromInspections');
const pickSrc = demand.slice(pickStart, pickEnd);
// 领料路径不再写 cost_details(否则多次领料互相覆盖、成本无订单归属)
expect(pickSrc).not.toContain('postProcessingStandaloneMaterialCost');
expect(pickSrc).toContain('reduceInventoryHoldingForMaterialPicks');
// 领料仅限本分公司库存:可用量预检 + FIFO 禁止跨仓兜底
expect(pickSrc).toContain('本分公司可用');
const outbound = readFileSync(
path.join(__dirname, '../src/services/inventoryOutboundService.ts'),
'utf8'
);
expect(outbound).toContain("operationType !== 'processing_out'");
// 完工:回写订单行单价与成品批次价;加工材料分摊不入账
expect(demand).toContain('settleDemandSheetCostOnCompletion');
expect(demand).toContain('processing_settled_unit_cost');
expect(demand).toContain('writeDemandLinkedSettledUnitCost');
expect(demand).toContain('DELETE FROM cost_details');
const settleStart = demand.indexOf('export async function settleDemandSheetCostOnCompletion');
const settleSrc = demand.slice(settleStart, demand.indexOf('export async function recalcDemandSheetsForOrder'));
expect(settleSrc).not.toContain('INSERT INTO cost_details');
expect(demand).toMatch(/function roundUnitCost\([\s\S]*?Math\.round\(n \* 100\) \/ 100/);
expect(demand).not.toMatch(/function roundUnitCost\([\s\S]*?10000/);
});
it('需求单作废前退料:已领未产出原料退回库存并恢复持有行', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
expect(demand).toContain('returnDemandSheetMaterials');
expect(demand).toContain('writeDemandLinkedSettledUnitCost(client, taskId, null)');
expect(demand).toContain('writeDemandLinkedSettledUnitCost');
// 退料发生在置作废之前
const qtyStart = demand.indexOf('async function recalcDemandSheetQty');
const qtySrc = demand.slice(qtyStart, qtyStart + 2000);
expect(qtySrc.indexOf('returnDemandSheetMaterials')).toBeLessThan(
qtySrc.indexOf('PROCESS_STATUS.rejected')
);
// 已有产出不退料;退料恢复持有行并清掉完工结算账本
expect(demand).toContain('netWeight > 0');
expect(demand).toContain("'processing_return'");
expect(demand).toContain('upsertInventoryHoldingCost');
});
it('仓内需求关联阈值统一为未作废(<50),完工不再使保护失效', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
const start = demand.indexOf('export async function purchaseLinkedToWarehouseDemand');
const end = demand.indexOf('}', demand.indexOf('return Boolean(result.rowCount);', start));
const src = demand.slice(start, end);
expect(src).toContain('PROCESS_STATUS.rejected');
expect(src).not.toContain('PROCESS_STATUS.completed');
});
it('领料与领料查询校验任务归属分公司', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
expect(demand).toContain('expectedBranchCode');
expect(demand).toContain("code: 'branch_mismatch'");
const inspectionRoutes = readFileSync(
path.join(__dirname, '../src/modules/workflow/routes/inspectionRoutes.ts'),
'utf8'
);
expect(inspectionRoutes).toContain('expectedBranchCode: branchCode');
const mobile = readFileSync(
path.join(__dirname, '../src/routes/mobile/mobilePurchaseRoutes.ts'),
'utf8'
);
expect(mobile).toContain('expectedBranchCode: ctx.branchCode');
});
it('加工单号并发:SAVEPOINT 内重试,禁止事务 aborted 后裸查', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
expect(demand).toContain('SAVEPOINT demand_sheet_insert');
expect(demand).toContain('ROLLBACK TO SAVEPOINT demand_sheet_insert');
// afterCommit 同步必须显式开事务(SAVEPOINT 依赖事务块)
const afterCommit = demand.slice(demand.indexOf('syncWarehouseProcessingDemandForOrderAfterCommit'));
expect(afterCommit).toContain("await client.query('BEGIN')");
const standalone = readFileSync(
path.join(__dirname, '../src/services/processingStandaloneService.ts'),
'utf8'
);
expect(standalone).toContain('SAVEPOINT standalone_task_insert');
});
it('独立自采入库幂等:request_id 去重,重试返回首单', () => {
const spi = readFileSync(
path.join(__dirname, '../src/services/selfPurchaseStockInboundService.ts'),
'utf8'
);
expect(spi).toContain('request_id');
expect(spi).toContain('loadSelfPurchaseInboundByRequestId');
expect(spi).toContain("'23505'");
const migration = readFileSync(
path.join(__dirname, '../../migrations/20260851_self_purchase_inbound_request_id.sql'),
'utf8'
);
expect(migration).toContain('request_id');
expect(migration).toContain('UNIQUE INDEX');
const web = readFileSync(
path.join(__dirname, '../../src/pages/purchase/SelfPurchaseInboundModal.tsx'),
'utf8'
);
expect(web).toContain('request_id: requestId');
const mp = readFileSync(
path.join(__dirname, '../../miniprogram/components/purchase-today-panel/index.js'),
'utf8'
);
expect(mp).toContain('spiRequestId');
expect(mp).toContain('request_id: this.data.spiRequestId');
});
it('web 采购列表挂仓内加工自愈,跳过接口事务化', () => {
const purchaseRoutes = readFileSync(
path.join(__dirname, '../src/modules/workflow/routes/purchaseRoutes.ts'),
'utf8'
);
const listStart = purchaseRoutes.indexOf("/purchase-orders/management-list");
const listSrc = purchaseRoutes.slice(listStart, listStart + 2000);
expect(listSrc).toContain('healOpenWarehouseDemandPurchases');
expect(listSrc).toContain('healWarehousePurchaseZeroCosts');
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
expect(demand).toContain('export async function healWarehousePurchaseZeroCosts');
expect(demand).toMatch(/actual_price = 0[\s\S]*purchase_price = 0[\s\S]*total_amount = 0/);
const skipStart = demand.indexOf('export async function skipWarehouseProcessingPurchase');
const skipSrc = demand.slice(skipStart, skipStart + 2500);
expect(skipSrc).toContain("await client.query('BEGIN')");
expect(skipSrc).not.toContain('input.existingClient || pool');
});
it('改回供应商加工时清掉自采仓内加工残留标记', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
expect(demand).toContain('export async function clearStaleWarehouseDemandPurchaseFlags');
expect(demand).toContain('self_processed = FALSE');
expect(demand).toContain('取消仓内加工,恢复待采');
expect(demand).toContain(
'await clearStaleWarehouseDemandPurchaseFlags(client, { orderCode: code, branchCode })'
);
expect(demand).toContain(
'await clearStaleWarehouseDemandPurchaseFlags(pool, branch ? { branchCode: branch } : {})'
);
});
it('领料幂等:request_id 去重,重试/双击不重复扣库存', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
const pickStart = demand.indexOf('export async function pickDemandSheetMaterial');
const pickEnd = demand.indexOf('export async function recalcDemandSheetFromInspections');
const pickSrc = demand.slice(pickStart, pickEnd);
expect(pickSrc).toContain('requestId');
expect(pickSrc).toContain('request_id');
expect(pickSrc).toContain('await recalcDemandSheetFromInspections(taskId, client)');
expect(pickSrc).toContain('material_qty');
// 撞唯一索引后回滚并返回首笔
expect(pickSrc).toContain("'23505'");
const migration = readFileSync(
path.join(__dirname, '../../migrations/20260852_processing_demand_pick_request_id.sql'),
'utf8'
);
expect(migration).toContain('idx_demand_picks_task_request');
// 两端路由都透传 request_id
const inspectionRoutes = readFileSync(
path.join(__dirname, '../src/modules/workflow/routes/inspectionRoutes.ts'),
'utf8'
);
expect(inspectionRoutes).toContain('request_id');
const mobile = readFileSync(
path.join(__dirname, '../src/routes/mobile/mobilePurchaseRoutes.ts'),
'utf8'
);
expect(mobile).toContain('requestId');
});
it('独立自采入库支持修改与删除:未消耗批次可操作,已消耗拒绝', () => {
const spi = readFileSync(
path.join(__dirname, '../src/services/selfPurchaseStockInboundService.ts'),
'utf8'
);
// 修改:数量/成本价按新值同步批次与持有行
expect(spi).toContain('updateSelfPurchaseStockInbound');
expect(spi).toContain("'stock_in_adjust'");
expect(spi).toContain('upsertInventoryHoldingCost');
// 删除:批次清零 + 冲持有 + 标记 voided_at
expect(spi).toContain('voidSelfPurchaseStockInbound');
expect(spi).toContain("'stock_in_void'");
expect(spi).toContain('canVoidIndependentInboundWhenInventoryHidden');
expect(spi).toContain("'batch_consumed'");
expect(spi).toContain("'branch_mismatch'");
expect(spi).toContain('reduceInventoryHoldingForReference');
expect(spi).toContain('FOR UPDATE');
// 列表与统计过滤已删除
expect(spi).toContain('spi.voided_at IS NULL');
const query = readFileSync(
path.join(__dirname, '../src/services/purchaseOrderQueryService.ts'),
'utf8'
);
expect(query).toContain('spi.voided_at IS NULL');
const migration = readFileSync(
path.join(__dirname, '../../migrations/20260853_self_purchase_inbound_void.sql'),
'utf8'
);
expect(migration).toContain('voided_at');
// 路由与前端按钮
const purchaseRoutes = readFileSync(
path.join(__dirname, '../src/modules/workflow/routes/purchaseRoutes.ts'),
'utf8'
);
expect(purchaseRoutes).toContain("router.patch('/purchase/self-purchase-stock-inbound/:id'");
expect(purchaseRoutes).toContain("router.delete('/purchase/self-purchase-stock-inbound/:id'");
const web = readFileSync(
path.join(__dirname, '../../src/pages/purchase/PurchaseManagement.tsx'),
'utf8'
);
expect(web).toContain('updateSelfPurchaseStockInboundApi');
expect(web).toContain('deleteSelfPurchaseStockInboundApi');
expect(web).toContain('handleDeleteSelfPurchaseInbound');
});
it('改单后自采单数量随订单需求同步', () => {
const items = readFileSync(
path.join(__dirname, '../src/services/orderManageItemsService.ts'),
'utf8'
);
// 明细保存路径调用 syncOpenPurchaseQtyForOrder(连接变量名可能是 follow)
expect(items).toContain('syncOpenPurchaseQtyForOrder');
expect(items).toMatch(/await syncOpenPurchaseQtyForOrder\(\w+,\s*orderCode\)/);
const alloc = readFileSync(
path.join(__dirname, '../src/services/orderAllocationService.ts'),
'utf8'
);
const start = alloc.indexOf('export async function syncOpenPurchaseQtyForOrder');
expect(start).toBeGreaterThan(-1);
const src = alloc.slice(start, start + 3000);
// 待采单更新计划量;仓内加工占位单连同实采量对齐;需求归零自动取消但不动仓内加工挂接单
expect(src).toContain('po.purchase_status IN (10, 32)');
expect(src).toContain('COALESCE(po.self_processed, false) = true');
expect(src).toContain('需求归零,自动取消');
expect(src).toContain("pt.source_type = 'demand'");
});
it('材料成本按净重分摊:单位成本=总成本/总净重,尾差落在末单', () => {
// 基础:100 元材料出 200 斤成品,两单 120/80 → 60/40
const base = allocateProcessingCostByWeight(100, [
{ orderCode: 'B', inspectedQty: 80 },
{ orderCode: 'A', inspectedQty: 120 },
]);
expect(base.unitCost).toBeCloseTo(0.5, 4);
expect(base.allocations).toEqual([
{ orderCode: 'B', amount: 40 },
{ orderCode: 'A', amount: 60 },
]);
expect(base.allocations.reduce((s, a) => s + a.amount, 0)).toBeCloseTo(100, 2);
// 尾差:100 元三等分,末单吃 0.01 尾差,合计必须等于材料成本
const third = allocateProcessingCostByWeight(100, [
{ orderCode: 'A', inspectedQty: 1 },
{ orderCode: 'B', inspectedQty: 1 },
{ orderCode: 'C', inspectedQty: 1 },
]);
expect(third.allocations.map((a) => a.amount)).toEqual([33.33, 33.33, 33.34]);
expect(third.allocations.reduce((s, a) => s + a.amount, 0)).toBeCloseTo(100, 2);
// 0 验收量的订单不分摊;全 0 / 0 成本 → 不分摊(走 processing_loss 或不入账)
const withZero = allocateProcessingCostByWeight(50, [
{ orderCode: 'A', inspectedQty: 0 },
{ orderCode: 'B', inspectedQty: 25 },
]);
expect(withZero.allocations).toEqual([{ orderCode: 'B', amount: 50 }]);
expect(withZero.unitCost).toBeCloseTo(2, 4);
expect(allocateProcessingCostByWeight(0, [{ orderCode: 'A', inspectedQty: 1 }]).allocations).toEqual([]);
expect(allocateProcessingCostByWeight(100, [{ orderCode: 'A', inspectedQty: 0 }]).allocations).toEqual([]);
// 单位成本两位:120 元领料 ÷ 18 斤入库 → 6.67(损耗摊进单价,不另记账)
const yam = allocateProcessingCostByWeight(120, [{ orderCode: 'A', inspectedQty: 18 }]);
expect(yam.unitCost).toBe(6.67);
expect(yam.allocations).toEqual([{ orderCode: 'A', amount: 120 }]);
});
it('自采与仓内加工待验按订单+SKU 去重,不把两家供应商并成一条', () => {
const reject = readFileSync(
path.join(__dirname, '../src/services/inspectionRejectFulfillmentService.ts'),
'utf8'
);
expect(reject).toContain("IN ('INTERNAL', 'UNASSIGNED')");
expect(reject).toContain('sqlSelfPurchaseSupplierEquiv');
expect(reject).toContain('pruneDuplicateSelfPurchasePendingInspections');
expect(reject).toContain('pruneAllDuplicateSelfPurchasePendingInspections');
const query = readFileSync(
path.join(__dirname, '../src/services/inspectionQueryService.ts'),
'utf8'
);
expect(query).toContain('pruneAllDuplicateSelfPurchasePendingInspections');
expect(query).toContain('demand_loss_qty');
expect(query).toContain("pt.source_type = 'demand'");
const prep = readFileSync(
path.join(__dirname, '../src/services/preparationFulfillmentService.ts'),
'utf8'
);
expect(prep).toContain('sqlSelfPurchaseSupplierEquiv');
expect(prep).toContain('pruneDuplicateSelfPurchasePendingInspections');
const compliance = readFileSync(
path.join(__dirname, '../src/services/inspectionComplianceService.ts'),
'utf8'
);
expect(compliance).toContain('sqlSelfPurchaseSupplierEquiv');
expect(compliance).toContain('pruneDuplicateSelfPurchasePendingInspections');
});
it('需求单按加工方式拆单:同仓同日同 SKU 不同方法各成一单', () => {
const demand = readFileSync(
path.join(__dirname, '../src/services/processingDemandSheetService.ts'),
'utf8'
);
// findOrCreateDemandSheet 的复用查询与并发兜底查询都必须带加工方式判重
const sheetStart = demand.indexOf('async function findOrCreateDemandSheet');
const sheetEnd = demand.indexOf('export async function stampWarehouseProcessingAsSelfPurchase');
const sheetSrc = demand.slice(sheetStart, sheetEnd);
const matches = sheetSrc.match(/AND processing_method = \$4/g) || [];
expect(matches.length).toBe(2);
// 唯一索引同步扩为含加工方式,且必须先删旧索引(旧索引仍会拦不同方法的第二单)
const migration = readFileSync(
path.join(__dirname, '../../migrations/20260856_processing_demand_sheet_by_method.sql'),
'utf8'
);
expect(migration).toContain('DROP INDEX IF EXISTS %I.idx_processing_demand_sheet_key');
expect(migration).toContain('(branch_code, demand_delivery_date, sku_code, processing_method)');
});
it('小程序加工底栏返回商品条数,不再按单位拆行', () => {
const taskSvc = readFileSync(
path.join(__dirname, '../src/services/processingTaskService.ts'),
'utf8'
);
expect(taskSvc).toContain('export async function sumTodayProcessingItemCount');
const mobile = readFileSync(
path.join(__dirname, '../src/routes/mobile/mobilePurchaseRoutes.ts'),
'utf8'
);
expect(mobile).toContain('today_process_item_count: todayProcessItemCount');
expect(mobile).toContain('today_process_qty_by_unit: []');
const panel = readFileSync(
path.join(__dirname, '../../miniprogram/components/processing-panel/index.js'),
'utf8'
);
const wxml = readFileSync(
path.join(__dirname, '../../miniprogram/components/processing-panel/index.wxml'),
'utf8'
);
expect(panel).toContain('resolveTodayProcessItemCount');
expect(wxml).toContain('todayProcessItemCount');
expect(wxml).not.toContain('todayProcessQtyByUnit');
});
it('下单日轴对无订单号需求单回退任务创建日', () => {
const taskSvc = readFileSync(
path.join(__dirname, '../src/services/processingTaskService.ts'),
'utf8'
);
const fnStart = taskSvc.indexOf('function processingWorkDateExpr');
const fnEnd = taskSvc.indexOf('function appendProcessingDateFilter');
const src = taskSvc.slice(fnStart, fnEnd);
expect(src).toContain("dateField === 'created_at'");
expect(src).toContain('pt.created_at');
expect(src).toContain('o.created_at');
});
it('明细保存回写报价单时排除仓内加工行', () => {
const svc = readFileSync(
path.join(__dirname, '../src/services/orderManageItemsService.ts'),
'utf8'
);
const loopStart = svc.indexOf('const costUpserts = new Map<');
const loopEnd = svc.indexOf('if (costUpserts.size > 0');
expect(loopStart).toBeGreaterThan(-1);
expect(loopEnd).toBeGreaterThan(loopStart);
const loop = svc.slice(loopStart, loopEnd);
expect(loop).toContain('requiresWarehouseProcessing');
expect(loop).toContain('normalizeProcessingOwner');
expect(loop).toContain('continue;');
});
});