feat: 完成P10生产硬化与矩阵收口(P10E1-P10G1)

这个提交包含在:
2026-02-10 11:25:18 +08:00
父节点 1b6e801b12
当前提交 bec21e1b38
共修改 15 个文件,包含 1718 行新增和 793 行删除
@@ -0,0 +1,58 @@
const { pushPaidReimbursementToErp } = require("./erp");
class IntegrationDispatchError extends Error {
constructor({ code, message, retryable, statusCode, response }) {
super(message || code || "integration_dispatch_failed");
this.name = "IntegrationDispatchError";
this.code = code || "integration_dispatch_failed";
this.retryable = typeof retryable === "boolean" ? retryable : true;
this.statusCode = Number.isFinite(statusCode) ? Number(statusCode) : null;
this.response = response ?? null;
}
}
function toDispatchError(result) {
return new IntegrationDispatchError({
code: result?.code,
message: result?.message,
retryable: result?.retryable,
statusCode: result?.httpStatus,
response: result?.response,
});
}
async function dispatchOutboxEvent({ config, eventType, payload }) {
if (eventType === "erp.reimbursement.paid") {
const result = await pushPaidReimbursementToErp(config, payload);
if (!result.ok) {
throw toDispatchError(result);
}
return {
channel: "erp",
code: result.code,
response: result.response ?? null,
};
}
if (eventType === "notification.im") {
return {
channel: "im",
code: "mock_sent",
response: {
channelType: payload.channelType,
},
};
}
throw new IntegrationDispatchError({
code: "unsupported_outbox_event",
message: `unsupported_outbox_event:${eventType}`,
retryable: false,
});
}
module.exports = {
IntegrationDispatchError,
dispatchOutboxEvent,
};
+157
查看文件
@@ -0,0 +1,157 @@
function buildErpPayload(input) {
return {
reimbursementId: input.reimbursement.id,
formNumber: input.reimbursement.form_number,
ownerEmployeeId: input.reimbursement.owner_id,
submitterEmployeeId: input.reimbursement.submitter_id,
totalAmount: input.reimbursement.total_amount?.toString?.() ?? null,
paymentVoucherNo: input.reimbursement.payment_voucher_no ?? null,
paymentDate: input.reimbursement.payment_date
? new Date(input.reimbursement.payment_date).toISOString().slice(0, 10)
: null,
paidAt: input.reimbursement.paid_at ? new Date(input.reimbursement.paid_at).toISOString() : null,
};
}
function normalizeProvider(config) {
return String(config.erpSyncProvider ?? "mock").trim().toLowerCase() || "mock";
}
function buildAuthHeaders(config) {
const token = String(config.erpSyncAuthToken ?? "").trim();
if (!token) {
return {};
}
return {
authorization: `Bearer ${token}`,
};
}
async function postToErpHttp(config, payload) {
const endpoint = String(config.erpSyncEndpoint ?? "").trim();
if (!endpoint) {
return {
ok: false,
code: "erp_sync_endpoint_missing",
message: "ERP sync endpoint missing",
retryable: false,
};
}
const timeoutMs = Math.max(100, Number(config.erpSyncTimeoutMs ?? 5000));
const controller = new AbortController();
const timer = setTimeout(() => {
controller.abort();
}, timeoutMs);
try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"content-type": "application/json",
...buildAuthHeaders(config),
},
body: JSON.stringify(payload),
signal: controller.signal,
});
let responseBody = null;
const contentType = response.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
try {
responseBody = await response.json();
} catch {
responseBody = null;
}
} else {
try {
responseBody = await response.text();
} catch {
responseBody = null;
}
}
if (response.ok) {
return {
ok: true,
code: "http_synced",
message: "ERP synced",
response: {
status: response.status,
body: responseBody,
},
};
}
const retryable = response.status >= 500;
return {
ok: false,
code: retryable ? "erp_sync_http_5xx" : "erp_sync_http_4xx",
message: `ERP sync HTTP ${response.status}`,
retryable,
httpStatus: response.status,
response: {
status: response.status,
body: responseBody,
},
};
} catch (error) {
if (error?.name === "AbortError") {
return {
ok: false,
code: "erp_sync_timeout",
message: `ERP sync timeout (${timeoutMs}ms)`,
retryable: true,
};
}
return {
ok: false,
code: "erp_sync_network_error",
message: String(error?.message ?? error ?? "ERP sync network error"),
retryable: true,
};
} finally {
clearTimeout(timer);
}
}
async function pushPaidReimbursementToErp(config, payload) {
if (!config.erpSyncEnabled) {
return {
ok: false,
code: "erp_sync_disabled",
message: "ERP sync disabled",
retryable: false,
};
}
const provider = normalizeProvider(config);
if (provider === "mock") {
return {
ok: true,
code: "mock_synced",
message: "mock ERP synced",
response: {
externalId: `ERP-${payload.formNumber ?? payload.reimbursementId}`,
},
};
}
if (provider === "http") {
return postToErpHttp(config, payload);
}
return {
ok: false,
code: "erp_sync_provider_invalid",
message: `Unsupported ERP sync provider: ${provider}`,
retryable: false,
};
}
module.exports = {
buildErpPayload,
pushPaidReimbursementToErp,
};
+161
查看文件
@@ -0,0 +1,161 @@
const OUTBOX_STATUSES = {
pending: "pending",
processing: "processing",
succeeded: "succeeded",
failed: "failed",
dead_letter: "dead_letter",
};
function nextRetryAt(config, attempts) {
const waitSeconds = Math.max(30, Number(config.integrationOutboxRetrySeconds ?? 120));
const backoff = waitSeconds * Math.max(1, attempts);
return new Date(Date.now() + backoff * 1000);
}
function formatDispatchError(error) {
const code = error?.code ? String(error.code) : null;
const statusCode = Number.isFinite(error?.statusCode) ? Number(error.statusCode) : null;
const message = String(error?.message ?? error ?? "integration_outbox_error").trim();
const parts = [];
if (code) {
parts.push(code);
}
if (statusCode != null) {
parts.push(`HTTP ${statusCode}`);
}
if (message) {
parts.push(message);
}
if (!parts.length) {
return "integration_outbox_error";
}
return parts.join(" | ");
}
async function enqueueIntegrationEvent(prisma, input) {
const dedupeKey = input.dedupeKey ?? null;
const existed =
dedupeKey != null
? await prisma.integrationOutbox.findUnique({
where: {
event_type_dedupe_key: {
event_type: input.eventType,
dedupe_key: dedupeKey,
},
},
select: { id: true, status: true },
})
: null;
if (existed) {
return {
id: existed.id,
status: existed.status,
duplicated: true,
};
}
const created = await prisma.integrationOutbox.create({
data: {
event_type: input.eventType,
status: OUTBOX_STATUSES.pending,
payload: input.payload,
dedupe_key: dedupeKey,
max_attempts: input.maxAttempts,
created_by: input.actorId ?? null,
updated_by: input.actorId ?? null,
},
select: {
id: true,
status: true,
},
});
return {
id: created.id,
status: created.status,
duplicated: false,
};
}
async function fetchPendingOutboxEvents(prisma, options) {
const batchSize = Math.max(1, Number(options.batchSize ?? 20));
const now = new Date();
return prisma.integrationOutbox.findMany({
where: {
status: {
in: [OUTBOX_STATUSES.pending, OUTBOX_STATUSES.failed],
},
OR: [{ next_retry_at: null }, { next_retry_at: { lte: now } }],
},
orderBy: [{ created_at: "asc" }],
take: batchSize,
});
}
async function markOutboxProcessing(prisma, id, actorId) {
return prisma.integrationOutbox.update({
where: { id },
data: {
status: OUTBOX_STATUSES.processing,
updated_by: actorId ?? null,
},
});
}
async function markOutboxSucceeded(prisma, id, actorId) {
return prisma.integrationOutbox.update({
where: { id },
data: {
status: OUTBOX_STATUSES.succeeded,
processed_at: new Date(),
last_error: null,
updated_by: actorId ?? null,
},
});
}
async function markOutboxFailed(prisma, config, item, error, actorId, options = {}) {
const attempts = Number(item.attempts ?? 0) + 1;
const maxAttempts = Math.max(
1,
Number(item.max_attempts ?? config.integrationOutboxMaxAttempts ?? 5),
);
const retryable =
typeof options.retryable === "boolean"
? options.retryable
: typeof error?.retryable === "boolean"
? error.retryable
: true;
const deadByAttempts = retryable && attempts >= maxAttempts;
const deadByPolicy = !retryable;
const dead = deadByPolicy || deadByAttempts;
return prisma.integrationOutbox.update({
where: { id: item.id },
data: {
attempts,
status: dead ? OUTBOX_STATUSES.dead_letter : OUTBOX_STATUSES.failed,
dead_letter_at: dead ? new Date() : null,
next_retry_at: dead ? null : nextRetryAt(config, attempts),
last_error: formatDispatchError(error).slice(0, 500),
updated_by: actorId ?? null,
},
});
}
module.exports = {
OUTBOX_STATUSES,
enqueueIntegrationEvent,
fetchPendingOutboxEvents,
markOutboxProcessing,
markOutboxSucceeded,
markOutboxFailed,
};