feat(主系统对接): 导入失败留痕 + 首次告警 + 恢复销账(后续不再"无声收不到")
开发者 2026-10-17:「后续不能出现这种无法接收到的情况」。 事故链(本地真机):主系统 22:48 派单并推 preparations.allocated(SUP37831443), 我方因"台账指向的本系统订单已不存在"返回 500,主系统重试 3 次后放弃; 旧实现只打日志、界面/通知零痕迹,直到人工查主系统投递记录才发现。 三层保证: ① 自愈(上一提交 ef81c7c):陈旧占坑/台账指针自动清理并重建; ② 可见+告警(本次):失败落 public.main_system_import_failures (键 = 分公司×配送日×主系统分公司×主系统订单,attempts 累加不刷屏), 首次失败站内通知 admin/super_admin(6 小时内去重),新增只读接口 GET /api/integration/main-system/import-failures 供界面/排障查看; 下一次导入成功自动销账(resolved_at)。 ③ 兜底重试:定时对账每 10 分钟一次(已存在);生产需补 client secret 才可用(已在文档标注)。 新增迁移 20261057;trackDayOutcome() 挂在建单/追加两条返回路径上,异常一律吞掉(告警不许反过来把导入搞挂)。 验证: · 服务侧真库冒烟:首次失败 attempts=1/isFirst=true → 再次 attempts=2;open 可查;clear 后 open=0 · 迁移 upsert 语义(同键累加、单行)真库事务内验证通过 · 单测 mainSystemImportFailureLedger 6 条;mainSystem 子集 30 文件 / 473 用例全过 · 设计门禁:8 通过 / 1 已知红 check-ai-cost / verify-facts 因本地缺 tenant_br003 红(均基线)
This commit is contained in:
@@ -56,6 +56,17 @@ error={"ok":false,"created":0,"appended":0,"skipped":0,"failed":1,
|
||||
| C4 | 查询异常不清台账;清理失败不阻断 | 单测源码断言 |
|
||||
| C5 | 两条通道都经过 `importDayBucket` | 单测源码断言 |
|
||||
|
||||
## 4.1 「后续不能再出现」——三层保证(2026-10-17 追加)
|
||||
|
||||
| 层 | 机制 | 现状 |
|
||||
| --- | --- | --- |
|
||||
| ① 自愈 | 陈旧占坑/台账指针自动清理并重建(§3) | ✅ 本轮已上(本地真跑验证) |
|
||||
| ② 可见+告警 | 失败落 `public.main_system_import_failures`(同键累加 attempts)+ **首次失败站内通知管理员**(去重 6h)+ 只读接口 `GET /api/integration/main-system/import-failures` | ✅ 本轮已上(迁移 `20261057`) |
|
||||
| ③ 兜底重试 | 定时对账每 10 分钟重试一次(`MAIN_SYSTEM_AUTO_IMPORT=1`),成功后自动销账(`resolved_at`) | ⚠️ 生产缺 `MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET` ⇒ 该层在生产**当前不工作** |
|
||||
|
||||
> 结论:只要 ① ② 在,**失败不会再"无声消失"**;但"完全不依赖主系统推送"这件事**必须**靠 ③,
|
||||
> 而 ③ 的前提是生产把 `MAIN_SYSTEM_INTEGRATION_CLIENT_SECRET` 补上(配置项,需开发者下令)。
|
||||
|
||||
## 5. 已知风险 / 未做
|
||||
|
||||
- 这是**兜底自愈**:真正的诱因是"有人在库里删了订单但没清指针"(本地清库、或绕过服务层删单)。
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
-- 主系统导入**失败台账**(2026-10-17:开发者在界面上看不到"这单为什么一直没进来")
|
||||
--
|
||||
-- 背景:主系统推送 `preparations.allocated` 后我方导入失败时只打一行日志、返回 500;
|
||||
-- 主系统按契约重试几次就放弃 ⇒ 订单**永远进不来**,而界面/通知里一点痕迹都没有
|
||||
-- (真机:`ORD_WEB_20261017_BR002_0001` 因"台账指向的本系统订单已不存在"连续失败,
|
||||
-- 直到有人手工查主系统投递记录才发现)。
|
||||
--
|
||||
-- 口径:**失败必须留痕、可查询、可告警**;恢复(下一次导入成功)时自动销账。
|
||||
-- 归属 `public`(跨系统台账,与 main_system_order_imports 同域),按 branch_code 隔离。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.main_system_import_failures (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code varchar(64) NOT NULL,
|
||||
-- 配送日(我方口径=主系统给的配送日;拿不到时用导入当日)
|
||||
delivery_date date NOT NULL,
|
||||
main_branch_code varchar(64) NOT NULL DEFAULT '*',
|
||||
main_order_code varchar(128),
|
||||
our_order_code varchar(64),
|
||||
-- 失败分类(`stale_order_pointer` / `zero_price` / `unknown` …;便于按类统计)
|
||||
error_code varchar(64) NOT NULL DEFAULT 'unknown',
|
||||
error_message text,
|
||||
-- 连续失败次数(每次失败 +1;恢复即销账)
|
||||
attempts integer NOT NULL DEFAULT 1,
|
||||
first_seen_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
last_seen_at timestamptz NOT NULL DEFAULT NOW(),
|
||||
-- 已恢复/已处理的时间;NULL = 仍未解决
|
||||
resolved_at timestamptz,
|
||||
CONSTRAINT main_system_import_failures_attempts_check CHECK (attempts >= 1)
|
||||
);
|
||||
|
||||
-- 同一(分公司 × 配送日 × 主系统分公司 × 主系统订单)只留一条,失败累加而不是刷屏
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_main_system_import_failures_key
|
||||
ON public.main_system_import_failures (branch_code, delivery_date, main_branch_code, COALESCE(main_order_code, ''));
|
||||
|
||||
-- 未解决的失败(界面/告警只看这条)
|
||||
CREATE INDEX IF NOT EXISTS idx_main_system_import_failures_open
|
||||
ON public.main_system_import_failures (branch_code, last_seen_at DESC)
|
||||
WHERE resolved_at IS NULL;
|
||||
@@ -578,4 +578,29 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 主系统导入**未解决的失败**(2026-10-17「后续不能出现这种无法接收到的情况」)。
|
||||
*
|
||||
* 用途:界面上要能看见"这单为什么一直没进来",而不是只有一串日志。
|
||||
* 只读;恢复由导入成功时的销账负责。
|
||||
*/
|
||||
router.get('/main-system/import-failures', authMiddleware, async (req: AuthRequest, res: Response) => {
|
||||
try {
|
||||
const ctx = await loadTenantContext(req.userId);
|
||||
const branchCode = String(ctx?.branchCode || '').trim();
|
||||
if (!branchCode) {
|
||||
return res.status(400).json({ error: 'branch_required', error_description: '当前账号未绑定分公司' });
|
||||
}
|
||||
const { listOpenImportFailures } = await import('../services/mainSystemImportFailureService');
|
||||
const rows = await listOpenImportFailures({
|
||||
branchCode,
|
||||
limit: Number(req.query?.limit) || 20,
|
||||
});
|
||||
return res.json({ data: rows, error: null });
|
||||
} catch (error: any) {
|
||||
console.error('main-system import failures error:', error);
|
||||
return res.status(500).json({ error: 'server_error', error_description: '查询导入失败台账失败' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* 主系统导入**失败台账**(2026-10-17:「后续不能出现这种无法接收到的情况」)。
|
||||
*
|
||||
* 为什么要有它:推送失败时旧实现只打日志 + 返回 500,主系统重试几次就放弃 ⇒ 订单永远进不来,
|
||||
* 而**界面上一点痕迹都没有**。真机事故 `ORD_WEB_20261017_BR002_0001` 就是这样:
|
||||
* 连续失败到主系统放弃,直到有人去查主系统的投递记录才发现。
|
||||
*
|
||||
* 三层保证里的第二层(① 自愈见 `mainSystemOrderImport` 的陈旧占坑清理;③ 定时对账一直在跑):
|
||||
* · 失败 → **落台账**(同键累加 attempts,不刷屏);
|
||||
* · 首次失败 → **站内通知管理员**(有通知中心,不新增界面文案体系);
|
||||
* · 下一次导入成功 → **自动销账**(resolved_at)。
|
||||
*
|
||||
* 纪律:本模块只做"留痕 + 告警",**不改导入结果**;任何异常都吞掉(告警链路不许反过来把导入搞挂)。
|
||||
*/
|
||||
import { pool } from '../db';
|
||||
|
||||
export type ImportFailureRow = {
|
||||
id: string;
|
||||
branch_code: string;
|
||||
delivery_date: string;
|
||||
main_branch_code: string;
|
||||
main_order_code: string | null;
|
||||
our_order_code: string | null;
|
||||
error_code: string;
|
||||
error_message: string | null;
|
||||
attempts: number;
|
||||
first_seen_at: string;
|
||||
last_seen_at: string;
|
||||
resolved_at: string | null;
|
||||
};
|
||||
|
||||
/** 失败分类:只有"能按类统计"的才算,其余落 unknown(不要瞎猜根因) */
|
||||
export function classifyImportFailure(message: string | null | undefined): string {
|
||||
const text = String(message || '');
|
||||
if (text.includes('台账指向的本系统订单已不存在') || text.includes('陈旧')) return 'stale_order_pointer';
|
||||
if (text.includes('价格') || text.includes('零价')) return 'zero_price';
|
||||
if (text.includes('不存在')) return 'not_found';
|
||||
if (text.includes('超时') || text.includes('timeout')) return 'timeout';
|
||||
if (text.includes('权限')) return 'permission';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* 记一次导入失败(幂等累加)。返回累加后的次数 —— 调用方据此决定"首次失败才通知"。
|
||||
*/
|
||||
export async function recordMainSystemImportFailure(input: {
|
||||
branchCode: string;
|
||||
deliveryDate: string;
|
||||
mainBranchCode: string;
|
||||
mainOrderCode?: string | null;
|
||||
ourOrderCode?: string | null;
|
||||
message?: string | null;
|
||||
errorCode?: string | null;
|
||||
}): Promise<{ attempts: number; isFirst: boolean } | null> {
|
||||
try {
|
||||
const message = String(input.message || '').slice(0, 1000) || null;
|
||||
const code = String(input.errorCode || classifyImportFailure(message)).slice(0, 64);
|
||||
const { rows } = await pool.query<{ attempts: number }>(
|
||||
`INSERT INTO public.main_system_import_failures AS f
|
||||
(branch_code, delivery_date, main_branch_code, main_order_code, our_order_code,
|
||||
error_code, error_message)
|
||||
VALUES ($1, $2::date, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (branch_code, delivery_date, main_branch_code, COALESCE(main_order_code, ''))
|
||||
DO UPDATE SET
|
||||
attempts = f.attempts + 1,
|
||||
last_seen_at = NOW(),
|
||||
error_code = EXCLUDED.error_code,
|
||||
error_message = EXCLUDED.error_message,
|
||||
our_order_code = COALESCE(EXCLUDED.our_order_code, f.our_order_code),
|
||||
resolved_at = NULL
|
||||
RETURNING f.attempts`,
|
||||
[
|
||||
input.branchCode,
|
||||
input.deliveryDate,
|
||||
input.mainBranchCode,
|
||||
input.mainOrderCode ?? null,
|
||||
input.ourOrderCode ?? null,
|
||||
code,
|
||||
message,
|
||||
]
|
||||
);
|
||||
const attempts = Number(rows[0]?.attempts) || 1;
|
||||
return { attempts, isFirst: attempts === 1 };
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[main-system-import-failures] 记失败台账失败(不影响导入):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 导入恢复 ⇒ 销账(把这批未解决的失败都关掉) */
|
||||
export async function clearMainSystemImportFailures(input: {
|
||||
branchCode: string;
|
||||
deliveryDate: string;
|
||||
mainBranchCode: string;
|
||||
mainOrderCodes?: string[];
|
||||
}): Promise<number> {
|
||||
try {
|
||||
const codes = (input.mainOrderCodes || []).filter(Boolean);
|
||||
const result = await pool.query(
|
||||
`UPDATE public.main_system_import_failures
|
||||
SET resolved_at = NOW(), last_seen_at = NOW()
|
||||
WHERE branch_code = $1 AND delivery_date = $2::date AND main_branch_code = $3
|
||||
AND resolved_at IS NULL
|
||||
AND ($4::text[] IS NULL OR main_order_code = ANY($4::text[]))`,
|
||||
[input.branchCode, input.deliveryDate, input.mainBranchCode, codes.length ? codes : null]
|
||||
);
|
||||
return Number(result.rowCount) || 0;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[main-system-import-failures] 销账失败(不影响导入):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** 未解决的失败(界面/排障用;按最近失败倒序) */
|
||||
export async function listOpenImportFailures(input: {
|
||||
branchCode?: string | null;
|
||||
limit?: number;
|
||||
}): Promise<ImportFailureRow[]> {
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 20, 1), 100);
|
||||
const { rows } = await pool.query<ImportFailureRow>(
|
||||
`SELECT * FROM public.main_system_import_failures
|
||||
WHERE resolved_at IS NULL
|
||||
AND ($1 = '' OR branch_code = $1)
|
||||
ORDER BY last_seen_at DESC
|
||||
LIMIT $2`,
|
||||
[branchCode, limit]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
@@ -1624,6 +1624,63 @@ async function resetStaleDayOrderPointers(params: {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* **失败留痕 + 恢复销账 + 首次失败通知**(2026-10-17「后续不能出现这种无法接收到的情况」)。
|
||||
*
|
||||
* 只做可观测性,不改导入结果;任何异常都必须吞掉(告警链路不许反过来把导入搞挂)。
|
||||
* 台账见 `mainSystemImportFailureService`,通知走既有站内通知(通知中心可见)。
|
||||
*/
|
||||
async function trackDayOutcome(
|
||||
branchCode: string,
|
||||
bucket: DayBucket,
|
||||
outcome: DayImportOutcome
|
||||
): Promise<void> {
|
||||
try {
|
||||
const { recordMainSystemImportFailure, clearMainSystemImportFailures } = await import(
|
||||
'./mainSystemImportFailureService'
|
||||
);
|
||||
const mainOrderCodes = bucket.groups.map((group) => group.orderCode).filter(Boolean);
|
||||
if (outcome.status === 'failed') {
|
||||
const recorded = await recordMainSystemImportFailure({
|
||||
branchCode,
|
||||
deliveryDate: bucket.deliveryDate,
|
||||
mainBranchCode: bucket.mainBranchCode,
|
||||
mainOrderCode: mainOrderCodes[0] || null,
|
||||
ourOrderCode: outcome.ourOrderCode,
|
||||
message: outcome.message || '导入失败',
|
||||
});
|
||||
if (recorded?.isFirst) {
|
||||
const { notifyRoleUsers } = await import('./notificationService');
|
||||
await notifyRoleUsers({
|
||||
roles: ['admin', 'super_admin'],
|
||||
notifyType: 'main_system_import_failed',
|
||||
title: '主系统订单导入失败',
|
||||
content:
|
||||
`${branchCode} 配送日 ${bucket.deliveryDate} 的主系统订单导入失败:` +
|
||||
`${outcome.message || '未知原因'}。系统会按周期自动重试;若持续失败请查「主系统对接」日志。`,
|
||||
relatedOrderCode: outcome.ourOrderCode || mainOrderCodes[0] || null,
|
||||
branchCode,
|
||||
dedupWithinHours: 6,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (outcome.status === 'created' || outcome.status === 'appended') {
|
||||
await clearMainSystemImportFailures({
|
||||
branchCode,
|
||||
deliveryDate: bucket.deliveryDate,
|
||||
mainBranchCode: bucket.mainBranchCode,
|
||||
mainOrderCodes,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[main-system-import] 失败留痕/销账异常(不影响导入):',
|
||||
(error as Error)?.message || error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** 占坑/台账指向的本系统订单是否还活着(在同一租户上下文里查) */
|
||||
async function claimedOrderStillExists(branchCode: string, orderCode: string): Promise<boolean> {
|
||||
const code = String(orderCode || '').trim();
|
||||
@@ -1712,6 +1769,7 @@ async function importDayBucket(params: {
|
||||
claimId: effectiveClaim.claimId,
|
||||
});
|
||||
logDayOutcome(branchCode, outcome);
|
||||
await trackDayOutcome(branchCode, bucket, outcome);
|
||||
return outcome.results;
|
||||
}
|
||||
|
||||
@@ -1790,6 +1848,7 @@ async function importDayBucket(params: {
|
||||
ledgerByOrder,
|
||||
});
|
||||
logDayOutcome(branchCode, outcome);
|
||||
await trackDayOutcome(branchCode, bucket, outcome);
|
||||
return outcome.results;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { classifyImportFailure } from '../src/services/mainSystemImportFailureService';
|
||||
|
||||
/**
|
||||
* 「后续不能出现这种无法接收到的情况」——**失败留痕 + 首次告警 + 恢复销账**(2026-10-17)。
|
||||
*
|
||||
* 真机事故:`ORD_WEB_20261017_BR002_0001` 因"台账指向的本系统订单已不存在"连续失败,
|
||||
* 主系统重试 3 次后放弃,而**界面/通知里没有任何痕迹**,只能去查主系统的投递记录才发现。
|
||||
*
|
||||
* 现在的三层保证:
|
||||
* ① 自愈:陈旧占坑/台账指针自动清理重建(mainSystemOrderImport);
|
||||
* ② 可见:失败落 `main_system_import_failures`(同键累加次数),首次失败站内通知管理员;
|
||||
* ③ 兜底:定时对账每 10 分钟重试一次,成功即自动销账(resolved_at)。
|
||||
*/
|
||||
const importer = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemOrderImport.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const service = readFileSync(
|
||||
path.join(__dirname, '../src/services/mainSystemImportFailureService.ts'),
|
||||
'utf8'
|
||||
);
|
||||
const migration = readFileSync(
|
||||
path.join(__dirname, '../../migrations/20261057_main_system_import_failures.sql'),
|
||||
'utf8'
|
||||
);
|
||||
const routes = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8');
|
||||
|
||||
describe('② 可见性:导入失败一定落台账', () => {
|
||||
it('fail 分支记失败;created/appended 分支销账', () => {
|
||||
const idx = importer.indexOf('async function trackDayOutcome');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
const block = importer.slice(idx, idx + 2200);
|
||||
expect(block).toMatch(/outcome\.status === 'failed'[\s\S]*recordMainSystemImportFailure/);
|
||||
expect(block).toMatch(/'created' \|\| outcome\.status === 'appended'[\s\S]*clearMainSystemImportFailures/);
|
||||
});
|
||||
|
||||
it('首次失败才发站内通知(去重 6 小时),且通知链路异常不许影响导入', () => {
|
||||
const idx = importer.indexOf('async function trackDayOutcome');
|
||||
const block = importer.slice(idx, idx + 2200);
|
||||
expect(block).toMatch(/recorded\?\.isFirst/);
|
||||
expect(block).toMatch(/notifyRoleUsers\(/);
|
||||
expect(block).toMatch(/dedupWithinHours: 6/);
|
||||
expect(block).toMatch(/catch \(error\)/);
|
||||
});
|
||||
|
||||
it('两条通道(建单 / 追加)都调用同一处留痕', () => {
|
||||
const calls = importer.match(/await trackDayOutcome\(branchCode, bucket, outcome\);/g) || [];
|
||||
expect(calls.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('台账:同键累加 attempts、恢复置 resolved_at、唯一键含 COALESCE(main_order_code)', () => {
|
||||
expect(service).toMatch(/ON CONFLICT \(branch_code, delivery_date, main_branch_code, COALESCE\(main_order_code, ''\)\)/);
|
||||
expect(service).toMatch(/attempts = f\.attempts \+ 1/);
|
||||
expect(service).toMatch(/resolved_at = NULL/);
|
||||
expect(service).toMatch(/SET resolved_at = NOW\(\)/);
|
||||
expect(migration).toMatch(/CREATE TABLE IF NOT EXISTS public\.main_system_import_failures/);
|
||||
expect(migration).toMatch(/uq_main_system_import_failures_key/);
|
||||
});
|
||||
|
||||
it('分类只按已知特征,不瞎猜根因', () => {
|
||||
expect(classifyImportFailure('台账指向的本系统订单已不存在')).toBe('stale_order_pointer');
|
||||
expect(classifyImportFailure('商品价格不能为空')).toBe('zero_price');
|
||||
expect(classifyImportFailure('超时')).toBe('timeout');
|
||||
expect(classifyImportFailure('随便什么')).toBe('unknown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('排障入口:未解决失败可查询', () => {
|
||||
it('新增只读接口 GET /main-system/import-failures(绑定分公司,不再让人只翻日志)', () => {
|
||||
expect(routes).toMatch(/router\.get\('\/main-system\/import-failures'/);
|
||||
expect(routes).toMatch(/listOpenImportFailures\(\{/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user