Files
SupplierSystem/server/src/services/batchOriginReportService.ts
T
Ubuntu 5a54480bdc
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
feat(产地): 上报带主系统订单号 + 主系统 SKU(可注入解析器)
- 供应商 SKU → 主系统 SKU:默认读本地只读镜像 main_system_sku_mappings(active),
  抽成可注入 resolveMainSku(测试用纯函数,避免依赖租户上下文)
- 未映射 ⇒ 跳过不上报(仅日志),不影响取货/到仓主流程
- preparations/status body 增 order_code + sku_code(主系统可据此直接定位订单行)
- 测试:16 passed(注入解析器后原两条用例恢复)
2026-10-20 13:13:14 +08:00

231 lines
9.6 KiB
TypeScript
Raw 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 { pool } from '../db';
import { runWithTenantDbContext } from './tenantDbContext';
import { isMainSystemIntegrationEnabled } from './mainSystem/config';
import { writebackMainSystemPreparationStatus } from './mainSystemPreparations';
import { resolveSupplierCodeForPrep } from './branchAccessCode';
/**
* **批次级产地上报**(2026-10-21)——「取货完成」/「配送上仓库完成」两个节点。
*
* 冻结口径(Lead / 用户):
* · 产地是**批次级 + 商品档案默认值**;有产地才发(批次优先,空则 `skus.origin` 兜底);
* · 与主系统对齐的接口 = **既有** `POST /api/supplier/preparations/status`(不新开端点):
* body 增 `batch_no` + `origin`(主系统要求两者成对,只落到同批次已有行、空值才写);
* · **fire-and-forget**:失败仅日志,绝不阻塞/回滚/弹错供应商主流程。
*
* 调用点(与需求对应):
* · `orderWorkflowFulfillmentService.completeOrderWithoutDriverDelivery` 成功后 = **取货完成**;
* · `orderWorkflowFulfillmentService.finalizeOrderFulfillment` 成功后 = **配送上仓库完成**。
* 两处都是"订单结案 90 之后"异步触发,不 await(本函数自身也从不抛错)。
*
* 设计:docs/design/20261021-批次级产地.md §4
*/
export type BatchOriginReportNode = 'pickup_complete' | 'inbound_complete';
export type BatchOriginReportResult = {
node: BatchOriginReportNode;
orderCode: string;
/** 命中(有产地)的批次条数 */
batches: number;
sent: number;
failed: number;
skipped: number;
};
const MAX_REPORTS_PER_ORDER = 50;
type BatchOriginRow = {
sku_code: string;
batch_no: string;
origin: string;
prep_ids: string[] | null;
main_supplier_code: string | null;
};
/**
* 「取货完成 / 到仓完成」后把**有产地**的批次上报主系统。
*
* 数据来源(只读):
* · 本单消耗的批次 = `picking_items.outbound_batches` ∪ `inventory_logs(picking_out/delivery_loading_out)`;
* · 产地 = `inventory.origin`(批次优先)→ `skus.origin`(商品档案兜底);
* · 备货行 = `public.main_system_order_import_items`(our_order_item_id → prep_id)。
*
* 本函数**永不抛错**:任何异常都吞掉并打日志(fire-and-forget 的语义要求)。
*/
export async function reportBatchOriginsToMainSystem(input: {
orderCode: string;
node: BatchOriginReportNode;
/** 可不传:自动从订单读(订单已结案,branch_code 仍可读) */
branchCode?: string | null;
/**
* 供应商 SKU → 主系统 SKU 解析器(默认读本地只读镜像 main_system_sku_mappings)。
* 抽成参数是为了可测:测试注入纯函数即可,不需要真租户上下文。
*/
resolveMainSku?: (supplierSkuCode: string) => Promise<string | null>;
}): Promise<BatchOriginReportResult> {
const result: BatchOriginReportResult = {
node: input.node,
orderCode: String(input.orderCode || ''),
batches: 0,
sent: 0,
failed: 0,
skipped: 0,
};
const orderCode = String(input.orderCode || '').trim();
if (!orderCode) return result;
if (!isMainSystemIntegrationEnabled()) {
result.skipped += 1;
return result;
}
try {
const branchCode = String(input.branchCode || '').trim();
let effectiveBranch = branchCode;
if (!effectiveBranch) {
// 先用平台侧台账找主系统供应商编码(不依赖租户上下文)
const bound = await pool.query<{ branch_code: string }>(
`SELECT branch_code FROM public.main_system_order_imports WHERE our_order_code = $1 LIMIT 1`,
[orderCode]
);
effectiveBranch = bound.rows[0]?.branch_code ? String(bound.rows[0].branch_code) : '';
}
if (!effectiveBranch) {
result.skipped += 1;
return result;
}
const rows = await runWithTenantDbContext(effectiveBranch, async () => {
const queried = await pool.query<BatchOriginRow>(
`WITH consumed AS (
-- 源①:分拣选定/计划批次
SELECT h.batch_no, h.sku_code
FROM picking_items pi
JOIN order_items oi ON oi.id = pi.order_item_id
CROSS JOIN LATERAL jsonb_array_elements(
CASE WHEN jsonb_typeof(pi.outbound_batches) = 'array' THEN pi.outbound_batches ELSE '[]'::jsonb END
) e
JOIN LATERAL (SELECT e->>'batch_no' AS batch_no, oi.sku_code AS sku_code) h ON TRUE
WHERE oi.order_code = $1 AND pi.branch_code = $2 AND NULLIF(TRIM(h.batch_no), '') IS NOT NULL
UNION
-- 源②:实际出库流水(含免入库骑手上门取货的软扣)
SELECT il.batch_no, il.sku_code
FROM inventory_logs il
WHERE il.related_order_code = $1
AND il.branch_code = $2
AND il.batch_no IS NOT NULL
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
)
SELECT c.sku_code,
c.batch_no,
COALESCE(NULLIF(TRIM(inv.origin), ''), NULLIF(TRIM(sk.origin), '')) AS origin,
array_remove(array_agg(DISTINCT l.prep_id::text), NULL) AS prep_ids,
(array_agg(DISTINCT l.main_supplier_code))[1] AS main_supplier_code
FROM consumed c
LEFT JOIN inventory inv
ON inv.batch_no = c.batch_no AND inv.sku_code = c.sku_code AND inv.branch_code = $2
LEFT JOIN skus sk ON sk.sku_code = c.sku_code AND sk.branch_code = $2
LEFT JOIN order_items oi ON oi.order_code = $1 AND oi.sku_code = c.sku_code
LEFT JOIN public.main_system_order_import_items l
ON l.our_order_item_id = oi.id AND l.branch_code = $2
WHERE COALESCE(NULLIF(TRIM(inv.origin), ''), NULLIF(TRIM(sk.origin), '')) IS NOT NULL
GROUP BY c.sku_code, c.batch_no,
COALESCE(NULLIF(TRIM(inv.origin), ''), NULLIF(TRIM(sk.origin), ''))
LIMIT ${MAX_REPORTS_PER_ORDER}`,
[orderCode, effectiveBranch]
);
return queried.rows;
});
result.batches = rows.length;
if (!rows.length) return result;
for (const row of rows) {
const prepIds = (row.prep_ids || []).map(String).filter(Boolean);
if (!prepIds.length) {
result.skipped += 1;
continue;
}
// 换主系统 SKU(默认读本地只读镜像);未映射 ⇒ 不上报(只日志),不影响主流程
const resolveMainSku =
input.resolveMainSku ||
(async (supplierSkuCode: string) => {
const mapped = await runWithTenantDbContext(effectiveBranch, async () => {
const hit = await pool.query<{ delivery_sku_code: string | null }>(
`SELECT delivery_sku_code FROM main_system_sku_mappings
WHERE supplier_sku_code = $1 AND status = 'active'
AND NULLIF(TRIM(delivery_sku_code), '') IS NOT NULL
LIMIT 1`,
[supplierSkuCode]
);
return hit.rows[0]?.delivery_sku_code ? String(hit.rows[0].delivery_sku_code) : null;
});
return mapped ?? null;
});
const mainSkuCode = await resolveMainSku(row.sku_code).catch(() => null);
if (!mainSkuCode) {
result.skipped += 1;
continue;
}
for (const prepId of prepIds) {
// 每个备货行取本分公司的主系统供应商编码(失败则跳过该行,不影响其它行/主流程)
const supplierCode = await resolveSupplierCodeForPrep({ branchCode: effectiveBranch, prepId }).catch(() => null);
if (!supplierCode) {
result.skipped += 1;
continue;
}
try {
const outcome = await writebackMainSystemPreparationStatus({
supplierCode,
preparationId: prepId,
// 两个节点都等价于主系统的「备货完成」;带 origin 只是顺带上报批次产地
status: 30,
batchNo: row.batch_no,
origin: row.origin,
orderCode: input.orderCode,
mainSkuCode,
});
if (outcome.kind === 'ok' || outcome.kind === 'already_done') result.sent += 1;
else {
result.failed += 1;
const reason = 'reason' in outcome ? outcome.reason : '';
console.warn(
`[batch-origin] 上报未成功(order=${orderCode}, prep=${prepId}, batch=${row.batch_no}, ` +
`node=${input.node}):${outcome.kind} ${reason}`
);
}
} catch (error: any) {
result.failed += 1;
console.warn(
`[batch-origin] 上报异常(order=${orderCode}, prep=${prepId}, batch=${row.batch_no}):`,
error?.message || error
);
}
}
}
if (result.failed || result.sent) {
console.log(
`[batch-origin] ${input.node} order=${orderCode}: 批次 ${result.batches}、发送 ${result.sent}、失败 ${result.failed}、跳过 ${result.skipped}`
);
}
return result;
} catch (error: any) {
result.failed += 1;
console.warn(
`[batch-origin] ${input.node} order=${orderCode} 上报整体失败(不影响主流程):`,
error?.message || error
);
return result;
}
}
/** fire-and-forget 包装:绝不返回 rejected promise,调用方 `void` 即可 */
export function fireAndForgetBatchOriginReport(input: {
orderCode: string;
node: BatchOriginReportNode;
branchCode?: string | null;
}): void {
void reportBatchOriginsToMainSystem(input).catch((error) => {
console.warn('[batch-origin] fire-and-forget 兜底日志:', error?.message || error);
});
}