450 lines
17 KiB
TypeScript
450 lines
17 KiB
TypeScript
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;
|
||
}
|
||
|
||
/** 主系统 client_request_id 只接受字母/数字/下划线/短横线,最长 64;本地 id 先归一化。 */
|
||
function normalizeRequestId(raw: unknown): string {
|
||
const cleaned = String(raw || '')
|
||
.replace(/[^0-9A-Za-z_-]/g, '_')
|
||
.slice(0, 64);
|
||
return cleaned || randomUUID();
|
||
}
|
||
|
||
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.main_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: '本地计划已保存;主系统同步未启用',
|
||
};
|
||
}
|
||
|
||
if (!String(row.main_order_item_id || '').trim()) {
|
||
await pool.query(
|
||
`UPDATE public.main_system_plan_changes
|
||
SET status = 'failed', last_error = $2, updated_at = NOW()
|
||
WHERE id = $1::uuid`,
|
||
[changeId, '缺少主系统订单行 id(请重新拉取该主系统备货行后再重试)']
|
||
);
|
||
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: '缺少主系统订单行 id,待重新拉取后同步',
|
||
};
|
||
}
|
||
|
||
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 = normalizeRequestId(input.requestId);
|
||
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,
|
||
NULLIF(TRIM(payload->>'mainOrderItemId'), '') AS main_order_item_id
|
||
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');
|
||
// 主系统订单行 id 允许暂时缺失:本地计划必须先落地;同步阶段再标失败/待补拉取。
|
||
const mainOrderItemId = String(mapping.rows[0].main_order_item_id || '').trim();
|
||
|
||
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, main_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::uuid,$5::varchar,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,'pending',$16,$17)
|
||
RETURNING id`,
|
||
[
|
||
String(item.branch_code || ''),
|
||
orderCode,
|
||
itemId,
|
||
mainOrderItemId || null,
|
||
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, main_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;
|
||
}
|