主系统已回执「可以开工」(其 §2.12.9 最终契约 / §4.5.17 逐条回执,接收侧提交 c24f4881)。
按契约实现我方推送侧,**未新开端点**:文件走他们 `/api/storage/quality-reports/upload`(multipart),
登记走 `/api/supplier/quality-reports`(按备货行逐条)。
**三重门禁(开发者要求"没绑定就别传、不能造成混乱")**:
① 分公司 ↔ 主系统有 active 绑定(未绑定 ⇒ 连 token 都取不到 ⇒ 物理上发不出去)
② 该行是主系统下发的(`main_system_order_import_items` 有 prep_id 对照)
③ 该批次已人工确认关联到报告
未满足 ⇒ **零出站**(采集 SQL 里就用 JOIN 卡死,且开关关闭时连候选都不查)
**幂等(B4=我方台账去重)**:新表 `public.main_system_report_pushes`,唯一键 `(prep_id, report_type)` +
**完整文件集指纹**:指纹未变 ⇒ 不重推;指纹变了(事后补充)⇒ 按**完整文件集**重推一次
(对方 latest wins:同 (prep, type) 再登记会作废旧报告,所以不能只推新增文件)。
**契约硬语义(单测钉死)**:绝不传 `defer_coverage`(暂存态:既不覆盖也不展示);
绝不传 sku/order/branch/supplier/category/delivery(对方按行派生);`report_type` 按行要求的类型
(`qualityReportType`,本轮给拉取映射补上;取不到且该行要求报告时**不猜、跳过**);
回执映射 200 stored / 404 ignored(终态) / 400 failed(终态) / 401 换 token / 5xx 退避重试。
**触发点三处**:① 分拣完成(pickingService 成功路径,旁路 fire-and-forget)
② 报告确认关联(inventoryRoutes confirm 路由)③ scheduler tick 定时兜底(默认关 ⇒ 零出站)。
**真环境冒烟(对照主系统 3001,已跑通)**:
· 上传 ⇒ `{"kind":"ok","path":"4019fbdf…png"}`(用他们回执里的 path 登记)
· 登记 ⇒ **200** `data.id=0de8d009-d28e-4124-a333-5bef819b6dac`
`order_code/BR002/sku_code/supplier_code` 全由他们从备货行派生;我们传的
`batch_no=STK202610107YRQEO`、`product_name=香菇、平菇`、`testing_org=XX检测中心` 都正确落库;
`share_key` **不以 `st|` 开头**(= 正常覆盖态,非 defer)
· 我方台账回执:`order_code=ORD_WEB_20261010_BR002_0001`、`prep_id=b4e7fd80-668d-4f9b-b69f-dcb3fddc623e`
· ⚠️ **发现对方一处回显缺陷(已坐实,待他们修)**:`POST /api/supplier/quality-reports` 回执里
`produced_at` 比传入/库里少一天(我们传 2026-10-08、他们库 `tenant_br002.quality_reports.produced_at`
实测 = 2026-10-08,但回执 JSON = 2026-10-07);`compare_at` 同样(库 2026-10-11 / 回执 2026-10-10)
⇒ 是他们 date 列的**序列化时区**问题(值没存错,只在回显),与他们清单 §2.12.9 ⑦-1
"与你们传的一致"这条判定相冲突,需他们确认修
验证:server tsc ✅;新增 27 例(服务 14 + 调用层 13)全绿;全量 380 文件 / 2405 用例 ⇒ 失败 25 文件
= 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice;门禁同基线。
设计:docs/design/20261011-批次报告推送主系统.md;冒烟脚本:server/scripts/smoke-main-system-report-push.ts
158 lines
5.9 KiB
TypeScript
158 lines
5.9 KiB
TypeScript
import {
|
||
MAIN_SYSTEM_FETCH_TIMEOUT_MS,
|
||
isMainSystemIntegrationEnabled,
|
||
} from './config';
|
||
import {
|
||
buildMainSystemUrl,
|
||
buildMainSystemUrlWithPath,
|
||
type MainSystemEndpoint,
|
||
type MainSystemQuery,
|
||
} from './endpoints';
|
||
|
||
/**
|
||
* 主系统 HTTP **唯一出口**:超时、JSON 解析、错误归一都在这里。
|
||
*
|
||
* 为什么要有它(开发者 2026-10-11「接口注意封装」):
|
||
* · 业务层不写 `fetch`、不判 HTTP 状态码、不解析 error_description;
|
||
* · 状态码归一口径**只此一份**:401/403/408/425/429 视为**暂态**(下轮重试),
|
||
* 其余 4xx = 被拒(不重试),5xx = 主系统不可用;
|
||
* · 需要"409 其实是我们想要的结果已达成"这类特例时,用 `classify` 钩子,不另写一套。
|
||
*
|
||
* 结果四态:`ok` / `rejected` / `unavailable` / `not_configured`(与既有服务层枚举一致)。
|
||
*/
|
||
|
||
export type MainSystemResult<T> =
|
||
| {
|
||
kind: 'ok';
|
||
status: number;
|
||
data: T;
|
||
payload: unknown;
|
||
/** 仅当 `classify` 把非 2xx 判成"其实已达成"时带上(如 409 已锁定),供调用方留痕 */
|
||
reason?: string;
|
||
}
|
||
| { kind: 'rejected'; status: number; reason: string; payload: unknown }
|
||
| { kind: 'unavailable'; status: number; reason: string; payload: unknown }
|
||
| { kind: 'not_configured'; status: 0; reason: string; payload: null };
|
||
|
||
/** 自定义归类钩子:返回 null 表示按默认口径判 */
|
||
export type MainSystemClassifyHook = (params: {
|
||
status: number;
|
||
reason: string;
|
||
payload: unknown;
|
||
}) => 'ok' | 'rejected' | 'unavailable' | null;
|
||
|
||
export type MainSystemRequestOptions = {
|
||
endpoint: MainSystemEndpoint;
|
||
/** 自定义路径(跟在端点后的子路径,如 `{preparations}/lookup`) */
|
||
path?: string;
|
||
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||
/** Bearer token(oauth 接口自身不传) */
|
||
token?: string | null;
|
||
body?: unknown;
|
||
/** multipart 上传(与 `body` 互斥):给了它就不设 Content-Type,交给 fetch 生成 boundary */
|
||
formData?: FormData;
|
||
query?: MainSystemQuery;
|
||
timeoutMs?: number;
|
||
/** 超时文案(保留各调用点既有措辞,便于日志比对) */
|
||
timeoutReason?: string;
|
||
/** 网络错误文案前缀(同上) */
|
||
networkReasonPrefix?: string;
|
||
classify?: MainSystemClassifyHook;
|
||
/** 默认 true:要求域名 + 凭据齐备 */
|
||
requireConfigured?: boolean;
|
||
/** 测试注入 */
|
||
fetchImpl?: typeof fetch;
|
||
};
|
||
|
||
/** 暂态 4xx:令牌过期/被撤、超时、限流 —— 必须留给下一轮重试,不能记成"被拒" */
|
||
const TRANSIENT_4XX = new Set([401, 403, 408, 425, 429]);
|
||
|
||
export function describeMainSystemError(payload: unknown, status: number): string {
|
||
const p = payload as { error?: unknown; error_description?: unknown } | null;
|
||
const text = `${p?.error || ''} ${p?.error_description || ''}`.trim();
|
||
return text || `HTTP ${status}`;
|
||
}
|
||
|
||
export async function requestMainSystem<T = any>(
|
||
options: MainSystemRequestOptions
|
||
): Promise<MainSystemResult<T>> {
|
||
if (options.requireConfigured !== false && !isMainSystemIntegrationEnabled()) {
|
||
return {
|
||
kind: 'not_configured',
|
||
status: 0,
|
||
reason: '主系统对接未配置(MAIN_SYSTEM_BASE_URL / MAIN_SYSTEM_INTEGRATION_CLIENT_ID / _SECRET)',
|
||
payload: null,
|
||
};
|
||
}
|
||
|
||
let url: string;
|
||
try {
|
||
url = options.path
|
||
? buildMainSystemUrlWithPath(options.path, options.query)
|
||
: buildMainSystemUrl(options.endpoint, options.query);
|
||
} catch (error: any) {
|
||
return {
|
||
kind: 'not_configured',
|
||
status: 0,
|
||
reason: String(error?.message || error),
|
||
payload: null,
|
||
};
|
||
}
|
||
|
||
const timeoutMs = options.timeoutMs ?? MAIN_SYSTEM_FETCH_TIMEOUT_MS;
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||
const doFetch = options.fetchImpl || fetch;
|
||
try {
|
||
const headers: Record<string, string> = { Accept: 'application/json' };
|
||
if (options.token) headers.Authorization = `Bearer ${options.token}`;
|
||
// multipart 不能自己设 Content-Type(boundary 由 fetch 生成)
|
||
if (options.body !== undefined && !options.formData) headers['Content-Type'] = 'application/json';
|
||
|
||
const response = await doFetch(url, {
|
||
method: options.method || 'GET',
|
||
headers,
|
||
...(options.formData
|
||
? { body: options.formData }
|
||
: options.body === undefined
|
||
? {}
|
||
: { body: JSON.stringify(options.body) }),
|
||
signal: controller.signal,
|
||
});
|
||
const payload: unknown = await response.json().catch(() => null);
|
||
|
||
if (!response.ok) {
|
||
const reason = describeMainSystemError(payload, response.status);
|
||
const custom = options.classify?.({ status: response.status, reason, payload });
|
||
if (custom === 'ok') return { kind: 'ok', status: response.status, data: payload as T, payload, reason };
|
||
if (custom === 'rejected') return { kind: 'rejected', status: response.status, reason, payload };
|
||
if (custom === 'unavailable') return { kind: 'unavailable', status: response.status, reason, payload };
|
||
if (TRANSIENT_4XX.has(response.status)) {
|
||
return { kind: 'unavailable', status: response.status, reason, payload };
|
||
}
|
||
return response.status >= 400 && response.status < 500
|
||
? { kind: 'rejected', status: response.status, reason, payload }
|
||
: { kind: 'unavailable', status: response.status, reason, payload };
|
||
}
|
||
|
||
return { kind: 'ok', status: response.status, data: payload as T, payload };
|
||
} catch (error: any) {
|
||
if (error?.name === 'AbortError') {
|
||
return {
|
||
kind: 'unavailable',
|
||
status: 0,
|
||
reason: options.timeoutReason || '调用主系统超时',
|
||
payload: null,
|
||
};
|
||
}
|
||
return {
|
||
kind: 'unavailable',
|
||
status: 0,
|
||
reason: `${options.networkReasonPrefix || '调用主系统失败:'}${error?.message || error}`,
|
||
payload: null,
|
||
};
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
}
|