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

供应商侧:按 SKU 库存单位称重出库;订单单位不一致时分拣后更新本地计划/实收并写 outbox,主系统接口开关默认关可重试。
This commit is contained in:
Ubuntu
2026-11-02 17:43:40 +08:00
parent 020f364572
commit b18e0c3f0a
14 changed files with 796 additions and 40 deletions
@@ -0,0 +1,63 @@
-- 2026-11-02:主系统备货计划变更(供应商侧)
-- 1) 订单行保存主系统备货计划修改后的实收口径;客户原下单快照仍用 ordered_*,价格/金额不动。
-- 2) 平台级 outbox:本地先改,再调主系统;失败可重试,不阻塞已完成的库存/分拣。
DO $$
DECLARE
sch text;
BEGIN
FOR sch IN
SELECT nspname FROM pg_namespace
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
LOOP
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema=sch AND table_name='order_items') THEN
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS actual_received_qty NUMERIC(14,3)', sch);
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS actual_received_unit VARCHAR(20)', sch);
EXECUTE format('ALTER TABLE %I.order_items ADD COLUMN IF NOT EXISTS inventory_unit VARCHAR(20)', sch);
EXECUTE format($c$COMMENT ON COLUMN %I.order_items.actual_received_qty IS '实际收货/称重数量(主系统备货计划变更后)'$c$, sch);
EXECUTE format($c$COMMENT ON COLUMN %I.order_items.actual_received_unit IS '实际收货单位(与 actual_received_qty 配套)'$c$, sch);
EXECUTE format($c$COMMENT ON COLUMN %I.order_items.inventory_unit IS '下单时 SKU 库存单位快照,避免后续主数据变更影响历史'$c$, sch);
END IF;
END LOOP;
END $$;
CREATE TABLE IF NOT EXISTS public.main_system_plan_changes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
branch_code VARCHAR(50) NOT NULL,
our_order_code VARCHAR(64) NOT NULL,
our_order_item_id UUID NOT NULL,
prep_id VARCHAR(64),
main_order_code VARCHAR(64),
before_qty NUMERIC(14,3) NOT NULL,
before_unit VARCHAR(20),
after_qty NUMERIC(14,3) NOT NULL,
after_unit VARCHAR(20),
actual_received_qty NUMERIC(14,3) NOT NULL,
original_customer_qty NUMERIC(14,3),
original_customer_unit VARCHAR(20),
reason TEXT,
source VARCHAR(32) NOT NULL DEFAULT 'supplier_picking',
status VARCHAR(20) NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','syncing','synced','failed','conflict','skipped')),
request_id VARCHAR(128) NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
response JSONB,
created_by UUID,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
synced_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_plan_changes_request
ON public.main_system_plan_changes (branch_code, request_id);
CREATE INDEX IF NOT EXISTS idx_main_system_plan_changes_pending
ON public.main_system_plan_changes (status, updated_at)
WHERE status IN ('pending','failed');
CREATE INDEX IF NOT EXISTS idx_main_system_plan_changes_order
ON public.main_system_plan_changes (branch_code, our_order_code);
COMMENT ON TABLE public.main_system_plan_changes IS
'供应商发起的主系统备货计划变更 outbox:本地计划先落地,主系统调用失败可重试,不阻塞库存/分拣。';
COMMENT ON COLUMN public.main_system_plan_changes.request_id IS '客户端幂等键;主系统接口也用同一个 client_request_id';
COMMENT ON COLUMN public.main_system_plan_changes.original_customer_qty IS '客户原下单数量快照(如 70 个),主系统备注使用';
+7
View File
@@ -294,6 +294,13 @@ export const config = {
priceQtyRequestPath:
process.env.MAIN_SYSTEM_PRICE_QTY_REQUEST_PATH || '/api/supplier/preparations/price-qty-request',
priceQtyEnabled: process.env.MAIN_SYSTEM_PRICE_QTY_ENABLED === '1',
/**
* 供应商分拣后修改主系统备货计划(数量/单位)。
* 默认关;主系统交付接口后再开,关闭时只写本地 outbox,不发请求。
*/
planChangePath:
process.env.MAIN_SYSTEM_PLAN_CHANGE_PATH || '/api/supplier/preparations',
planChangeEnabled: process.env.MAIN_SYSTEM_PLAN_CHANGE_ENABLED === '1',
},
};
@@ -403,6 +403,80 @@ router.patch('/orders/:orderCode/items', authMiddleware, async (req: AuthRequest
}
});
/**
* 主系统备货计划变更(供应商侧,2026-11-02)。
*
* 只在主系统分配行上使用;本地库存/分拣必须先完成,调用前不得重复扣库存。
* 价格/金额、客户原下单快照不动;主系统同步见 public.main_system_plan_changes。
*/
router.post(
'/orders/:orderCode/items/:itemId/plan-change',
authMiddleware,
async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'allocation_manage']);
const orderCode = String(req.params.orderCode || '').trim();
await assertOrderCodeAccess(orderCode, ctx!);
const { changeOrderItemPlan } = await import('../../../services/mainSystemPlanChangeService');
const data = await changeOrderItemPlan({
orderCode,
itemId: String(req.params.itemId || '').trim(),
afterQty: Number(req.body?.after_qty),
afterUnit: String(req.body?.after_unit || '').trim(),
actualReceivedQty: Number(req.body?.actual_received_qty ?? req.body?.after_qty),
reason: req.body?.reason ? String(req.body.reason) : null,
requestId: req.body?.request_id ? String(req.body.request_id) : null,
operatorId: ctx?.userId || null,
});
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '修改备货计划失败',
});
}
}
);
/**
* 计划变更同步台账/重试(主系统接口未启用时只读 pending,供联调使用)。
*/
router.get('/main-system/plan-changes', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage']);
const branchCode = getEffectiveBranchCode(ctx!, readOperatingBranchCode(req)) || ctx?.branchCode || '';
const { listPlanChanges } = await import('../../../services/mainSystemPlanChangeService');
const rows = await listPlanChanges({
branchCode,
orderCode: req.query?.order_code ? String(req.query.order_code) : null,
limit: Number(req.query?.limit) || 100,
});
return res.json({ data: rows });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '查询计划变更失败',
});
}
});
router.post('/main-system/plan-changes/retry', authMiddleware, async (req: AuthRequest, res: Response) => {
try {
const ctx = await getWorkflowCtx(req);
requireWorkflowPermission(ctx, ['order_edit', 'order_entry', 'order_manage', 'allocation_manage']);
const { retryPendingPlanChanges } = await import('../../../services/mainSystemPlanChangeService');
const data = await retryPendingPlanChanges(Number(req.body?.limit) || 50);
return res.json({ data });
} catch (error: any) {
return res.status(error?.status || 500).json({
error: error?.code || 'server_error',
error_description: error?.message || '重试计划变更失败',
});
}
});
/**
* 明细「缺货」(开发者 2026-10-10)。
*
@@ -545,6 +545,7 @@ export async function deductInventoryForOrderDeparture(
`SELECT pi.id, pi.order_item_id, pi.pick_code, pi.item_name, pi.sku_code, pi.unit,
pi.loaded_qty, pi.picked_qty, pi.required_qty, pi.picked_weight,
oi.sku_code AS order_sku,
sku_dd.unit AS inventory_unit,
catalog.code AS catalog_sku,
pt.branch_code AS pick_branch,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound,
@@ -615,7 +616,7 @@ export async function deductInventoryForOrderDeparture(
resolveCompleteReceivedSettlementQty(
row.picked_weight,
row.loaded_qty,
row.unit,
row.inventory_unit || row.unit,
row.picked_qty,
row.required_qty
) ||
@@ -946,6 +947,7 @@ async function planDeductLinesForOrder(
`SELECT pi.id, pi.order_item_id, pi.pick_code, pi.item_name, pi.sku_code,
pi.loaded_qty, pi.picked_qty, pi.required_qty, pi.unit, pi.picked_weight,
oi.sku_code AS order_sku, catalog.code AS catalog_sku,
sku_dd.unit AS inventory_unit,
COALESCE(skip_sup.skip_inbound, false) AS skip_inbound,
${skuDirectDeliveryAppliesSql(
"COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))",
@@ -1006,7 +1008,7 @@ async function planDeductLinesForOrder(
resolveCompleteReceivedSettlementQty(
row.picked_weight,
row.loaded_qty,
row.unit,
row.inventory_unit || row.unit,
row.picked_qty,
row.required_qty
) || 0;
@@ -0,0 +1,57 @@
import { MAIN_SYSTEM_FETCH_TIMEOUT_MS, MAIN_SYSTEM_DEFAULT_PATHS } from '../config';
import { getMainSystemToken } from '../token';
import { requestMainSystem, type MainSystemResult } from '../http';
import { mainSystemPlanChangePath } from '../endpoints';
/**
* 供应商分拣后修改主系统备货计划(数量/单位)。
*
* 契约见 handoff/20261102-主系统备货计划变更-提示词与实施计划.md。
* 主系统必须只改供应商备货计划,不改客户订单金额/成交价;备注与通知由主系统负责。
*/
export type MainSystemPlanChangePayload = {
prep_id: string;
order_item_id?: string | null;
before_qty: number;
before_unit: string;
after_qty: number;
after_unit: string;
actual_received_qty: number;
original_customer_qty?: number | null;
original_customer_unit?: string | null;
reason?: string | null;
source?: string;
client_request_id: string;
};
export async function submitMainSystemPlanChange(input: {
branchCode: string;
payload: MainSystemPlanChangePayload;
fetchImpl?: typeof fetch;
}): Promise<MainSystemResult<any>> {
const prepId = String(input.payload?.prep_id || '').trim();
if (!prepId) return { kind: 'rejected', status: 0, reason: '缺少主系统备货行 id', payload: null };
const tokenResult = await getMainSystemToken(input.branchCode);
if (tokenResult.kind === 'not_configured') {
return { kind: 'not_configured', status: 0, reason: tokenResult.reason, payload: null };
}
if (tokenResult.kind !== 'ok') {
return { kind: 'unavailable', status: 0, reason: tokenResult.reason, payload: null };
}
return requestMainSystem<any>({
endpoint: 'supplierPlanChange',
method: 'POST',
token: tokenResult.token,
path: mainSystemPlanChangePath(prepId),
body: input.payload,
timeoutMs: MAIN_SYSTEM_FETCH_TIMEOUT_MS,
timeoutReason: '修改主系统备货计划超时',
networkReasonPrefix: '修改主系统备货计划失败:',
fetchImpl: input.fetchImpl,
});
}
/** 仅用于检查端点表不会静默丢失(主系统未交付时也允许读到默认路径)。 */
export function defaultPlanChangeBasePath(): string {
return MAIN_SYSTEM_DEFAULT_PATHS.supplierPlanChange;
}
+4
View File
@@ -36,6 +36,8 @@ export const MAIN_SYSTEM_DEFAULT_PATHS = {
preparations: '/api/supplier/preparations',
preparationsStatus: '/api/supplier/preparations/status',
priceQtyRequest: '/api/supplier/preparations/price-qty-request',
/** 供应商分拣后修改主系统备货计划:POST {base}/{prep_id}/plan-change */
supplierPlanChange: '/api/supplier/preparations',
// 实收/单位申请的决策回传(Q9,主系统提交 b8519fbb)
actualQtyDecision: '/api/supplier/preparations/actual-qty-decision',
/**
@@ -139,6 +141,7 @@ export function mainSystemFeatureFlags(): {
fulfillmentEvents: boolean;
skipInboundAwaitPickup: boolean;
priceQty: boolean;
planChange: boolean;
} {
const flags = config.mainSystemIntegration;
return {
@@ -148,6 +151,7 @@ export function mainSystemFeatureFlags(): {
fulfillmentEvents: flags.fulfillmentEventsEnabled === true,
skipInboundAwaitPickup: flags.skipInboundAwaitPickup === true,
priceQty: flags.priceQtyEnabled === true,
planChange: flags.planChangeEnabled === true,
};
}
@@ -28,6 +28,8 @@ function pathOverride(endpoint: MainSystemEndpoint): string | undefined {
return flags.statusPath;
case 'priceQtyRequest':
return flags.priceQtyRequestPath;
case 'supplierPlanChange':
return flags.planChangePath;
case 'actualQtyDecision':
return process.env.MAIN_SYSTEM_ACTUAL_QTY_DECISION_PATH;
case 'priceQtyRequestsList':
@@ -132,3 +134,10 @@ export function buildMainSystemUrlWithPath(path: string, query?: MainSystemQuery
export function mainSystemSkuMappingBindPath(): string {
return mainSystemPath('skuMappingBind');
}
/** 供应商分拣后修改主系统备货计划:{base}/{prepId}/plan-change */
export function mainSystemPlanChangePath(prepId: string): string {
const base = mainSystemPath('supplierPlanChange').replace(/\/+$/, '');
return `${base}/${encodeURIComponent(String(prepId || '').trim())}/plan-change`;
}
@@ -0,0 +1,416 @@
import { randomUUID } from 'node:crypto';
import { pool } from '../db';
import { writeAuditLog } from './auditService';
import { mainSystemFeatureFlags } from './mainSystem/config';
import { submitMainSystemPlanChange } from './mainSystem/api/planChanges';
/**
* 主系统备货计划变更(供应商侧)。
*
* 顺序:
* 1. 分拣/称重已完成,库存按实际称重扣减(由分拣出库服务负责,本服务不重复扣);
* 2. 本地计划数量/单位/实收数量落地(价格、金额保持原订单口径);
* 3. public.main_system_plan_changes outbox 记录;
* 4. 主系统接口可用时同步;失败只标记 failed,可重试,不回滚库存/分拣。
*
* 契约:handoff/20261102-主系统备货计划变更-提示词与实施计划.md
*/
export type PlanChangeResult = {
change_id: string;
request_id: string;
status: 'pending' | 'syncing' | 'synced' | 'failed' | 'conflict' | 'skipped';
before_qty: number;
before_unit: string;
after_qty: number;
after_unit: string;
actual_received_qty: number;
sync_enabled: boolean;
message: string;
};
function bizError(message: string, status = 400, code = 'invalid_request'): Error {
return Object.assign(new Error(message), { status, code });
}
function roundQty(value: unknown): number {
return Math.round((Number(value) || 0) * 1000) / 1000;
}
function flagOn(): boolean {
return mainSystemFeatureFlags().planChange === true;
}
async function loadChange(id: string) {
const r = await pool.query(
`SELECT * FROM public.main_system_plan_changes WHERE id = $1::uuid LIMIT 1`,
[id]
);
return r.rows[0] || null;
}
function payloadOf(row: Record<string, any>) {
return {
prep_id: String(row.prep_id || ''),
order_item_id: String(row.our_order_item_id || '') || null,
before_qty: Number(row.before_qty) || 0,
before_unit: String(row.before_unit || ''),
after_qty: Number(row.after_qty) || 0,
after_unit: String(row.after_unit || ''),
actual_received_qty: Number(row.actual_received_qty) || 0,
original_customer_qty: row.original_customer_qty == null ? null : Number(row.original_customer_qty),
original_customer_unit: row.original_customer_unit == null ? null : String(row.original_customer_unit),
reason: row.reason == null ? null : String(row.reason),
source: String(row.source || 'supplier_picking'),
client_request_id: String(row.request_id),
};
}
/** 同步一条 outbox。主系统接口未启用时保持 pending,不发请求。 */
export async function dispatchMainSystemPlanChange(changeId: string): Promise<PlanChangeResult> {
const row = await loadChange(changeId);
if (!row) throw bizError('计划变更记录不存在', 404, 'not_found');
const status = String(row.status || '');
if (status === 'synced' || status === 'conflict' || status === 'skipped') {
return {
change_id: String(row.id),
request_id: String(row.request_id),
status,
before_qty: Number(row.before_qty) || 0,
before_unit: String(row.before_unit || ''),
after_qty: Number(row.after_qty) || 0,
after_unit: String(row.after_unit || ''),
actual_received_qty: Number(row.actual_received_qty) || 0,
sync_enabled: flagOn(),
message: status === 'synced' ? '已同步' : '已结束',
};
}
if (!flagOn()) {
await pool.query(
`UPDATE public.main_system_plan_changes
SET last_error = $2, updated_at = NOW()
WHERE id = $1::uuid AND status <> 'synced'`,
[changeId, '主系统计划变更接口未启用(MAIN_SYSTEM_PLAN_CHANGE_ENABLED)']
);
return {
change_id: String(row.id),
request_id: String(row.request_id),
status: 'pending',
before_qty: Number(row.before_qty) || 0,
before_unit: String(row.before_unit || ''),
after_qty: Number(row.after_qty) || 0,
after_unit: String(row.after_unit || ''),
actual_received_qty: Number(row.actual_received_qty) || 0,
sync_enabled: false,
message: '本地计划已保存;主系统同步未启用',
};
}
await pool.query(
`UPDATE public.main_system_plan_changes
SET status = 'syncing', attempts = attempts + 1, updated_at = NOW()
WHERE id = $1::uuid`,
[changeId]
);
let result;
try {
result = await submitMainSystemPlanChange({
branchCode: String(row.branch_code),
payload: payloadOf(row),
});
} catch (error: any) {
await pool.query(
`UPDATE public.main_system_plan_changes
SET status = 'failed', last_error = $2, updated_at = NOW()
WHERE id = $1::uuid`,
[changeId, String(error?.message || error)]
);
return {
change_id: String(row.id),
request_id: String(row.request_id),
status: 'failed',
before_qty: Number(row.before_qty) || 0,
before_unit: String(row.before_unit || ''),
after_qty: Number(row.after_qty) || 0,
after_unit: String(row.after_unit || ''),
actual_received_qty: Number(row.actual_received_qty) || 0,
sync_enabled: true,
message: String(error?.message || error),
};
}
if (result.kind === 'ok') {
await pool.query(
`UPDATE public.main_system_plan_changes
SET status = 'synced', response = $2::jsonb, last_error = NULL,
synced_at = NOW(), updated_at = NOW()
WHERE id = $1::uuid`,
[changeId, JSON.stringify(result.payload ?? null)]
);
return {
change_id: String(row.id),
request_id: String(row.request_id),
status: 'synced',
before_qty: Number(row.before_qty) || 0,
before_unit: String(row.before_unit || ''),
after_qty: Number(row.after_qty) || 0,
after_unit: String(row.after_unit || ''),
actual_received_qty: Number(row.actual_received_qty) || 0,
sync_enabled: true,
message: '已同步主系统',
};
}
const conflict = result.kind === 'rejected' && [409].includes(Number(result.status));
const nextStatus = conflict ? 'conflict' : 'failed';
await pool.query(
`UPDATE public.main_system_plan_changes
SET status = $2, last_error = $3, response = $4::jsonb, updated_at = NOW()
WHERE id = $1::uuid`,
[changeId, nextStatus, String(result.reason || '同步失败'), JSON.stringify(result.payload ?? null)]
);
return {
change_id: String(row.id),
request_id: String(row.request_id),
status: nextStatus,
before_qty: Number(row.before_qty) || 0,
before_unit: String(row.before_unit || ''),
after_qty: Number(row.after_qty) || 0,
after_unit: String(row.after_unit || ''),
actual_received_qty: Number(row.actual_received_qty) || 0,
sync_enabled: true,
message: String(result.reason || '同步失败'),
};
}
/**
* 本地计划变更入口。
* 价格/金额/客户原下单快照不在此处重算;actualReceivedQty 必须来自分拣称重。
*/
export async function changeOrderItemPlan(input: {
orderCode: string;
itemId: string;
afterQty: number;
afterUnit: string;
actualReceivedQty: number;
reason?: string | null;
requestId?: string | null;
operatorId?: string | null;
}): Promise<PlanChangeResult> {
const orderCode = String(input.orderCode || '').trim();
const itemId = String(input.itemId || '').trim();
const afterQty = roundQty(input.afterQty);
const actualReceivedQty = roundQty(input.actualReceivedQty);
const afterUnit = String(input.afterUnit || '').trim();
const requestId = String(input.requestId || '').trim() || randomUUID();
if (!orderCode || !itemId) throw bizError('缺少订单或明细', 400);
if (!(afterQty > 0) || !(actualReceivedQty > 0)) throw bizError('计划数量和实收数量必须大于 0', 400);
if (!afterUnit) throw bizError('计划单位不能为空', 400);
const client = await pool.connect();
let changeId = '';
let beforeQty = 0;
let beforeUnit = '';
let itemBranch = '';
try {
await client.query('BEGIN');
const existing = await client.query(
`SELECT id, request_id, status, before_qty, before_unit, after_qty, after_unit, actual_received_qty
FROM public.main_system_plan_changes
WHERE branch_code = (SELECT branch_code FROM orders WHERE order_code = $1 LIMIT 1)
AND request_id = $2
LIMIT 1`,
[orderCode, requestId]
);
if (existing.rowCount) {
await client.query('ROLLBACK');
const row = existing.rows[0];
return {
change_id: String(row.id),
request_id: String(row.request_id),
status: row.status,
before_qty: Number(row.before_qty) || 0,
before_unit: String(row.before_unit || ''),
after_qty: Number(row.after_qty) || 0,
after_unit: String(row.after_unit || ''),
actual_received_qty: Number(row.actual_received_qty) || 0,
sync_enabled: flagOn(),
message: '重复请求,已返回原记录',
};
}
const itemResult = await client.query(
`SELECT oi.id, oi.order_code, oi.sku_code, oi.quantity, oi.unit,
oi.ordered_quantity, oi.ordered_unit, oi.price, oi.amount,
o.branch_code, o.order_status
FROM order_items oi
JOIN orders o ON o.order_code = oi.order_code
WHERE oi.id = $1::uuid AND oi.order_code = $2
FOR UPDATE OF oi`,
[itemId, orderCode]
);
if (!itemResult.rowCount) throw bizError('订单明细不存在', 404, 'not_found');
const item = itemResult.rows[0];
beforeQty = Number(item.quantity) || 0;
beforeUnit = String(item.unit || '').trim();
itemBranch = String(item.branch_code || '');
if (Number(item.order_status) >= 90) {
throw bizError('订单已完成,不能修改计划', 409, 'order_completed');
}
if (Math.abs(beforeQty - afterQty) < 1e-9 && beforeUnit === afterUnit) {
throw bizError('计划数量和单位未变化', 400, 'no_change');
}
const mapping = await client.query(
`SELECT prep_id, main_order_code
FROM public.main_system_order_import_items
WHERE our_order_item_id = $1::uuid AND branch_code = $2
LIMIT 1`,
[itemId, String(item.branch_code || '')]
);
if (!mapping.rowCount) {
throw bizError('该行不是主系统分配商品,不能同步主系统计划', 400, 'not_main_system_item');
}
const prepId = String(mapping.rows[0].prep_id || '').trim();
if (!prepId) throw bizError('缺少主系统备货行 id', 400, 'missing_prep_id');
const skuUnit = await client.query(
`SELECT unit FROM skus WHERE sku_code = $1 AND branch_code = $2 LIMIT 1`,
[String(item.sku_code || ''), String(item.branch_code || '')]
);
const inventoryUnit = String(skuUnit.rows[0]?.unit || '').trim() || null;
const originalQty = item.ordered_quantity == null ? beforeQty : Number(item.ordered_quantity);
const originalUnit = String(item.ordered_unit || beforeUnit || '').trim();
await client.query(
`UPDATE order_items
SET quantity = $2,
unit = $3,
actual_received_qty = $4,
actual_received_unit = $3,
inventory_unit = COALESCE(inventory_unit, $5),
ordered_quantity = COALESCE(ordered_quantity, $6),
ordered_unit = COALESCE(ordered_unit, $7)
WHERE id = $1::uuid`,
[itemId, afterQty, afterUnit, actualReceivedQty, inventoryUnit, originalQty, originalUnit]
);
const inserted = await client.query(
`INSERT INTO public.main_system_plan_changes (
branch_code, our_order_code, our_order_item_id, prep_id, main_order_code,
before_qty, before_unit, after_qty, after_unit, actual_received_qty,
original_customer_qty, original_customer_unit, reason, source, status,
request_id, created_by
) VALUES ($1,$2,$3,$4::varchar,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,'pending',$15,$16)
RETURNING id`,
[
String(item.branch_code || ''),
orderCode,
itemId,
prepId,
mapping.rows[0].main_order_code || null,
beforeQty,
beforeUnit,
afterQty,
afterUnit,
actualReceivedQty,
originalQty,
originalUnit,
String(input.reason || '').trim() || '分拣称重后按实际重量',
'supplier_picking',
requestId,
input.operatorId || null,
]
);
changeId = String(inserted.rows[0]?.id || '');
// 订单行数量/单位变了:同步客户/供应商结算投影(金额本身不重算,仍按原订单口径)。
{
const { syncStatementsForOrderSafe } = await import('./financeReconciliationService');
await syncStatementsForOrderSafe(orderCode, client as any);
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
try {
await writeAuditLog({
operatorId: input.operatorId || null,
operationType: 'main_system_plan_change_local',
targetTable: 'order_items',
targetId: itemId,
oldValue: { before_qty: beforeQty, before_unit: beforeUnit },
newValue: {
after_qty: afterQty,
after_unit: afterUnit,
actual_received_qty: actualReceivedQty,
request_id: requestId,
note: '价格/金额未改;主系统同步见 outbox',
},
branchCode: itemBranch || null,
actionCategory: 'order',
});
} catch (error) {
console.warn('[plan-change] 审计失败(不影响本地计划):', (error as Error)?.message || error);
}
if (!flagOn()) {
return {
change_id: changeId,
request_id: requestId,
status: 'pending',
before_qty: beforeQty,
before_unit: beforeUnit,
after_qty: afterQty,
after_unit: afterUnit,
actual_received_qty: actualReceivedQty,
sync_enabled: false,
message: '本地计划已保存;主系统同步未启用',
};
}
return dispatchMainSystemPlanChange(changeId);
}
/** 重试待同步记录(定时任务/管理员补发)。 */
export async function retryPendingPlanChanges(limit = 50): Promise<{ retried: number; synced: number; failed: number }> {
if (!flagOn()) return { retried: 0, synced: 0, failed: 0 };
const r = await pool.query(
`SELECT id FROM public.main_system_plan_changes
WHERE status IN ('pending','failed') AND attempts < 20
ORDER BY updated_at ASC
LIMIT $1`,
[Math.max(1, Math.min(Number(limit) || 50, 200))]
);
let synced = 0;
let failed = 0;
for (const row of r.rows) {
const result = await dispatchMainSystemPlanChange(String(row.id));
if (result.status === 'synced') synced += 1;
else failed += 1;
}
return { retried: r.rowCount || 0, synced, failed };
}
export async function listPlanChanges(input: {
branchCode: string;
orderCode?: string | null;
limit?: number;
}) {
const limit = Math.max(1, Math.min(Number(input.limit) || 100, 200));
const result = await pool.query(
`SELECT id, branch_code, our_order_code, our_order_item_id, prep_id, main_order_code,
before_qty, before_unit, after_qty, after_unit, actual_received_qty,
original_customer_qty, original_customer_unit, status, attempts,
last_error, request_id, created_at, updated_at, synced_at
FROM public.main_system_plan_changes
WHERE branch_code = $1
AND ($2::text IS NULL OR our_order_code = $2)
ORDER BY created_at DESC
LIMIT $3`,
[input.branchCode, input.orderCode || null, limit]
);
return result.rows;
}
+65 -21
View File
@@ -1679,9 +1679,11 @@ export async function confirmPickingComplete(input: {
* 已拣/已核货的行照旧校验(历史事故:分拣完成会把实拣量写成结算量,不能漏行)。
*/
`SELECT pi.id, pi.order_item_id, pi.item_name, pi.required_qty, pi.picked_qty, pi.picked_weight,
pi.review_status, pi.unit, pi.order_code
pi.review_status, pi.unit, pi.order_code,
s.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN skus s ON s.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
WHERE pi.pick_code = $1
AND (
pi.order_item_id IS NULL
@@ -1707,19 +1709,20 @@ export async function confirmPickingComplete(input: {
});
}
if (await isPickingScaleRequired()) {
const missingWeight = items.rows.filter(
(row) =>
isPickingWeightUnit(row.unit) &&
(Number(row.required_qty) || 0) > 0 &&
(Number(row.picked_weight) || 0) <= 0
const scaleRequired = await isPickingScaleRequired();
const missingWeight = items.rows.filter((row) => {
const inventoryUnit = String(row.inventory_unit || '').trim();
if (!isPickingWeightUnit(inventoryUnit)) return false;
if ((Number(row.required_qty) || 0) <= 0) return false;
// 库存按重量管理,且订单单位不是重量单位时,必须称重;同单位沿用原有 scale 开关。
if (!scaleRequired && isPickingWeightUnit(row.unit)) return false;
return (Number(row.picked_weight) || 0) <= 0;
});
if (missingWeight.length) {
throw Object.assign(
new Error(`还有 ${missingWeight.length} 项重量单位未录入实拣重量`),
{ status: 400 }
);
if (missingWeight.length) {
throw Object.assign(
new Error(`已开启分拣称重,还有 ${missingWeight.length} 项重量单位未录入实拣重量`),
{ status: 400 }
);
}
}
let hasDiff = false;
@@ -1800,6 +1803,37 @@ export async function confirmPickingComplete(input: {
);
}
// 订单单位与库存单位不一致(如订单 70 个 / 库存斤):分拣称重后,
// 先按实际重量调整本地计划数量/单位/实收,再写主系统同步 outbox。
// 库存扣减已由出库服务按 SKU 库存单位完成,这里不重复扣库。
for (const row of items.rows) {
const inventoryUnit = String(row.inventory_unit || '').trim();
if (
!inventoryUnit ||
!isPickingWeightUnit(inventoryUnit) ||
isPickingWeightUnit(row.unit) ||
!Number(row.picked_weight || 0) ||
!row.order_item_id
) {
continue;
}
try {
const { changeOrderItemPlan } = await import('./mainSystemPlanChangeService');
await changeOrderItemPlan({
orderCode: String(row.order_code || task.order_code || ''),
itemId: String(row.order_item_id),
afterQty: Number(row.picked_weight),
afterUnit: inventoryUnit,
actualReceivedQty: Number(row.picked_weight),
reason: '分拣称重后按实际重量',
requestId: `pick:${pickCode}:${row.id}`,
operatorId: input.reviewerId || null,
});
} catch (error) {
console.warn('[picking] 分拣后修改本地计划失败(不阻断分拣)', pickCode, (error as Error)?.message || error);
}
}
// 第九批「批次报告同步」触发点①:分拣完成 ⇒ 本次出库批次已确定,旁路异步推批次报告
// (未绑定/非主系统下发的行在推送侧被物理拦住;开关默认关 ⇒ 零出站。见 20261011-批次报告推送主系统.md)
const { triggerReportPush } = await import('./mainSystemReportPushService');
@@ -2213,10 +2247,12 @@ export async function completePickingOutbound(input: {
const allItems = await client.query(
`SELECT pi.*,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
o.order_status
o.order_status,
s.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN orders o ON o.order_code = pi.order_code
LEFT JOIN skus s ON s.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
WHERE pi.pick_code = $1`,
[input.pickCode]
);
@@ -2248,13 +2284,14 @@ export async function completePickingOutbound(input: {
const pendingRows = allItems.rows.filter(
(row: { outbound_at?: string | null }) => !row.outbound_at
);
/** 库存扣减口径:优先 SKU 库存单位;订单单位/个不能直接当斤。 */
const pickingSettlement = (row: { picked_qty?: unknown; picked_weight?: unknown; unit?: unknown; inventory_unit?: unknown }) =>
resolvePickingSettlementQty(row.picked_qty, row.picked_weight, String(row.inventory_unit || row.unit || ''));
const warehousePending = pendingRows.filter(
(row: { is_extra_dish?: unknown; order_status?: unknown }) =>
!isTruthyFlag(row.is_extra_dish) && Number(row.order_status) < 50
);
const items = warehousePending.filter(
(row) => resolvePickingSettlementQty(row.picked_qty, row.picked_weight, row.unit) > 0
);
const items = warehousePending.filter((row) => pickingSettlement(row) > 0);
if (!items.length) {
if (!warehousePending.length) {
await client.query(
@@ -2278,14 +2315,14 @@ export async function completePickingOutbound(input: {
client,
items.map((row) => ({
...row,
picked_qty: resolvePickingSettlementQty(row.picked_qty, row.picked_weight, row.unit),
picked_qty: pickingSettlement(row),
})),
task.branch_code,
task.order_code || items[0]?.order_code || null
);
for (const item of items) {
const outboundQty = resolvePickingSettlementQty(item.picked_qty, item.picked_weight, item.unit);
const outboundQty = pickingSettlement(item);
if (outboundQty <= 0 || !trimSku(item.sku_code)) continue;
if (await isPassThroughSku({ skuCode: trimSku(item.sku_code), branchCode: task.branch_code }, client)) {
continue;
@@ -2518,10 +2555,12 @@ export async function outboundPickingByContainer(input: {
const itemResult = await client.query(
`SELECT pi.*,
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
o.order_status
o.order_status,
s.unit AS inventory_unit
FROM picking_items pi
LEFT JOIN order_items oi ON oi.id = pi.order_item_id
LEFT JOIN orders o ON o.order_code = pi.order_code
LEFT JOIN skus s ON s.sku_code = COALESCE(NULLIF(TRIM(pi.sku_code), ''), NULLIF(TRIM(oi.sku_code), ''))
WHERE pi.id = $1 AND pi.pick_code = $2 FOR UPDATE`,
[container.pick_item_id, task.pick_code]
);
@@ -2554,7 +2593,11 @@ export async function outboundPickingByContainer(input: {
const skipWarehouse =
isTruthyFlag(item.is_extra_dish) || Number(item.order_status) >= 50;
const outboundQty = resolvePickingSettlementQty(item.picked_qty, item.picked_weight, item.unit);
const outboundQty = resolvePickingSettlementQty(
item.picked_qty,
item.picked_weight,
String(item.inventory_unit || item.unit || '')
);
if (!skipWarehouse && outboundQty <= 0) {
throw businessError('该件实拣数量/重量为 0,不能出库');
}
@@ -3696,6 +3739,7 @@ export const PICKING_ITEMS_ENRICHED_SQL = `
pi.item_name AS item_name_snapshot,
pi.required_qty, pi.picked_qty,
pi.picked_weight, pi.unit,
s.unit AS inventory_unit,
pi.review_status, pi.diff_reason, pi.sort_order, pi.created_at,
-- 商品分类(分拣列表批量打印按「分类」排队用;纯读,oi 已在 JOIN 中)
oi.category_name AS category_name,
+10
View File
@@ -1170,6 +1170,16 @@ export function startScheduledJobs() {
runSkuMappingSync(),
// 主系统镜像空单收口兜底(纯本地)
runEmptyMirrorOrderClosure(),
// 供应商备货计划变更 outbox 重试(开关默认关 ⇒ 直接返回)
(async () => {
const { retryPendingPlanChanges } = await import('./mainSystemPlanChangeService');
const result = await retryPendingPlanChanges(50);
if (result.retried) {
console.log(
`[scheduler] 主系统计划变更重试:${result.retried} 条,成功 ${result.synced},失败 ${result.failed}`
);
}
})(),
]);
} catch (error) {
console.error('[scheduler] 跨系统任务异常:', error);
+54
View File
@@ -0,0 +1,54 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { mainSystemPlanChangePath } from '../src/services/mainSystem/endpoints';
import { resolveCompleteReceivedSettlementQty } from '../src/services/orderItemSupplyUnitSync';
const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8');
const svc = read('src/services/mainSystemPlanChangeService.ts');
const api = read('src/services/mainSystem/api/planChanges.ts');
const migration = read('../migrations/20261103_main_system_plan_change.sql');
const orderRoutes = read('src/modules/workflow/routes/orderRoutes.ts');
const outbound = read('src/services/inventoryOutboundService.ts');
const picking = read('src/services/pickingService.ts');
describe('主系统备货计划变更(供应商侧)', () => {
it('主系统路径固定为 /preparations/:id/plan-change', () => {
expect(mainSystemPlanChangePath('abc')).toBe('/api/supplier/preparations/abc/plan-change');
expect(api).toContain("endpoint: 'supplierPlanChange'");
expect(api).toContain('client_request_id');
});
it('本地计划变更不覆盖价格/金额,保留客户原下单快照', () => {
expect(svc).toContain('actual_received_qty');
expect(svc).toContain('ordered_quantity = COALESCE(ordered_quantity');
expect(svc).not.toContain('price =');
expect(svc).not.toContain('amount =');
});
it('先写 outbox,主系统接口关闭时只 pending', () => {
expect(migration).toContain('main_system_plan_changes');
expect(migration).toContain('status IN');
expect(svc).toContain('planChange');
expect(svc).toContain('主系统同步未启用');
});
it('有主系统备货行映射才允许同步', () => {
expect(svc).toContain('main_system_order_import_items');
expect(svc).toContain('not_main_system_item');
});
it('库存出库和分拣称重按 SKU 库存单位判断', () => {
expect(outbound).toContain('sku_dd.unit AS inventory_unit');
expect(outbound).toContain('row.inventory_unit || row.unit');
expect(picking).toContain('s.unit AS inventory_unit');
expect(picking).toContain('isPickingWeightUnit(inventoryUnit)');
// 订单 70 个 / 库存斤:称重 30 斤必须按 30 斤出库,不能按 70 个/斤。
expect(resolveCompleteReceivedSettlementQty(30, 0, '斤', 70, 70)).toBe(30);
expect(resolveCompleteReceivedSettlementQty(0, 0, '个', 70, 70)).toBe(70);
});
it('路由入口和台账查询存在', () => {
expect(orderRoutes).toContain('/orders/:orderCode/items/:itemId/plan-change');
expect(orderRoutes).toContain('/main-system/plan-changes');
});
});
@@ -58,7 +58,9 @@ describe('④ 完成校验口径与读取一致(否则互锁:界面看不到
it('confirmPickingComplete 的取行 SQL 用的是同一条谓词', () => {
const idx = pickingSrc.indexOf('export async function confirmPickingComplete');
expect(idx).toBeGreaterThan(-1);
const body = pickingSrc.slice(idx, idx + 6000);
// 2026-11-02:confirmPickingComplete 增加 SKU 库存单位/计划同步后,
// 取行 SQL 仍在函数开头约 6.2k 字符内;窗口放宽到 7k,避免文本位移导致假失败。
const body = pickingSrc.slice(idx, idx + 7000);
// 同一份谓词必须出现两次(读取 1 次 + 完成校验 1 次)
expect((pickingSrc.match(SAME_PREDICATE) || []).length).toBe(2);
expect(body).toMatch(/FROM picking_items pi[\s\S]*LEFT JOIN order_items oi/);
+28 -16
View File
@@ -108,6 +108,22 @@ type PickingListColumnId =
type PickingDetailColumnId = 'product' | 'required' | 'picked' | 'weight' | 'diff' | 'container' | 'batch';
/** 分拣计量单位:优先库存单位(订单单位可能与 SKU 库存单位不一致,如订单个/库存斤)。 */
const pickingMeasureUnit = (item: Pick<PickingItemRow, 'unit' | 'inventory_unit'>): string => {
return String(item.inventory_unit || item.unit || '').trim();
};
const pickingMustWeigh = (
item: Pick<PickingItemRow, 'unit' | 'inventory_unit'>,
scaleRequired: boolean
): boolean => {
const inventoryUnit = pickingMeasureUnit(item);
if (!isPickingWeightUnit(inventoryUnit)) return false;
// 库存按重量管理,且订单单位不是重量单位时,必须称重;同单位沿用原有 scale 开关。
return scaleRequired || !isPickingWeightUnit(item.unit);
};
const PICKING_LIST_COLUMNS: Array<TableColumnDef<PickingListColumnId>> = [
{ id: 'pick_code', label: 'col.pick_code' },
{ id: 'scope', label: 'col.scope' },
@@ -1370,7 +1386,7 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
// 方案 1:批次合计 = 本次实际取出的量,回写实拣量(重量单位写重量列、计件写数量列)
if (item && total > 0) {
const value = String(round3(total));
if (isPickingWeightUnit(item.unit)) {
if (isPickingWeightUnit(pickingMeasureUnit(item))) {
setDraftWeight((prev) => ({ ...prev, [item.id]: value }));
} else {
setDraftQty((prev) => ({ ...prev, [item.id]: value }));
@@ -1574,18 +1590,16 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
notify(t('picking.toast.noItems'));
return;
}
if (pickingScaleRequired) {
const missingWeight = taskItems.filter((item) => {
const required = Number(item.required_qty) || 0;
if (required <= 0) return false;
if (!isPickingWeightUnit(item.unit)) return false;
const weight = Number(draftWeight[item.id] ?? item.picked_weight ?? 0) || 0;
return weight <= 0;
});
if (missingWeight.length) {
notify(t('picking.toast.needWeight', { count: missingWeight.length }));
return;
}
const missingWeight = taskItems.filter((item) => {
const required = Number(item.required_qty) || 0;
if (required <= 0) return false;
if (!pickingMustWeigh(item, pickingScaleRequired)) return false;
const weight = Number(draftWeight[item.id] ?? item.picked_weight ?? 0) || 0;
return weight <= 0;
});
if (missingWeight.length) {
notify(t('picking.toast.needWeight', { count: missingWeight.length }));
return;
}
if (
!(await confirmDialog({
@@ -1790,11 +1804,9 @@ function assigneeLabel(user: PickingAssignee, roleLabel: (code: string) => strin
if (Number(selectedTask.pick_status) >= 30) return false;
return taskItems.every((item) => {
if (!(settlementQtyOf(item.id, item) > 0)) return false;
if (!pickingScaleRequired) return true;
const required = Number(item.required_qty) || 0;
if (required <= 0) return true;
// 仅重量单位强制实拣重量;瓶/件等有数量即可
if (!isPickingWeightUnit(item.unit)) return true;
if (!pickingMustWeigh(item, pickingScaleRequired)) return true;
return (Number(draftWeight[item.id] ?? item.picked_weight ?? 0) || 0) > 0;
});
}, [taskItems, selectedTask, draftQty, draftWeight, pickingScaleRequired]);
+2
View File
@@ -26,6 +26,8 @@ export interface PickingItemRow {
picked_qty: number;
picked_weight?: number | null;
unit?: string | null;
/** SKU 库存单位;订单单位与库存单位不一致时,称重按此单位判断 */
inventory_unit?: string | null;
review_status: number;
diff_reason?: string | null;
barcode?: string | null;