Merge branch 'feature/p19-erp-2-procurement-commitment-archive' into main

这个提交包含在:
2026-03-08 23:58:25 +08:00
当前提交 4a92045006
共修改 27 个文件,包含 3091 行新增和 223 行删除
+103
查看文件
@@ -111,6 +111,78 @@ export type PurchaseOrderArchive = {
archivedFiles: PurchaseArchivedFile[];
};
export type PurchaseErpTrackStatus =
| "not_triggered"
| "pending"
| "processing"
| "succeeded"
| "failed"
| "dead_letter"
| "skipped";
export type PurchaseErpBinding = {
id: string;
provider: string;
entityType: string;
localId: string;
externalId: string | null;
externalCode: string | null;
lastSyncedAt: string | null;
};
export type PurchaseErpOutbox = {
id: string;
eventType: string;
status: string;
attempts: number;
lastError: string | null;
processedAt: string | null;
updatedAt: string | null;
};
export type PurchaseErpTrackStage = {
eligible: boolean;
reason: string | null;
status: PurchaseErpTrackStatus | string;
preview: Record<string, unknown>;
outbox: PurchaseErpOutbox | null;
binding?: PurchaseErpBinding | null;
bindings?: {
po: PurchaseErpBinding | null;
contract: PurchaseErpBinding | null;
};
};
export type PurchaseRequestErpTrack = {
purchaseRequest: {
id: string;
requestNo: string | null;
status: string;
totalAmount: string;
supplier: {
id: string;
code: string | null;
name: string | null;
} | null;
archiveOrder: {
id: string;
poNo: string;
contractNo: string | null;
archivedAt: string | null;
} | null;
};
stages: {
commitmentJournal: PurchaseErpTrackStage;
accrualJournal: PurchaseErpTrackStage;
archiveSummary: PurchaseErpTrackStage;
};
permissions: {
canRetry: boolean;
};
};
export type PurchaseRequestErpRequeueTarget = "commitment_journal" | "accrual_journal" | "archive_summary";
export type PurchaseRequestDetail = PurchaseRequestSummary & {
items: PurchaseRequestItem[];
attachments: PurchaseAttachment[];
@@ -290,3 +362,34 @@ export async function issuePurchaseAttachmentSignedUrl(purchaseRequestId: string
},
);
}
export async function fetchPurchaseRequestErpTrack(purchaseRequestId: string) {
return apiRequestData<PurchaseRequestErpTrack>(
`/api/integrations/erp/procurement/purchase-requests/${purchaseRequestId}/track`,
);
}
export async function requeuePurchaseRequestErpSync(
purchaseRequestId: string,
payload: {
targets: PurchaseRequestErpRequeueTarget[];
},
runNow = true,
) {
return apiRequestData<{
items: Array<{
target: PurchaseRequestErpRequeueTarget;
outboxId: string;
status: string;
duplicated: boolean;
requeued: boolean;
eventType: string;
}>;
}>(
`/api/integrations/erp/procurement/purchase-requests/${purchaseRequestId}/requeue${toQueryString({ runNow })}`,
{
method: 'POST',
body: JSON.stringify(payload),
},
);
}
+6 -1
查看文件
@@ -5,7 +5,12 @@ import { cn } from "../../lib/utils";
const STATUS_MAP: Record<string, { label: string; className: string }> = {
draft: { label: "草稿", className: "badge-neutral bg-zinc-200/50" },
reviewing: { label: "审批中", className: "badge-warning" },
pending: { label: "处理中", className: "badge-warning" },
pending: { label: "待派发", className: "badge-warning" },
processing: { label: "处理中", className: "badge-warning" },
succeeded: { label: "已成功", className: "badge-success" },
failed: { label: "失败", className: "badge-error" },
dead_letter: { label: "死信", className: "badge-error" },
not_triggered: { label: "未触发", className: "badge-neutral" },
pending_ocr: { label: "识别中", className: "badge-warning" },
approved: { label: "已通过", className: "badge-success" },
completed: { label: "已完成", className: "badge-success" },
+239
查看文件
@@ -9,12 +9,17 @@ import {
deletePurchaseAttachment,
fetchPurchaseOrderArchive,
fetchPurchaseRequestDetail,
fetchPurchaseRequestErpTrack,
fetchPurchaseRequests,
issuePurchaseAttachmentSignedUrl,
requeuePurchaseRequestErpSync,
submitPurchaseRequest,
updatePurchaseRequest,
uploadPurchaseAttachment,
withdrawPurchaseRequest,
type PurchaseErpBinding,
type PurchaseRequestErpRequeueTarget,
type PurchaseRequestErpTrack,
type PurchaseRequestItemPayload,
type PurchaseRequestStatus,
} from "../api/purchaseRequests";
@@ -87,12 +92,113 @@ function statusOptions(): Array<{ value: PurchaseRequestStatus | ""; label: stri
];
}
type PurchaseErpStageKey = keyof PurchaseRequestErpTrack["stages"];
const PURCHASE_ERP_STAGE_META: Record<
PurchaseErpStageKey,
{ title: string; target: PurchaseRequestErpRequeueTarget }
> = {
commitmentJournal: { title: "Commitment", target: "commitment_journal" },
accrualJournal: { title: "Accrual", target: "accrual_journal" },
archiveSummary: { title: "PO/合同同步", target: "archive_summary" },
};
function formatStageReason(reason: string | null) {
switch (reason) {
case "purchase_request_not_approved":
return "当前采购单尚未处于已通过状态";
case "purchase_order_archive_missing":
return "尚未完成 PO/合同归档";
default:
return reason ?? null;
}
}
function resolveStageTimestamp(stage: PurchaseRequestErpTrack["stages"][PurchaseErpStageKey]) {
const binding = stage.binding as PurchaseErpBinding | null | undefined;
const poBinding = stage.bindings?.po ?? null;
const contractBinding = stage.bindings?.contract ?? null;
return (
stage.outbox?.updatedAt ??
stage.outbox?.processedAt ??
binding?.lastSyncedAt ??
poBinding?.lastSyncedAt ??
contractBinding?.lastSyncedAt ??
null
);
}
function resolveStageExternalCode(stage: PurchaseRequestErpTrack["stages"][PurchaseErpStageKey]) {
const binding = stage.binding as PurchaseErpBinding | null | undefined;
return binding?.externalCode ?? stage.bindings?.po?.externalCode ?? stage.bindings?.contract?.externalCode ?? null;
}
function resolveStageExternalId(stage: PurchaseRequestErpTrack["stages"][PurchaseErpStageKey]) {
const binding = stage.binding as PurchaseErpBinding | null | undefined;
return binding?.externalId ?? stage.bindings?.po?.externalId ?? stage.bindings?.contract?.externalId ?? null;
}
function resolveStageSummary(stageKey: PurchaseErpStageKey, stage: PurchaseRequestErpTrack["stages"][PurchaseErpStageKey]) {
const preview = stage.preview as {
documentNo?: string | null;
requestNo?: string | null;
poNo?: string | null;
contractNo?: string | null;
totalAmount?: string | null;
supplier?: {
code?: string | null;
};
dimensions?: {
legalEntityCode?: string | null;
costCenterCode?: string | null;
supplierCode?: string | null;
};
};
return {
documentNo:
preview.documentNo ??
preview.requestNo ??
(stageKey === "archiveSummary" ? preview.poNo ?? null : null),
totalAmount: preview.totalAmount ?? null,
legalEntityCode: preview.dimensions?.legalEntityCode ?? null,
costCenterCode: preview.dimensions?.costCenterCode ?? null,
supplierCode: preview.dimensions?.supplierCode ?? preview.supplier?.code ?? null,
poNo: preview.poNo ?? null,
contractNo: preview.contractNo ?? null,
};
}
function resolveStageAction(stageKey: PurchaseErpStageKey, stage: PurchaseRequestErpTrack["stages"][PurchaseErpStageKey]) {
if (!stage.eligible) {
return null;
}
if (stage.status === "failed" || stage.status === "dead_letter") {
return {
label: stageKey === "archiveSummary" ? "重试同步摘要" : "重试同步",
target: PURCHASE_ERP_STAGE_META[stageKey].target,
};
}
if (stage.status === "not_triggered" || stage.status === "skipped") {
return {
label: stageKey === "archiveSummary" ? "补发摘要" : "补发",
target: PURCHASE_ERP_STAGE_META[stageKey].target,
};
}
return null;
}
export function PurchaseRequestsPage() {
const queryClient = useQueryClient();
const { permissions } = useAuth();
const canCreate = hasPermission(permissions, "procurement.create");
const canManage = hasPermission(permissions, "procurement.manage");
const canIntegrationManage = hasPermission(permissions, "integration.manage");
const canViewAll =
hasPermission(permissions, "procurement.view_all") ||
canManage;
@@ -164,6 +270,14 @@ export function PurchaseRequestsPage() {
queryFn: () => fetchPurchaseOrderArchive(selectedId),
});
const erpTrackQuery = useQuery({
enabled:
Boolean(selectedId) &&
(detailQuery.data?.status === "approved" || Boolean(detailQuery.data?.archiveOrder)),
queryKey: ["purchase-requests", "erp-track", selectedId],
queryFn: () => fetchPurchaseRequestErpTrack(selectedId),
});
useEffect(() => {
if (selectedId) {
if (detailQuery.isLoading) {
@@ -337,6 +451,7 @@ export function PurchaseRequestsPage() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["purchase-requests"] }),
queryClient.invalidateQueries({ queryKey: ["workflow", "tasks"] }),
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "erp-track", selectedId] }),
]);
setFormError("");
toast.success(
@@ -364,6 +479,7 @@ export function PurchaseRequestsPage() {
queryClient.invalidateQueries({ queryKey: ["purchase-requests"] }),
queryClient.invalidateQueries({ queryKey: ["workflow", "tasks"] }),
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "archive-order", selectedId] }),
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "erp-track", selectedId] }),
]);
setFormError("");
toast.success("采购申请已撤回到草稿");
@@ -394,6 +510,7 @@ export function PurchaseRequestsPage() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "detail", selectedId] }),
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "archive-order", selectedId] }),
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "erp-track", selectedId] }),
]);
toast.success("PO/合同归档已保存");
},
@@ -403,6 +520,39 @@ export function PurchaseRequestsPage() {
},
});
const requeueErpMutation = useMutation({
mutationFn: async (payload: { target: PurchaseRequestErpRequeueTarget; label: string }) => {
if (!selectedId) {
throw new Error("请先选择采购单");
}
return {
label: payload.label,
response: await requeuePurchaseRequestErpSync(selectedId, { targets: [payload.target] }),
};
},
onSuccess: async ({ label, response }) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "detail", selectedId] }),
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "archive-order", selectedId] }),
queryClient.invalidateQueries({ queryKey: ["purchase-requests", "erp-track", selectedId] }),
]);
const firstItem = response.items[0];
if (firstItem?.duplicated) {
toast.success(`${label} 已存在待处理记录`);
return;
}
if (firstItem?.requeued) {
toast.success(`${label} 已重新入队`);
return;
}
toast.success(`${label} 已加入同步队列`);
},
onError: (error) => {
const message = resolveError(error);
toast.error(message);
},
});
const uploadMutation = useMutation({
mutationFn: async (file: File) => {
if (!selectedId) {
@@ -455,6 +605,8 @@ export function PurchaseRequestsPage() {
const detail = detailQuery.data;
const archiveOrder = archiveOrderQuery.data?.archiveOrder ?? detail?.archiveOrder ?? null;
const erpTrack = erpTrackQuery.data ?? null;
const canRetryErp = Boolean(canIntegrationManage && erpTrack?.permissions.canRetry);
const showArchiveSection = Boolean(detail && (detail.status === "approved" || archiveOrder));
const canEditDraft = Boolean(detail?.permissions.canEditDraft);
const canSubmit = Boolean(detail?.permissions.canSubmit);
@@ -1027,6 +1179,93 @@ export function PurchaseRequestsPage() {
) : null}
</div>
) : null}
{showArchiveSection ? (
<div className="space-y-3 rounded-lg border border-zinc-200 p-4">
<div className="flex items-center justify-between">
<div>
<h4 className="text-base font-semibold text-zinc-900">采购 ERP 同步轨道</h4>
<p className="text-sm text-zinc-500">展示 Commitment / Accrual / PO/合同摘要三段 ERP 同步状态,失败后可在此重试。</p>
</div>
</div>
{erpTrackQuery.isLoading ? (
<p className="rounded-lg bg-zinc-50 px-3 py-2 text-sm text-zinc-500">ERP 轨道加载中...</p>
) : erpTrackQuery.isError ? (
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">{resolveError(erpTrackQuery.error)}</p>
) : erpTrack ? (
<div className="grid gap-3 xl:grid-cols-3">
{(Object.entries(PURCHASE_ERP_STAGE_META) as Array<
[PurchaseErpStageKey, (typeof PURCHASE_ERP_STAGE_META)[PurchaseErpStageKey]]
>).map(([stageKey, meta]) => {
const stage = erpTrack.stages[stageKey];
const summary = resolveStageSummary(stageKey, stage);
const action = canRetryErp ? resolveStageAction(stageKey, stage) : null;
const stageTime = resolveStageTimestamp(stage);
const externalCode = resolveStageExternalCode(stage);
const externalId = resolveStageExternalId(stage);
const reasonText = formatStageReason(stage.reason);
const isSubmittingAction = requeueErpMutation.isPending && requeueErpMutation.variables?.target === action?.target;
return (
<div key={stageKey} className="space-y-3 rounded-lg border border-zinc-200 p-3">
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-sm font-semibold text-zinc-900">{meta.title}</div>
<div className="text-xs text-zinc-500">
{stageTime ? `最近更新时间:${new Date(stageTime).toLocaleString()}` : "尚无同步记录"}
</div>
</div>
<StatusBadge status={stage.status} />
</div>
<div className="space-y-1 text-xs text-zinc-600">
<div>单号:{summary.documentNo ?? "-"}</div>
<div>金额:{summary.totalAmount ?? "-"}</div>
<div>法体 / 成本中心:{summary.legalEntityCode ?? "-"} / {summary.costCenterCode ?? "-"}</div>
<div>供应商:{summary.supplierCode ?? "-"}</div>
{stageKey !== "commitmentJournal" ? (
<div>PO / 合同:{summary.poNo ?? "-"} / {summary.contractNo ?? "-"}</div>
) : null}
</div>
{reasonText ? (
<div className="rounded bg-zinc-50 px-2 py-1 text-xs text-zinc-500">{reasonText}</div>
) : null}
{stage.outbox?.lastError ? (
<div className="rounded bg-red-50 px-2 py-1 text-xs text-red-600">{stage.outbox.lastError}</div>
) : null}
{canIntegrationManage && (externalCode || externalId) ? (
<div className="rounded bg-zinc-50 px-2 py-1 text-xs text-zinc-600">
ERP 编号:{externalCode ?? "-"}
{externalId ? ` · ${externalId}` : ""}
</div>
) : null}
{action ? (
<div className="flex justify-end">
<Button
type="button"
size="sm"
variant="secondary"
disabled={requeueErpMutation.isPending}
onClick={() => requeueErpMutation.mutate({ target: action.target, label: meta.title })}
>
{isSubmittingAction ? "处理中..." : action.label}
</Button>
</div>
) : null}
</div>
);
})}
</div>
) : (
<p className="rounded-lg bg-zinc-50 px-3 py-2 text-sm text-zinc-500">暂无 ERP 轨道信息</p>
)}
</div>
) : null}
</>
) : null}
</div>
+15 -10
查看文件
@@ -1,7 +1,7 @@
# 领域事件清单(P19 / P19+IM-1 / P19+ERP-1)
# 领域事件清单(P19 / P19+IM-1 / P19+ERP-2)
**快照日期**:2026-03-08
**目标**:冻结 `hyb-oa` 当前采购与资产域的标准领域事件名,并补充 `P19+IM-1` 已实际消费的 IM 通知类型清单,以及 `P19+ERP-1` 已实际落地的 ERP 消费映射,作为后续 ERP / IM / AI 适配的事实源。
**目标**:冻结 `hyb-oa` 当前采购与资产域的标准领域事件名,并补充 `P19+IM-1` 已实际消费的 IM 通知类型清单,以及 `P19+ERP-1 / ERP-2` 已实际落地的 ERP 消费映射,作为后续 ERP / IM / AI 适配的事实源。
## 1. 使用原则
- 本文档同时维护两类事实:
@@ -18,6 +18,7 @@
| `purchase_request.approved` | 采购申请审批通过后 | `purchase_request` | `purchaseRequestId`, `requestNo`, `approvedBy`, `legalEntityId`, `costCenterId`, `supplierId`, `budgetPoolId`, `totalAmount`, `status` | ERP、IM、AI | 对应预算 `confirm` 已完成 |
| `purchase_request.rejected` | 采购申请审批驳回后 | `purchase_request` | `purchaseRequestId`, `requestNo`, `actorId`, `reason`, `status` | IM、AI | 若存在预算预留,应已释放 |
| `purchase_request.withdrawn` | 申请人撤回采购申请后 | `purchase_request` | `purchaseRequestId`, `requestNo`, `actorId`, `status` | IM、AI、ERP 补偿 | 表示由 `reviewing` 回到 `draft` |
| `purchase_order.archived` | PO/合同归档保存成功后 | `purchase_order_archive` | `purchaseOrderArchiveId`, `purchaseRequestId`, `requestNo`, `poNo`, `contractNo`, `archivedAt`, `totalAmount` | ERP、AI | ERP-2 以此驱动 accrual journal 与 archive summary |
| `asset.card.created` | 资产卡片创建成功后 | `asset_card` | `assetId`, `assetNo`, `name`, `categoryId`, `legalEntityId`, `costCenterId`, `purchaseRequestId`, `status` | ERP、IM、AI | 资产域不接 workflow |
| `asset.assigned` | 资产领用成功后 | `asset_card` | `assetId`, `assetNo`, `employeeId`, `assignedAt`, `location`, `status` | IM、AI | 对应新增 open assignment |
| `asset.returned` | 资产归还成功后 | `asset_card` | `assetId`, `assetNo`, `employeeId`, `returnedAt`, `location`, `status` | IM、AI | 对应关闭 open assignment |
@@ -29,6 +30,7 @@
| entityType | 推荐事件前缀 | 当前事实源 |
| --- | --- | --- |
| `purchase_request` | `purchase_request.*` | `P17A` / `P17B` |
| `purchase_order_archive` | `purchase_order.*` | `P17B` / `P19+ERP-2` |
| `asset_card` | `asset.*` | `P18A` / `P18B` |
| `inventory_check` | `inventory_check.*` | `P18B` |
@@ -55,13 +57,13 @@
- 载荷字段命名应与 HTTP camelCase 输出保持一致,不直接暴露数据库 snake_case 列名。
## 6. 明确不纳入当前事件主表的事项
- `purchase_request.archived`:待未来采购归档通知专项再冻结
- `purchase_order.cancelled`:待未来采购撤销 / 作废专项再冻结
- `inventory_check.started`:当前不是对外关键事实源
- `asset.repaired` / `asset.retired`:待未来维修 / 报废专项后再定义
## 7. 推荐消费场景
- IM:采购审批结果、报销结果、资产领用归还、盘点完成提醒
- ERP:采购审批通过摘要、资产卡片新增摘要、盘点完成摘要
- ERP:采购审批 commitment、PO/合同归档 accrual / summary、资产卡片新增摘要、盘点完成摘要
- AI:审批摘要、异常提示、主数据重复建议、盘点结果总结
## 8. P19+IM-1 已消费通知类型
@@ -91,9 +93,12 @@
这些事件名称仍保留在长期蓝图中,但不属于 `P19+IM-1` 的首批协同覆盖范围。
## 10. P19+ERP-1 已实现消费映射
- `P19+ERP-1` 没有新增新的领域事件名;当前 ERP 一期真正落地消费的既有业务事实是 `reimbursement.paid`。
- 运行时不会把 ERP 专有结构写回核心报销表,而是先构建标准化 `ReimbursementJournalSlice`,再通过 `erp.journal.export` 写入 `IntegrationOutbox` 异步派发。
- `ReimbursementJournalSlice.sourceEventName` 固定为 `reimbursement.paid`,用于标记该凭证切片来源于“报销付款完成”这一既有业务事实。
- ERP 主数据同步(`LegalEntity` / `CostCenter` / `Supplier`)属于主动 Pull,不作为新的领域事件名纳入本表。
- `purchase_request.approved`、`asset.card.created`、`inventory_check.completed` 等事件仍只冻结名称与最小载荷;真实 ERP 导出留待后续 `P19+ERP-2 / ERP-3`。
## 10. P19+ERP-1 / ERP-2 已实现消费映射
- `P19+ERP-1` 没有新增新的领域事件名;ERP 一期真正落地消费的既有业务事实是 `reimbursement.paid`,运行时会先构建标准化 `ReimbursementJournalSlice`,再通过 `erp.journal.export` 写入 `IntegrationOutbox` 异步派发。
- `ReimbursementJournalSlice.sourceEventName` 固定为 `reimbursement.paid`,用于标记该凭证切片来源于“报销付款完成”这一既有业务事实;历史 `erp.reimbursement.paid` outbox 仍继续兼容。
- `P19+ERP-2` 正式冻结新增领域事件名 `purchase_order.archived`,并消费两类采购事实:
- `purchase_request.approved` → `PurchaseCommitmentJournalSlice` → `erp.journal.export`
- `purchase_order.archived` → `PurchaseAccrualJournalSlice` + `purchase_order_archive` summary → `erp.journal.export` / `erp.procurement.export`
- 采购 ERP 成功派发后,运行时统一把外部 ERP 编号回写到 `integration_bindings`,分别对应 `purchase_request_commitment_journal`、`purchase_order_accrual_journal`、`purchase_order_po`、`purchase_order_contract`。
- ERP 主数据同步(`LegalEntity` / `CostCenter` / `Supplier`)仍属于主动 Pull,不作为新的领域事件名纳入本表;`IntegrationSyncState` 也继续只承载主数据资源级同步状态,而不承载采购单据轨道。
- `asset.card.created`、`inventory_check.completed` 等事件继续只冻结名称与最小载荷;真实 ERP 导出留待后续 `P19+ERP-3`。
+11 -2
查看文件
@@ -1,8 +1,8 @@
# hyb-oa 实现状态矩阵(P5-P19+IM-1+ERP-1)
# hyb-oa 实现状态矩阵(P5-P19+IM-1+ERP-2)
**快照日期**:2026-03-08
**范围**:`F1-F42`(含 `F19b/F19c/F19d`)+ `R1-S2` + `P9A1-P9D1` + `P10E1-P10G1` + `G0-G6` + `H1` + `M1-M4` + `P13-0-P13-8` + `P14-0-P14-8` + `P15A-0-P15A-5` + `P15B-0-P15B-6` + `P16A-0-P16A-6` + `P16B-0-P16B-6` + `P16C-0-P16C-6` + `R9-0-R9-3` + `G2-0-G2-6` + `P17A-0-P17A-6` + `P17B-0-P17B-6` + `P18A-0-P18A-6` + `P18B-0-P18B-6` + `P19-0-P19-6` + `P19IM1-0-P19IM1-6` + `P19ERP1-0-P19ERP1-6`,共 206 项。
**事实源**:`issues/2026-02-09_13-39-02-p5-blueprint-v3.csv` + `issues/2026-02-09_23-30-00-p6-p8-remaining-work-master.csv` + `issues/2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv` + `issues/2026-02-10_10-35-30-p10-production-hardening.csv` + `issues/2026-02-11-p11-p12-governance-mobile.csv` + `issues/2026-02-12_01-09-41-p13-l5-governance.csv` + `issues/2026-02-13_00-11-56-p14-l5-operationalization.csv` + `issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv` + `issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv` + `issues/2026-03-07_13-47-05-p16a-l5-master-data-core.csv` + `issues/2026-03-07_16-22-07-p16b-l5-holiday-calendar.csv` + `issues/2026-03-07_17-14-39-p16c-l5-suppliers.csv` + `issues/2026-03-07_18-15-03-r9-g2-p19-roadmap-refresh.csv` + `issues/2026-03-07_18-16-00-g2-l5-cross-domain-bridge.csv` + `issues/2026-03-07_19-33-09-p17a-l5-procurement-core.csv` + `issues/2026-03-07_21-00-37-p17b-l5-procurement-budget-archive.csv` + `issues/2026-03-07_22-02-09-p18a-l5-asset-registry-core.csv` + `issues/2026-03-07_22-34-03-p18b-l5-asset-movements-inventory.csv` + `issues/2026-03-07_23-22-00-p19-l4-integration-readiness.csv` + `issues/2026-03-08_12-18-10-p19-im-1-l5-collaboration-adapter.csv` + `issues/2026-03-08_14-10-53-p19-erp-1-l5-masterdata-journal-bridge.csv`(执行合同)
**事实源**:`issues/2026-02-09_13-39-02-p5-blueprint-v3.csv` + `issues/2026-02-09_23-30-00-p6-p8-remaining-work-master.csv` + `issues/2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv` + `issues/2026-02-10_10-35-30-p10-production-hardening.csv` + `issues/2026-02-11-p11-p12-governance-mobile.csv` + `issues/2026-02-12_01-09-41-p13-l5-governance.csv` + `issues/2026-02-13_00-11-56-p14-l5-operationalization.csv` + `issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv` + `issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv` + `issues/2026-03-07_13-47-05-p16a-l5-master-data-core.csv` + `issues/2026-03-07_16-22-07-p16b-l5-holiday-calendar.csv` + `issues/2026-03-07_17-14-39-p16c-l5-suppliers.csv` + `issues/2026-03-07_18-15-03-r9-g2-p19-roadmap-refresh.csv` + `issues/2026-03-07_18-16-00-g2-l5-cross-domain-bridge.csv` + `issues/2026-03-07_19-33-09-p17a-l5-procurement-core.csv` + `issues/2026-03-07_21-00-37-p17b-l5-procurement-budget-archive.csv` + `issues/2026-03-07_22-02-09-p18a-l5-asset-registry-core.csv` + `issues/2026-03-07_22-34-03-p18b-l5-asset-movements-inventory.csv` + `issues/2026-03-07_23-22-00-p19-l4-integration-readiness.csv` + `issues/2026-03-08_12-18-10-p19-im-1-l5-collaboration-adapter.csv` + `issues/2026-03-08_14-10-53-p19-erp-1-l5-masterdata-journal-bridge.csv` + `issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv`(执行合同)
**说明**:
- 本矩阵用于全局读图(审计/交接/回归覆盖追踪),不替代 `issues/*.csv` 的执行合同职责。
@@ -238,3 +238,12 @@
| P19ERP1-5 | OpenAPI文档与矩阵同步 | N/A | 2026-03-08_14-10-53-p19-erp-1-l5-masterdata-journal-bridge.csv | 2026-03-08_14-10-53-p19-erp-1-l5-masterdata-journal-bridge.csv | 2026-03-08 | DONE | validate-feature-matrix | 集成边界、领域事件、Feature Matrix 与校验器同步到 `P5-P19+IM-1+ERP-1`,并纳入 ERP-1 合同事实源 |
| P19ERP1-6 | P19ERP1回归与安全收口 | N/A | 2026-03-08_14-10-53-p19-erp-1-l5-masterdata-journal-bridge.csv | 2026-03-08_14-10-53-p19-erp-1-l5-masterdata-journal-bridge.csv | 2026-03-08 | DONE | server:test + regression-integrations + regression-all + client:typecheck/build | 主数据 Pull、报销凭证切片、ERP 管理入口、开关阻断与 dead_letter 重入全部通过,且既有主流程零回归 |
| P19ERP2-0 | P19ERP2执行合同建档 | N/A | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08 | DONE | CSV 校验 | 采购 ERP 双阶段出站执行合同建档,冻结 commitment / accrual / archive summary 三段模型 |
| P19ERP2-1 | 采购ERP出站契约与provider扩展 | N/A | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08 | DONE | server:test | 扩展 `erp.journal.export` / `erp.procurement.export` 契约、payload、dedupe 与采购 binding 回写规则 |
| P19ERP2-2 | 采购审批与归档自动出站 | N/A | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08 | DONE | server:test + regression-integrations | 采购审批自动入队 commitment,首次归档自动入队 accrual + summary,且 gate 关闭时仅 skip 不阻断业务 |
| P19ERP2-3 | 采购ERP轨道查询与重试接口 | N/A | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08 | DONE | server:test + regression-integrations | 新增采购 ERP track / requeue 接口,支持历史补发、失败重试与 archive summary 覆盖同步 |
| P19ERP2-4 | 采购详情ERP轨道挂件 | N/A | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08 | DONE | client:typecheck/build | `PurchaseRequestsPage` 归档区新增 ERP 三段轨道挂件,按权限区分查看与重试能力 |
| P19ERP2-5 | 文档事件与矩阵同步 | N/A | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08 | DONE | validate-feature-matrix | 集成边界、领域事件、Feature Matrix 与校验器同步到 `P5-P19+IM-1+ERP-2`,并纳入 ERP-2 合同事实源 |
| P19ERP2-6 | P19ERP2回归与验收收口 | N/A | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | 2026-03-08 | DONE | server:test + regression-integrations + regression-all + client:typecheck/build | 采购双阶段 journal、archive summary 覆盖同步、详情挂件、权限边界与既有 ERP / IM 主流程回归全部通过 |
+12 -4
查看文件
@@ -1,8 +1,8 @@
# 集成边界冻结(P19 / P19+IM-1 / P19+ERP-1)
# 集成边界冻结(P19 / P19+IM-1 / P19+ERP-2)
**快照日期**:2026-03-08
**当前基线**:`P19+IM-1` 与 `P19+ERP-1` 已完成;当前运行时已落地企微群机器人 + 深链 + Outbox 异步派发的一期协同适配,以及 ERP 主数据 Pull / 报销付款凭证切片的一期桥接。
**目标**:在保持核心域稳定的前提下,冻结 ERP / IM / AI / MCP 的长期边界,并记录 IM 一期与 ERP 一期的已实现范围、禁入规则和后续扩展位。
**当前基线**:`P19+IM-1`、`P19+ERP-1` 与 `P19+ERP-2` 已完成;当前运行时已落地企微群机器人 + 深链 + Outbox 异步派发的一期协同适配,以及 ERP 主数据 Pull、报销付款凭证切片、采购双阶段 journal 与归档摘要出站。
**目标**:在保持核心域稳定的前提下,冻结 ERP / IM / AI / MCP 的长期边界,并记录 IM 一期与 ERP 两期的已实现范围、禁入规则和后续扩展位。
## 1. 总体原则
@@ -48,7 +48,7 @@
### 2.4 建议后续专项
- `P19+ERP-1`:主数据同步协议
- `P19+ERP-2`:采购审批结果导出 / 回写协议
- `P19+ERP-2`:采购双阶段 journal 与归档摘要出站
- `P19+ERP-3`:资产台账摘要导出协议
### 2.5 P19+ERP-1 已实现范围
@@ -58,6 +58,14 @@
- 已兼容保留历史 `erp.reimbursement.paid` 派发路径;成功导出后统一回写 `integration_bindings(provider=erp, entity_type=reimbursement_journal)`。
- 已明确 `ERP_SYNC_ENABLED` 与 `erp_sync` feature flag 共同构成 ERP 管理端总闸,任一关闭都必须阻断主数据同步与手动导出。
### 2.6 P19+ERP-2 已实现范围
- 已冻结采购双阶段财务语义:`purchase_request.approved` 自动生成 `purchase_request_commitment` journal,`purchase_order.archived` 首次归档自动生成 `purchase_order_accrual` journal。
- 已新增 `erp.procurement.export` 用于 `purchase_order_archive` 摘要出站;commitment / accrual 仍统一复用 `erp.journal.export`,避免额外拆分出站总线。
- 已为 `purchase_order_archive` 建立“同一条 outbox 覆盖同步”语义:当 `poNo` / `contractNo` / `archivedFiles` 变化时,仅重置 summary 对应 outbox 并覆盖 payload,不重复创建 accrual journal。
- 已在 `integration_bindings` 中落地采购映射:`purchase_request_commitment_journal`、`purchase_order_accrual_journal`、`purchase_order_po`、`purchase_order_contract`;成功派发后回写 ERP 外部编号与最近同步时间。
- 已明确 `IntegrationSyncState` 继续只表示资源级主数据同步状态,不承载采购单据级轨道;采购详情轨道只允许由 `IntegrationOutbox + IntegrationBinding + 当前单据事实` 推导。
- 已将采购 ERP 轨道挂件固定在采购详情 / 归档区:所有可读用户仅查看阶段状态,`integration.manage` 才能查看 ERP 外部编号并执行手动补发 / 重试。
## 3. IM / 协同适配边界
### 3.1 一期已实现能力(P19+IM-1)
@@ -0,0 +1,8 @@
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
P19ERP2-0,P19ERP2执行合同建档,创建并校验采购ERP双阶段出站执行合同CSV,CSV通过校验且字段完整,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv,manual,DONE,DONE,DONE,issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv,[],P19ERP2固定为采购审批commitment + 归档accrual + 归档摘要出站
P19ERP2-1,采购ERP出站契约与provider扩展,扩展journal与procurement export provider契约并定义payload/dedupe/binding规则,ERP journal与procurement summary均可通过现有dispatcher/outbox处理且不新增核心表ERP字段,cd server && npm run test,manual,DONE,DONE,DONE,server/src/services/integrations/erp.js | server/src/services/integrations/dispatcher.js | server/src/services/integrations/erpProcurement.js | server/tests,"[""P19ERP2-0""]",默认不新增Prisma表 继续复用IntegrationBinding与IntegrationOutbox
P19ERP2-2,采购审批与归档自动出站,在purchase approval与archive-order落点自动入队commitment/accrual/archive summary并处理gate skip,审批与归档成功后业务事务不受ERP失败影响 且outbox/binding语义正确,cd server && npm run test && ./scripts/regression-integrations.sh,manual,DONE,DONE,DONE,server/src/routes/workflow.js | server/src/routes/purchaseRequests.js | server/src/services/integrations/outbox.js | server/tests,"[""P19ERP2-1""]",自动触发走strictDepartment=true 手动重试走strictDepartment=false
P19ERP2-3,采购ERP轨道查询与重试接口,新增采购详情ERP轨道查询与requeue接口支持历史补发和失败重试,采购可读用户可看轨道 integration.manage可重试且开关关闭时正确阻断,cd server && npm run test && ./scripts/regression-integrations.sh,manual,DONE,DONE,DONE,server/src/routes/integrations.js | server/tests,"[""P19ERP2-2""]",archive summary允许同一条outbox在payload变化时重置覆盖
P19ERP2-4,采购详情ERP轨道挂件,在PurchaseRequestsPage归档区下增加ERP轨道挂件与重试交互,详情页可展示三段轨道状态且权限边界正确,cd client && npm run typecheck && npm run build,manual,DONE,DONE,DONE,client/src/pages/PurchaseRequestsPage.tsx | client/src/api/purchaseRequests.ts,"[""P19ERP2-3""]",仅详情挂件 不新增ERP页采购面板
P19ERP2-5,文档事件与矩阵同步,同步采购ERP-2边界 事件映射 Feature Matrix与校验器,矩阵标题更新为P5-P19+IM-1+ERP-2且总数为213,python3 scripts/validate-feature-matrix.py,manual,DONE,DONE,DONE,docs/integration-boundaries.md | docs/domain-events.md | docs/feature-matrix.md | scripts/validate-feature-matrix.py | issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv,"[""P19ERP2-4""]",新增purchase_order.archived事件并补采购ERP消费映射
P19ERP2-6,P19ERP2回归与验收收口,完成采购双阶段出站 详情挂件与回归验证后收口,采购ERP happy path与失败重试通过且报销/请假/采购/资产/IM零回归,cd server && npm run test && ./scripts/regression-integrations.sh && OCR_PROVIDER=mock JOBS_ENABLED=false IM_NOTIFIER_ENABLED=true APP_ORIGIN='http://127.0.0.1:3000' ./scripts/regression-all.sh && cd ../client && npm run typecheck && npm run build,manual,DONE,DONE,DONE,issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | server/scripts/regression-integrations.sh | client/src/pages/PurchaseRequestsPage.tsx,"[""P19ERP2-5""]",重点核对archive summary覆盖同步 成功journal不可强制replay 权限边界与gate阻断
1 ID Title Description Acceptance Test_Method Tools Dev_Status Review1_Status Regression_Status Files Dependencies Notes
2 P19ERP2-0 P19ERP2执行合同建档 创建并校验采购ERP双阶段出站执行合同CSV CSV通过校验且字段完整 python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv manual DONE DONE DONE issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv [] P19ERP2固定为采购审批commitment + 归档accrual + 归档摘要出站
3 P19ERP2-1 采购ERP出站契约与provider扩展 扩展journal与procurement export provider契约并定义payload/dedupe/binding规则 ERP journal与procurement summary均可通过现有dispatcher/outbox处理且不新增核心表ERP字段 cd server && npm run test manual DONE DONE DONE server/src/services/integrations/erp.js | server/src/services/integrations/dispatcher.js | server/src/services/integrations/erpProcurement.js | server/tests ["P19ERP2-0"] 默认不新增Prisma表 继续复用IntegrationBinding与IntegrationOutbox
4 P19ERP2-2 采购审批与归档自动出站 在purchase approval与archive-order落点自动入队commitment/accrual/archive summary并处理gate skip 审批与归档成功后业务事务不受ERP失败影响 且outbox/binding语义正确 cd server && npm run test && ./scripts/regression-integrations.sh manual DONE DONE DONE server/src/routes/workflow.js | server/src/routes/purchaseRequests.js | server/src/services/integrations/outbox.js | server/tests ["P19ERP2-1"] 自动触发走strictDepartment=true 手动重试走strictDepartment=false
5 P19ERP2-3 采购ERP轨道查询与重试接口 新增采购详情ERP轨道查询与requeue接口支持历史补发和失败重试 采购可读用户可看轨道 integration.manage可重试且开关关闭时正确阻断 cd server && npm run test && ./scripts/regression-integrations.sh manual DONE DONE DONE server/src/routes/integrations.js | server/tests ["P19ERP2-2"] archive summary允许同一条outbox在payload变化时重置覆盖
6 P19ERP2-4 采购详情ERP轨道挂件 在PurchaseRequestsPage归档区下增加ERP轨道挂件与重试交互 详情页可展示三段轨道状态且权限边界正确 cd client && npm run typecheck && npm run build manual DONE DONE DONE client/src/pages/PurchaseRequestsPage.tsx | client/src/api/purchaseRequests.ts ["P19ERP2-3"] 仅详情挂件 不新增ERP页采购面板
7 P19ERP2-5 文档事件与矩阵同步 同步采购ERP-2边界 事件映射 Feature Matrix与校验器 矩阵标题更新为P5-P19+IM-1+ERP-2且总数为213 python3 scripts/validate-feature-matrix.py manual DONE DONE DONE docs/integration-boundaries.md | docs/domain-events.md | docs/feature-matrix.md | scripts/validate-feature-matrix.py | issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv ["P19ERP2-4"] 新增purchase_order.archived事件并补采购ERP消费映射
8 P19ERP2-6 P19ERP2回归与验收收口 完成采购双阶段出站 详情挂件与回归验证后收口 采购ERP happy path与失败重试通过且报销/请假/采购/资产/IM零回归 cd server && npm run test && ./scripts/regression-integrations.sh && OCR_PROVIDER=mock JOBS_ENABLED=false IM_NOTIFIER_ENABLED=true APP_ORIGIN='http://127.0.0.1:3000' ./scripts/regression-all.sh && cd ../client && npm run typecheck && npm run build manual DONE DONE DONE issues/2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv | server/scripts/regression-integrations.sh | client/src/pages/PurchaseRequestsPage.tsx ["P19ERP2-5"] 重点核对archive summary覆盖同步 成功journal不可强制replay 权限边界与gate阻断
+1
查看文件
@@ -40,6 +40,7 @@ CSV_FACT_SOURCES = [
ROOT / "issues" / "2026-03-07_23-22-00-p19-l4-integration-readiness.csv",
ROOT / "issues" / "2026-03-08_12-18-10-p19-im-1-l5-collaboration-adapter.csv",
ROOT / "issues" / "2026-03-08_14-10-53-p19-erp-1-l5-masterdata-journal-bridge.csv",
ROOT / "issues" / "2026-03-08_22-46-51-p19-erp-2-l5-procurement-commitment-archive.csv",
]
ID_PATTERN = re.compile(r"^[A-Z][0-9][0-9A-Za-z-]*$")
@@ -0,0 +1,2 @@
ALTER TABLE "integration_bindings"
ALTER COLUMN "entity_type" TYPE VARCHAR(64);
+1 -1
查看文件
@@ -1208,7 +1208,7 @@ model IntegrationOutbox {
model IntegrationBinding {
id String @id @default(uuid()) @db.Uuid
provider String @db.VarChar(32)
entity_type String @db.VarChar(32)
entity_type String @db.VarChar(64)
local_id String @db.Uuid
external_id String? @db.VarChar(128)
external_code String? @db.VarChar(128)
+424 -24
查看文件
@@ -6,6 +6,10 @@ MOCK_ERP_PORT="${MOCK_ERP_PORT:-$((3900 + RANDOM % 500))}"
APP_PORT="${APP_PORT:-$((4300 + RANDOM % 500))}"
BASE_URL="http://127.0.0.1:${APP_PORT}"
DEVICE_FINGERPRINT="${DEVICE_FINGERPRINT:-regression-integrations}"
EMPLOYEE_IDENTIFIER="${EMPLOYEE_IDENTIFIER:-employee@hyinda.com}"
EMPLOYEE_PASSWORD="${EMPLOYEE_PASSWORD:-EmployeePassword1234}"
MANAGER_IDENTIFIER="${MANAGER_IDENTIFIER:-manager@hyinda.com}"
MANAGER_PASSWORD="${MANAGER_PASSWORD:-ManagerPassword1234}"
FINANCE_MGR_IDENTIFIER="${FINANCE_MGR_IDENTIFIER:-finance_mgr@hyinda.com}"
FINANCE_MGR_PASSWORD="${FINANCE_MGR_PASSWORD:-FinanceMgrPassword1234}"
RUN_SUFFIX="$(date +%s)-$RANDOM"
@@ -155,7 +159,11 @@ const server = http.createServer(async (req, res) => {
if (
req.method === 'POST' &&
(url.pathname === '/erp/journals/reimbursements/paid' || url.pathname === '/erp/reimbursements/paid')
(
url.pathname === '/erp/journals/export' ||
url.pathname === '/erp/journals/reimbursements/paid' ||
url.pathname === '/erp/reimbursements/paid'
)
) {
const mode = url.searchParams.get('mode') || 'success';
const chunks = [];
@@ -176,6 +184,7 @@ const server = http.createServer(async (req, res) => {
ok: true,
scenario: 'timeout',
externalId: `ERP-TIMEOUT-${Date.now()}`,
externalCode: `ERP-TIMEOUT-${Date.now()}`,
reimbursementId: parsedBody?.reimbursementId || parsedBody?.entityId || null,
});
}, 1500);
@@ -200,14 +209,68 @@ const server = http.createServer(async (req, res) => {
});
}
const documentNo = parsedBody?.documentNo || parsedBody?.formNumber || parsedBody?.entityId || Date.now();
return sendJson(res, 200, {
ok: true,
scenario: 'success',
externalId: `ERP-${parsedBody?.documentNo || parsedBody?.formNumber || parsedBody?.entityId || Date.now()}`,
externalId: `ERP-${documentNo}`,
externalCode: `ERP-${documentNo}`,
reimbursementId: parsedBody?.reimbursementId || parsedBody?.entityId || null,
});
}
if (req.method === 'POST' && url.pathname === '/erp/procurement/export') {
const mode = url.searchParams.get('mode') || 'success';
const chunks = [];
for await (const chunk of req) {
chunks.push(chunk);
}
let parsedBody = null;
try {
parsedBody = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
} catch {
parsedBody = null;
}
if (mode === 'timeout') {
setTimeout(() => {
sendJson(res, 200, {
ok: true,
externalPoId: `ERP-PO-${Date.now()}`,
externalPoNo: `ERP-PO-${parsedBody?.poNo || Date.now()}`,
});
}, 1500);
return;
}
if (mode === 'client') {
return sendJson(res, 422, {
ok: false,
code: 'invalid_payload',
message: 'mock procurement client error',
});
}
if (mode === 'server') {
return sendJson(res, 503, {
ok: false,
code: 'service_unavailable',
message: 'mock procurement server error',
});
}
return sendJson(res, 200, {
ok: true,
externalId: `ERP-PROC-${parsedBody?.poNo || parsedBody?.entityId || Date.now()}`,
externalCode: `ERP-PROC-${parsedBody?.poNo || parsedBody?.entityId || Date.now()}`,
externalPoId: parsedBody?.poNo ? `ERP-PO-${parsedBody.poNo}` : null,
externalPoNo: parsedBody?.poNo ? `ERP-PO-${parsedBody.poNo}` : null,
externalContractId: parsedBody?.contractNo ? `ERP-CT-${parsedBody.contractNo}` : null,
externalContractNo: parsedBody?.contractNo ? `ERP-CT-${parsedBody.contractNo}` : null,
});
}
sendJson(res, 404, { ok: false, message: 'not_found' });
});
@@ -239,9 +302,11 @@ start_app_server() {
ERP_SYNC_ENABLED=true \
ERP_SYNC_PROVIDER=http \
ERP_MASTER_DATA_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/master-data/pull?mode=success" \
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/reimbursements/paid?mode=success" \
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/export?mode=success" \
ERP_PROCUREMENT_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/procurement/export?mode=success" \
ERP_SYNC_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=success" \
ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_PROCUREMENT_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_MASTER_DATA_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_SYNC_AUTH_TOKEN="" \
node src/index.js >"$TMP_DIR/app.log" 2>&1 &
@@ -259,16 +324,45 @@ start_app_server() {
exit 1
}
login_finance_mgr() {
local login_body="$TMP_DIR/login.json"
login_user() {
local identifier="$1"
local password="$2"
local suffix="$3"
local out_file="$TMP_DIR/login-${suffix}.json"
local login_status
login_status="$(curl -sS -o "$login_body" -w "%{http_code}" \
-X POST "$BASE_URL/api/auth/login" \
-H "content-type: application/json" \
-H "x-device-fingerprint: ${DEVICE_FINGERPRINT}-finance" \
-d "{\"identifier\":\"$FINANCE_MGR_IDENTIFIER\",\"password\":\"$FINANCE_MGR_PASSWORD\"}")"
assert_status "$login_status" "200" "finance_mgr login"
TOKEN="$(jq -er '.data.accessToken' "$login_body")"
login_status="$(
curl -sS -o "$out_file" -w "%{http_code}" \
-X POST "$BASE_URL/api/auth/login" \
-H "content-type: application/json" \
-H "x-device-fingerprint: ${DEVICE_FINGERPRINT}-${suffix}" \
-d "$(jq -nc --arg identifier "$identifier" --arg password "$password" '{identifier: $identifier, password: $password}')"
)"
assert_status "$login_status" "200" "login ${identifier}" "$out_file"
jq -er '.data.accessToken' "$out_file"
}
login_finance_mgr() {
TOKEN="$(login_user "$FINANCE_MGR_IDENTIFIER" "$FINANCE_MGR_PASSWORD" finance)"
}
api_json_auth() {
local method="$1"
local path="$2"
local token="$3"
local out_file="$4"
local body="${5:-}"
if [[ -n "$body" ]]; then
curl -sS -o "$out_file" -w "%{http_code}" \
-X "$method" "$BASE_URL$path" \
-H "authorization: Bearer $token" \
-H "content-type: application/json" \
-d "$body"
else
curl -sS -o "$out_file" -w "%{http_code}" \
-X "$method" "$BASE_URL$path" \
-H "authorization: Bearer $token"
fi
}
set_erp_flag() {
@@ -460,6 +554,175 @@ const { createPrismaClient } = require('./src/prismaClient');
NODE
}
resolve_procurement_fixture_ids() {
DATABASE_URL="$DATABASE_URL" node - <<'NODE'
require('dotenv/config');
const { createPrismaClient } = require('./src/prismaClient');
const { resolveApplicableBudgetPoolByContext } = require('./src/services/budgetPool');
(async () => {
const { prisma, pool } = createPrismaClient();
await prisma.$connect();
try {
const employee = await prisma.employee.findUnique({
where: { email: process.env.SEED_EMPLOYEE_EMAIL ?? '[email protected]' },
select: { department_id: true, legal_entity_id: true },
});
const costCenter = await prisma.costCenter.findFirst({
where: {
enabled: true,
archived_at: null,
legal_entity_id: employee.legal_entity_id,
},
orderBy: { created_at: 'asc' },
select: { id: true },
});
const supplier = await prisma.supplier.findFirst({
where: {
enabled: true,
archived_at: null,
OR: [{ legal_entity_id: employee.legal_entity_id }, { legal_entity_id: null }],
},
orderBy: { created_at: 'asc' },
select: { id: true },
});
const documentCategory = await prisma.documentCategory.findFirst({
where: {
enabled: true,
archived_at: null,
entity_type: 'purchase_request',
},
orderBy: { created_at: 'asc' },
select: { id: true },
});
const budgetPool = await resolveApplicableBudgetPoolByContext(prisma, {
departmentId: employee.department_id,
legalEntityId: employee.legal_entity_id,
costCenterId: costCenter?.id ?? null,
effectiveDate: new Date(),
});
process.stdout.write(
[
employee.legal_entity_id,
costCenter?.id ?? '',
supplier?.id ?? '',
documentCategory?.id ?? '',
budgetPool?.id ?? '',
].join('\n'),
);
} finally {
await prisma.$disconnect();
await pool.end();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
NODE
}
query_outbox_by_key() {
local event_type="$1"
local dedupe_key="$2"
DATABASE_URL="$DATABASE_URL" EVENT_TYPE="$event_type" DEDUPE_KEY="$dedupe_key" node <<'NODE'
require('dotenv/config');
const { createPrismaClient } = require('./src/prismaClient');
(async () => {
const { prisma, pool } = createPrismaClient();
await prisma.$connect();
try {
const row = await prisma.integrationOutbox.findUnique({
where: {
event_type_dedupe_key: {
event_type: process.env.EVENT_TYPE,
dedupe_key: process.env.DEDUPE_KEY,
},
},
select: {
id: true,
event_type: true,
status: true,
attempts: true,
processed_at: true,
next_retry_at: true,
dead_letter_at: true,
last_error: true,
payload: true,
},
});
process.stdout.write(JSON.stringify(row ? {
id: row.id,
eventType: row.event_type,
status: row.status,
attempts: row.attempts,
processedAt: row.processed_at ? row.processed_at.toISOString() : null,
nextRetryAt: row.next_retry_at ? row.next_retry_at.toISOString() : null,
deadLetterAt: row.dead_letter_at ? row.dead_letter_at.toISOString() : null,
lastError: row.last_error,
payload: row.payload,
} : null));
} finally {
await prisma.$disconnect();
await pool.end();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
NODE
}
query_binding_by_key() {
local entity_type="$1"
local local_id="$2"
DATABASE_URL="$DATABASE_URL" ENTITY_TYPE="$entity_type" LOCAL_ID="$local_id" node <<'NODE'
require('dotenv/config');
const { createPrismaClient } = require('./src/prismaClient');
(async () => {
const { prisma, pool } = createPrismaClient();
await prisma.$connect();
try {
const row = await prisma.integrationBinding.findUnique({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: process.env.ENTITY_TYPE,
local_id: process.env.LOCAL_ID,
},
},
select: {
external_id: true,
external_code: true,
last_synced_at: true,
},
});
process.stdout.write(JSON.stringify({
externalId: row?.external_id ?? null,
externalCode: row?.external_code ?? null,
lastSyncedAt: row?.last_synced_at ? row.last_synced_at.toISOString() : null,
}));
} finally {
await prisma.$disconnect();
await pool.end();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
NODE
}
assert_outbox_absent_by_key() {
local event_type="$1"
local dedupe_key="$2"
local state_json
state_json="$(query_outbox_by_key "$event_type" "$dedupe_key")"
jq -e '. == null' <<<"$state_json" >/dev/null
}
assert_master_data_seeded() {
DATABASE_URL="$DATABASE_URL" LEGAL_ENTITY_CODE="$LEGAL_ENTITY_CODE" COST_CENTER_CODE="$COST_CENTER_CODE" SUPPLIER_CODE="$SUPPLIER_CODE" node <<'NODE'
require('dotenv/config');
@@ -497,16 +760,9 @@ NODE
}
run_outbox_once() {
local mode="$1"
DATABASE_URL="$DATABASE_URL" \
INTEGRATION_OUTBOX_BATCH_SIZE=500 \
ERP_SYNC_ENABLED=true \
ERP_SYNC_PROVIDER=http \
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/reimbursements/paid?mode=$mode" \
ERP_SYNC_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=$mode" \
ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_SYNC_AUTH_TOKEN="" \
npm run --silent job:integration-outbox-once >"$TMP_DIR/outbox-once.log"
local journal_mode="$1"
local procurement_mode="${2:-$journal_mode}"
DATABASE_URL="$DATABASE_URL" INTEGRATION_OUTBOX_BATCH_SIZE=500 ERP_SYNC_ENABLED=true ERP_SYNC_PROVIDER=http ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/export?mode=$journal_mode" ERP_PROCUREMENT_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/procurement/export?mode=$procurement_mode" ERP_SYNC_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=$journal_mode" ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" ERP_PROCUREMENT_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" ERP_SYNC_AUTH_TOKEN="" npm run --silent job:integration-outbox-once >"$TMP_DIR/outbox-once.log"
}
assert_pull_mode() {
@@ -553,6 +809,60 @@ api_post() {
-d "$body"
}
create_and_approve_purchase() {
local employee_token="$1"
local manager_token="$2"
local title_suffix="$3"
local tmp_prefix="$4"
local create_status
create_status="$(api_json_auth POST "/api/purchase-requests" "$employee_token" "$TMP_DIR/${tmp_prefix}-create.json" '{}')"
assert_status "$create_status" "200" "create purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-create.json"
local purchase_id
purchase_id="$(jq -er '.data.purchaseRequest.id' "$TMP_DIR/${tmp_prefix}-create.json")"
local patch_body
patch_body="$({
jq -nc \
--arg title "$title_suffix" \
--arg le "$LEGAL_ENTITY_ID" \
--arg cc "$COST_CENTER_ID" \
--arg sp "$SUPPLIER_ID" \
--arg dc "$DOCUMENT_CATEGORY_ID" \
'{title:$title, legalEntityId:$le, costCenterId:$cc, supplierId:$sp, documentCategoryId:$dc, items:[{description:"Laptop", specification:"14 inch", quantity:"2.00", unitPrice:"440.00", isAssetCandidate:true}] }'
})"
local patch_status
patch_status="$(api_json_auth PATCH "/api/purchase-requests/$purchase_id" "$employee_token" "$TMP_DIR/${tmp_prefix}-patch.json" "$patch_body")"
assert_status "$patch_status" "200" "patch purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-patch.json"
local submit_status
submit_status="$(api_json_auth POST "/api/purchase-requests/$purchase_id/submit" "$employee_token" "$TMP_DIR/${tmp_prefix}-submit.json" '{}')"
assert_status "$submit_status" "200" "submit purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-submit.json"
local task_id
task_id="$(jq -er '.data.currentTaskId' "$TMP_DIR/${tmp_prefix}-submit.json")"
local approve_status
approve_status="$(api_json_auth POST "/api/workflow/tasks/$task_id/approve" "$manager_token" "$TMP_DIR/${tmp_prefix}-approve.json" '{"comment":"approve procurement erp regression"}')"
assert_status "$approve_status" "200" "approve purchase ${title_suffix}" "$TMP_DIR/${tmp_prefix}-approve.json"
jq -e '.data.outcome == "approved" and .data.purchaseRequestStatus == "approved"' "$TMP_DIR/${tmp_prefix}-approve.json" >/dev/null
printf '%s\n%s' "$purchase_id" "$task_id"
}
archive_purchase_order() {
local finance_token="$1"
local purchase_id="$2"
local po_no="$3"
local contract_no="$4"
local tmp_prefix="$5"
local archive_status
archive_status="$(api_json_auth POST "/api/purchase-requests/$purchase_id/archive-order" "$finance_token" "$TMP_DIR/${tmp_prefix}-archive.json" "$(jq -nc --arg po "$po_no" --arg contract "$contract_no" '{poNo:$po, contractNo:$contract, archivedFiles:[]}')")"
assert_status "$archive_status" "200" "archive purchase ${purchase_id}" "$TMP_DIR/${tmp_prefix}-archive.json"
jq -e --arg po "$po_no" --arg contract "$contract_no" '.data.archiveOrder.poNo == $po and .data.archiveOrder.contractNo == $contract' "$TMP_DIR/${tmp_prefix}-archive.json" >/dev/null
jq -er '.data.archiveOrder.id' "$TMP_DIR/${tmp_prefix}-archive.json"
}
assert_export_mode_semantics() {
local mode="$1"
local state_json="$2"
@@ -692,7 +1002,95 @@ legacy_outbox_id="$(jq -er '.data.outboxId' "$legacy_body")"
legacy_state="$(query_outbox_state "$legacy_outbox_id")"
jq -e '.eventType == "erp.journal.export" and .status == "pending"' <<<"$legacy_state" >/dev/null
echo "[9/9] ERP env gate off blocks sync"
echo "[9/13] Procurement approval/archive auto export + bindings"
EMPLOYEE_TOKEN="$(login_user "$EMPLOYEE_IDENTIFIER" "$EMPLOYEE_PASSWORD" employee)"
MANAGER_TOKEN="$(login_user "$MANAGER_IDENTIFIER" "$MANAGER_PASSWORD" manager)"
FINANCE_MGR_TOKEN="$TOKEN"
mapfile -t FIXTURE_IDS < <(resolve_procurement_fixture_ids)
LEGAL_ENTITY_ID="${FIXTURE_IDS[0]}"
COST_CENTER_ID="${FIXTURE_IDS[1]}"
SUPPLIER_ID="${FIXTURE_IDS[2]}"
DOCUMENT_CATEGORY_ID="${FIXTURE_IDS[3]}"
BUDGET_POOL_ID="${FIXTURE_IDS[4]}"
mapfile -t PROCUREMENT_APPROVED < <(create_and_approve_purchase "$EMPLOYEE_TOKEN" "$MANAGER_TOKEN" "procurement erp success" "proc-success")
PURCHASE_ID_APPROVED="${PROCUREMENT_APPROVED[0]}"
COMMITMENT_DEDUPE="purchase_request:${PURCHASE_ID_APPROVED}:commitment"
commitment_state="$(query_outbox_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE")"
jq -e '.status == "pending" and .payload.journalType == "purchase_request_commitment"' <<<"$commitment_state" >/dev/null
run_outbox_once success success
commitment_state_done="$(query_outbox_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE")"
jq -e '.status == "succeeded"' <<<"$commitment_state_done" >/dev/null
commitment_binding="$(query_binding_by_key 'purchase_request_commitment_journal' "$PURCHASE_ID_APPROVED")"
jq -e '.externalCode != null' <<<"$commitment_binding" >/dev/null
ARCHIVE_ID_APPROVED="$(archive_purchase_order "$FINANCE_MGR_TOKEN" "$PURCHASE_ID_APPROVED" 'PO-P19ERP2-001' 'CT-P19ERP2-001' 'proc-success')"
ACCRUAL_DEDUPE="purchase_order_archive:${ARCHIVE_ID_APPROVED}:accrual"
SUMMARY_DEDUPE="purchase_order_archive:${ARCHIVE_ID_APPROVED}:summary"
accrual_state="$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE")"
summary_state="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")"
jq -e '.status == "pending" and .payload.journalType == "purchase_order_accrual"' <<<"$accrual_state" >/dev/null
jq -e '.status == "pending" and .payload.exportType == "purchase_order_archive"' <<<"$summary_state" >/dev/null
run_outbox_once success success
accrual_state_done="$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE")"
summary_state_done="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")"
jq -e '.status == "succeeded"' <<<"$accrual_state_done" >/dev/null
jq -e '.status == "succeeded"' <<<"$summary_state_done" >/dev/null
accrual_binding="$(query_binding_by_key 'purchase_order_accrual_journal' "$ARCHIVE_ID_APPROVED")"
po_binding="$(query_binding_by_key 'purchase_order_po' "$ARCHIVE_ID_APPROVED")"
contract_binding="$(query_binding_by_key 'purchase_order_contract' "$ARCHIVE_ID_APPROVED")"
jq -e '.externalCode != null' <<<"$accrual_binding" >/dev/null
jq -e '.externalCode != null' <<<"$po_binding" >/dev/null
jq -e '.externalCode != null' <<<"$contract_binding" >/dev/null
echo "[10/13] Archive update only resets summary"
ARCHIVE_UPDATE_STATUS="$(api_json_auth POST "/api/purchase-requests/$PURCHASE_ID_APPROVED/archive-order" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-success-archive-update.json" '{"poNo":"PO-P19ERP2-001","contractNo":"CT-P19ERP2-002","archivedFiles":[]}')"
assert_status "$ARCHIVE_UPDATE_STATUS" "200" "archive update" "$TMP_DIR/proc-success-archive-update.json"
accrual_state_after_update="$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE")"
summary_state_after_update="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")"
ACCRUAL_OUTBOX_ID="$(jq -er '.id' <<<"$accrual_state_done")"
SUMMARY_OUTBOX_ID="$(jq -er '.id' <<<"$summary_state_done")"
jq -e --arg id "$ACCRUAL_OUTBOX_ID" '.id == $id and .status == "succeeded"' <<<"$accrual_state_after_update" >/dev/null
jq -e --arg id "$SUMMARY_OUTBOX_ID" '.id == $id and .status == "pending" and .payload.contractNo == "CT-P19ERP2-002"' <<<"$summary_state_after_update" >/dev/null
run_outbox_once success success
contract_binding_updated="$(query_binding_by_key 'purchase_order_contract' "$ARCHIVE_ID_APPROVED")"
jq -e '.externalCode != null' <<<"$contract_binding_updated" >/dev/null
echo "[11/13] Force-off skips auto export and manual requeue backfills historical单据"
set_erp_flag "force_off"
mapfile -t PROCUREMENT_SKIPPED < <(create_and_approve_purchase "$EMPLOYEE_TOKEN" "$MANAGER_TOKEN" "procurement erp skipped" "proc-skipped")
PURCHASE_ID_SKIPPED="${PROCUREMENT_SKIPPED[0]}"
COMMITMENT_DEDUPE_SKIPPED="purchase_request:${PURCHASE_ID_SKIPPED}:commitment"
assert_outbox_absent_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE_SKIPPED"
ARCHIVE_ID_SKIPPED="$(archive_purchase_order "$FINANCE_MGR_TOKEN" "$PURCHASE_ID_SKIPPED" 'PO-P19ERP2-101' 'CT-P19ERP2-101' 'proc-skipped')"
ACCRUAL_DEDUPE_SKIPPED="purchase_order_archive:${ARCHIVE_ID_SKIPPED}:accrual"
SUMMARY_DEDUPE_SKIPPED="purchase_order_archive:${ARCHIVE_ID_SKIPPED}:summary"
assert_outbox_absent_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE_SKIPPED"
assert_outbox_absent_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE_SKIPPED"
set_erp_flag "force_on"
PROC_REQUEUE_CODE="$(api_json_auth POST "/api/integrations/erp/procurement/purchase-requests/$PURCHASE_ID_SKIPPED/requeue?runNow=0" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-requeue.json" '{"targets":["commitment_journal","accrual_journal","archive_summary"]}')"
assert_status "$PROC_REQUEUE_CODE" "200" "procurement requeue" "$TMP_DIR/proc-requeue.json"
jq -e '.data.items | length == 3' "$TMP_DIR/proc-requeue.json" >/dev/null
run_outbox_once success success
jq -e '.status == "succeeded"' <<<"$(query_outbox_by_key 'erp.journal.export' "$COMMITMENT_DEDUPE_SKIPPED")" >/dev/null
jq -e '.status == "succeeded"' <<<"$(query_outbox_by_key 'erp.journal.export' "$ACCRUAL_DEDUPE_SKIPPED")" >/dev/null
jq -e '.status == "succeeded"' <<<"$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE_SKIPPED")" >/dev/null
echo "[12/13] Archive summary dead-letter can requeue same outbox"
PROC_SUMMARY_FAIL_STATUS="$(api_json_auth POST "/api/purchase-requests/$PURCHASE_ID_APPROVED/archive-order" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-summary-fail-archive.json" '{"poNo":"PO-P19ERP2-001","contractNo":"CT-P19ERP2-003","archivedFiles":[]}')"
assert_status "$PROC_SUMMARY_FAIL_STATUS" "200" "archive update for summary failure" "$TMP_DIR/proc-summary-fail-archive.json"
run_outbox_once success client
summary_dead_state="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")"
jq -e '.status == "dead_letter" and .attempts == 1' <<<"$summary_dead_state" >/dev/null
SUMMARY_DEAD_ID="$(jq -er '.id' <<<"$summary_dead_state")"
PROC_SUMMARY_REQUEUE_CODE="$(api_json_auth POST "/api/integrations/erp/procurement/purchase-requests/$PURCHASE_ID_APPROVED/requeue?runNow=0" "$FINANCE_MGR_TOKEN" "$TMP_DIR/proc-summary-requeue.json" '{"targets":["archive_summary"]}')"
assert_status "$PROC_SUMMARY_REQUEUE_CODE" "200" "procurement summary requeue" "$TMP_DIR/proc-summary-requeue.json"
jq -e --arg id "$SUMMARY_DEAD_ID" '.data.items[0].outboxId == $id and .data.items[0].requeued == true' "$TMP_DIR/proc-summary-requeue.json" >/dev/null
run_outbox_once success success
summary_requeue_state="$(query_outbox_by_key 'erp.procurement.export' "$SUMMARY_DEDUPE")"
jq -e --arg id "$SUMMARY_DEAD_ID" '.id == $id and .status == "succeeded"' <<<"$summary_requeue_state" >/dev/null
echo "[13/13] ERP env gate off blocks sync"
if kill -0 "$APP_SERVER_PID" >/dev/null 2>&1; then
kill "$APP_SERVER_PID" >/dev/null 2>&1 || true
wait "$APP_SERVER_PID" >/dev/null 2>&1 || true
@@ -705,8 +1103,10 @@ OCR_PROVIDER=mock \
ERP_SYNC_ENABLED=false \
ERP_SYNC_PROVIDER=http \
ERP_MASTER_DATA_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/master-data/pull?mode=success" \
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/reimbursements/paid?mode=success" \
ERP_JOURNAL_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/journals/export?mode=success" \
ERP_PROCUREMENT_EXPORT_ENDPOINT="http://127.0.0.1:$MOCK_ERP_PORT/erp/procurement/export?mode=success" \
ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_PROCUREMENT_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_MASTER_DATA_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_SYNC_AUTH_TOKEN="" \
node src/index.js >"$TMP_DIR/app-gate-off.log" 2>&1 &
+4
查看文件
@@ -109,8 +109,12 @@ function getConfig() {
erpSyncProvider: process.env.ERP_SYNC_PROVIDER ?? "mock",
erpSyncEndpoint: process.env.ERP_SYNC_ENDPOINT ?? "",
erpJournalExportEndpoint: process.env.ERP_JOURNAL_EXPORT_ENDPOINT ?? "",
erpProcurementExportEndpoint: process.env.ERP_PROCUREMENT_EXPORT_ENDPOINT ?? "",
erpMasterDataEndpoint: process.env.ERP_MASTER_DATA_ENDPOINT ?? "",
erpSyncTimeoutMs: Number(process.env.ERP_SYNC_TIMEOUT_MS ?? 5000),
erpProcurementTimeoutMs: Number(
process.env.ERP_PROCUREMENT_TIMEOUT_MS ?? process.env.ERP_SYNC_TIMEOUT_MS ?? 5000,
),
erpMasterDataTimeoutMs: Number(
process.env.ERP_MASTER_DATA_TIMEOUT_MS ?? process.env.ERP_SYNC_TIMEOUT_MS ?? 5000,
),
+11
查看文件
@@ -41,6 +41,17 @@ async function runIntegrationOutboxOnce(prisma, config, logger) {
reimbursementId:
item.payload?.reimbursementId ??
(item.payload?.entityType === 'reimbursement_form' ? item.payload?.entityId ?? null : null),
purchaseRequestId:
item.payload?.purchaseRequestId ??
item.payload?.references?.purchaseRequestId ??
(item.payload?.entityType === 'purchase_request' ? item.payload?.entityId ?? null : null),
purchaseOrderArchiveId:
item.payload?.purchaseOrderArchiveId ??
item.payload?.references?.purchaseOrderArchiveId ??
(item.payload?.entityType === 'purchase_order_archive' ? item.payload?.entityId ?? null : null),
journalType: item.payload?.journalType ?? null,
poNo: item.payload?.poNo ?? item.payload?.references?.poNo ?? null,
contractNo: item.payload?.contractNo ?? item.payload?.references?.contractNo ?? null,
entityType: item.payload?.entityType ?? null,
entityId: item.payload?.entityId ?? null,
channelId: item.payload?.channelId ?? null,
+300
查看文件
@@ -19,12 +19,28 @@ const {
buildReimbursementJournalPreview,
enqueueReimbursementJournalExport,
} = require('../services/integrations/erpJournal');
const {
PROCUREMENT_ERP_TARGETS,
buildPurchaseRequestErpTrack,
enqueuePurchaseAccrualJournalExport,
enqueuePurchaseArchiveSummaryExport,
enqueuePurchaseCommitmentJournalExport,
loadPurchaseRequestErpContext,
} = require('../services/integrations/erpProcurement');
const UUID_SCHEMA = z.string().uuid();
const MASTER_DATA_RESOURCE_ENUM = z.enum(['legal_entity', 'cost_center', 'supplier']);
const MASTER_DATA_SYNC_BODY_SCHEMA = z.object({
resources: z.array(MASTER_DATA_RESOURCE_ENUM).max(3).optional(),
});
const PROCUREMENT_REQUEUE_TARGET_ENUM = z.enum([
'commitment_journal',
'accrual_journal',
'archive_summary',
]);
const PROCUREMENT_REQUEUE_BODY_SCHEMA = z.object({
targets: z.array(PROCUREMENT_REQUEUE_TARGET_ENUM).min(1).max(3),
});
const ERP_SYNC_RESPONSE_SCHEMA = {
type: 'object',
@@ -195,6 +211,145 @@ function ensurePaidReimbursement(reimbursement) {
}
}
function canReadPurchaseRequest(request, purchaseRequest) {
if (!purchaseRequest) {
return false;
}
const permissionCodes = request?.employee?.permissionCodes ?? [];
if (permissionCodes.includes('*') || permissionCodes.includes('procurement.view_all') || permissionCodes.includes('procurement.manage')) {
return true;
}
return (
purchaseRequest.applicant_id === request.employee.id ||
purchaseRequest.submitter_id === request.employee.id
);
}
function normalizeProcurementTargets(body) {
const parsed = PROCUREMENT_REQUEUE_BODY_SCHEMA.safeParse(body ?? {});
if (!parsed.success) {
throw new AppError({
code: 'VALID_001',
message: '参数校验失败',
statusCode: 400,
details: parsed.error.flatten(),
});
}
const orderedTargets = [
PROCUREMENT_ERP_TARGETS.commitmentJournal,
PROCUREMENT_ERP_TARGETS.accrualJournal,
PROCUREMENT_ERP_TARGETS.archiveSummary,
];
const requested = new Set(parsed.data.targets);
return orderedTargets.filter((target) => requested.has(target));
}
async function fetchReadablePurchaseRequestContext(prisma, purchaseRequestId, request) {
const context = await loadPurchaseRequestErpContext(prisma, purchaseRequestId);
if (!context?.purchaseRequest) {
throw new AppError({
code: 'SYS_404',
message: 'Not Found',
statusCode: 404,
});
}
if (!canReadPurchaseRequest(request, context.purchaseRequest)) {
throw new AppError({
code: 'PERM_001',
message: '无权限',
statusCode: 403,
});
}
return context;
}
function ensureProcurementTargetEligible(target, context) {
const purchaseRequest = context?.purchaseRequest;
const archive = purchaseRequest?.order_archive ?? null;
if (target === PROCUREMENT_ERP_TARGETS.commitmentJournal) {
if (purchaseRequest?.status !== 'approved') {
throw new AppError({
code: 'VALID_001',
message: '参数校验失败',
statusCode: 409,
details: { purchaseRequest: 'purchase_request_not_approved', target },
});
}
return;
}
if (!archive) {
throw new AppError({
code: 'VALID_001',
message: '参数校验失败',
statusCode: 409,
details: { purchaseOrderArchive: 'purchase_order_archive_missing', target },
});
}
}
async function enqueueProcurementTargetsAndMaybeRun({
prisma,
config,
logger,
context,
actorId,
targets,
runNow,
}) {
const purchaseRequest = context.purchaseRequest;
const archive = purchaseRequest.order_archive ?? null;
const items = [];
for (const target of targets) {
ensureProcurementTargetEligible(target, context);
if (target === PROCUREMENT_ERP_TARGETS.commitmentJournal) {
const enqueued = await enqueuePurchaseCommitmentJournalExport(prisma, config, {
purchaseRequest,
occurredAt: context.approvalOccurredAt ?? new Date(),
actorId,
requeueOnFailure: true,
});
items.push({ target, ...enqueued });
continue;
}
if (target === PROCUREMENT_ERP_TARGETS.accrualJournal) {
const enqueued = await enqueuePurchaseAccrualJournalExport(prisma, config, {
purchaseRequest,
archive,
occurredAt: archive.archived_at ?? new Date(),
actorId,
requeueOnFailure: true,
});
items.push({ target, ...enqueued });
continue;
}
const enqueued = await enqueuePurchaseArchiveSummaryExport(prisma, config, {
purchaseRequest,
archive,
archivedAt: archive.archived_at ?? new Date(),
actorId,
requeueOnFailure: true,
});
items.push({ target, ...enqueued });
}
if (runNow && items.some((item) => !item.duplicated || item.requeued)) {
await runIntegrationOutboxOnce(prisma, config, logger);
}
return items;
}
async function enqueueReimbursementExportAndMaybeRun({
prisma,
config,
@@ -454,6 +609,148 @@ async function integrationsRoutes(fastify) {
},
);
fastify.get(
'/integrations/erp/procurement/purchase-requests/:purchaseRequestId/track',
{
preHandler: fastify.authenticate,
schema: {
tags: ['integrations'],
summary: '查询采购 ERP 同步轨道',
security: [{ bearerAuth: [] }],
params: {
type: 'object',
required: ['purchaseRequestId'],
properties: {
purchaseRequestId: { type: 'string', format: 'uuid' },
},
},
},
},
async (request, reply) => {
const parsedId = UUID_SCHEMA.safeParse(request.params?.purchaseRequestId);
if (!parsedId.success) {
throw new AppError({
code: 'VALID_001',
message: '参数校验失败',
statusCode: 400,
details: { purchaseRequestId: 'invalid_uuid' },
});
}
const [context, gate] = await Promise.all([
fetchReadablePurchaseRequestContext(fastify.prisma, parsedId.data, request),
resolveErpGate(fastify.prisma, fastify.config),
]);
const canManage = fastify.hasPermission(request.employee, 'integration.manage');
const track = await buildPurchaseRequestErpTrack(fastify.prisma, fastify.config, parsedId.data, {
context,
canManage,
gate,
});
return sendData(reply, request, track);
},
);
fastify.post(
'/integrations/erp/procurement/purchase-requests/:purchaseRequestId/requeue',
{
preHandler: fastify.requirePermission('integration.manage'),
schema: {
tags: ['integrations'],
summary: '重试或补发采购 ERP 同步',
security: [{ bearerAuth: [] }],
params: {
type: 'object',
required: ['purchaseRequestId'],
properties: {
purchaseRequestId: { type: 'string', format: 'uuid' },
},
},
querystring: {
type: 'object',
properties: {
runNow: {
anyOf: [
{ type: 'string', enum: ['0', '1', 'false', 'true'] },
{ type: 'boolean' },
],
},
},
additionalProperties: true,
},
},
},
async (request, reply) => {
const parsedId = UUID_SCHEMA.safeParse(request.params?.purchaseRequestId);
if (!parsedId.success) {
throw new AppError({
code: 'VALID_001',
message: '参数校验失败',
statusCode: 400,
details: { purchaseRequestId: 'invalid_uuid' },
});
}
const targets = normalizeProcurementTargets(request.body);
const gate = await requireErpManagementGate(fastify.prisma, fastify.config);
const context = await loadPurchaseRequestErpContext(fastify.prisma, parsedId.data);
if (!context?.purchaseRequest) {
throw new AppError({
code: 'SYS_404',
message: 'Not Found',
statusCode: 404,
});
}
const items = await enqueueProcurementTargetsAndMaybeRun({
prisma: fastify.prisma,
config: fastify.config,
logger: fastify.log,
context,
actorId: request.employee.id,
targets,
runNow: parseRunNow(request.query),
});
for (const item of items) {
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: 'ERP_SYNC_ENQUEUED',
targetType: item.target === PROCUREMENT_ERP_TARGETS.commitmentJournal ? 'purchase_request' : 'purchase_order_archive',
targetId:
item.target === PROCUREMENT_ERP_TARGETS.commitmentJournal
? context.purchaseRequest.id
: context.purchaseRequest.order_archive?.id ?? null,
extra: {
erpTarget: item.target,
eventType: item.eventType,
purchaseRequestId: context.purchaseRequest.id,
purchaseOrderArchiveId: context.purchaseRequest.order_archive?.id ?? null,
outboxId: item.id,
duplicated: item.duplicated,
requeued: item.requeued,
gateReason: gate.effectiveReason,
featureFlag: FEATURE_FLAG_KEYS.erpSync,
},
}),
});
}
return sendData(reply, request, {
items: items.map((item) => ({
target: item.target,
outboxId: item.id,
status: item.status,
duplicated: item.duplicated,
requeued: item.requeued,
eventType: item.eventType,
})),
});
},
);
fastify.post(
'/integrations/erp/sync/:reimbursementId',
{
@@ -555,6 +852,9 @@ async function integrationsRoutes(fastify) {
}
integrationsRoutes.__testables = {
canReadPurchaseRequest,
ensureProcurementTargetEligible,
normalizeProcurementTargets,
normalizeResourcesInput,
parseRunNow,
};
+144
查看文件
@@ -11,6 +11,13 @@ const { signPayload, verifyToken } = require("../utils/signedUrl");
const { parseWorkflowSteps, resolveActionableStep, toMoneyString } = require("../utils/workflow");
const { resolveApplicableBudgetPoolByContext } = require("../services/budgetPool");
const { issueDocumentNumber } = require("../services/documentSequence");
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
const {
PROCUREMENT_ERP_TARGETS,
enqueuePurchaseAccrualJournalExport,
enqueuePurchaseArchiveSummaryExport,
loadPurchaseRequestErpContext,
} = require("../services/integrations/erpProcurement");
const { reserveBudgetForEntity, releaseReservedBudgetIfAny } = require("../services/purchaseBudget");
const { sendNotificationEmailSafe } = require("../services/email");
const { createNotifications, resolveRecipientsForAssignee } = require("../services/notifications");
@@ -837,6 +844,116 @@ async function loadReadablePurchaseRequest(tx, purchaseRequestId, request) {
return purchaseRequest;
}
async function handlePurchaseArchiveErpSync({
tx,
config,
request,
actorId,
purchaseRequestId,
archiveId,
isFirstArchive,
loadContext = loadPurchaseRequestErpContext,
evaluateGate = evaluateFeatureFlag,
enqueueAccrual = enqueuePurchaseAccrualJournalExport,
enqueueSummary = enqueuePurchaseArchiveSummaryExport,
}) {
const context = await loadContext(tx, purchaseRequestId);
if (!context?.purchaseRequest?.order_archive) {
return { skipped: true, reason: 'purchase_order_archive_missing' };
}
const purchaseRequest = context.purchaseRequest;
const archive = purchaseRequest.order_archive;
const departmentId = purchaseRequest.department_id ?? request.employee.department_id ?? null;
const gate = await evaluateGate({
prisma: tx,
config,
flagKey: FEATURE_FLAG_KEYS.erpSync,
departmentId,
strictDepartment: true,
});
if (!gate.enabled) {
const skipTargets = isFirstArchive
? [PROCUREMENT_ERP_TARGETS.accrualJournal, PROCUREMENT_ERP_TARGETS.archiveSummary]
: [PROCUREMENT_ERP_TARGETS.archiveSummary];
for (const erpTarget of skipTargets) {
await tx.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: 'ERP_SYNC_SKIPPED_BY_FEATURE_FLAG',
targetType: 'purchase_order_archive',
targetId: archiveId,
extra: {
erpTarget,
eventType: erpTarget === PROCUREMENT_ERP_TARGETS.archiveSummary ? 'erp.procurement.export' : 'erp.journal.export',
purchaseRequestId,
purchaseOrderArchiveId: archiveId,
gateReason: gate.reason,
featureFlag: FEATURE_FLAG_KEYS.erpSync,
departmentId,
},
}),
});
}
return { skipped: true, gate, purchaseRequest, archive };
}
const enqueuedItems = [];
if (isFirstArchive) {
const accrual = await enqueueAccrual(tx, config, {
purchaseRequest,
archive,
occurredAt: archive.archived_at ?? new Date(),
actorId,
requeueOnFailure: false,
});
enqueuedItems.push(accrual);
}
const summary = await enqueueSummary(tx, config, {
purchaseRequest,
archive,
archivedAt: archive.archived_at ?? new Date(),
actorId,
requeueOnFailure: false,
});
enqueuedItems.push(summary);
for (const item of enqueuedItems) {
await tx.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: 'ERP_SYNC_ENQUEUED',
targetType: 'purchase_order_archive',
targetId: archiveId,
extra: {
erpTarget: item.erpTarget,
eventType: item.eventType,
purchaseRequestId,
purchaseOrderArchiveId: archiveId,
outboxId: item.id,
duplicated: item.duplicated,
requeued: item.requeued,
gateReason: gate.reason,
featureFlag: FEATURE_FLAG_KEYS.erpSync,
departmentId,
},
}),
});
}
return {
skipped: false,
gate,
purchaseRequest,
archive,
items: enqueuedItems,
};
}
async function purchaseRequestRoutes(fastify) {
fastify.get(
"/purchase-requests",
@@ -1527,6 +1644,11 @@ async function purchaseRequestRoutes(fastify) {
throw buildValidationError({ status: "only_approved_archivable" }, 409);
}
const existingArchive = await tx.purchaseOrderArchive.findUnique({
where: { purchase_request_id: purchaseRequestId },
select: { id: true },
});
const archive = await tx.purchaseOrderArchive.upsert({
where: { purchase_request_id: purchaseRequestId },
update: {
@@ -1575,6 +1697,23 @@ async function purchaseRequestRoutes(fastify) {
}),
});
try {
await handlePurchaseArchiveErpSync({
tx,
config: fastify.config,
request,
actorId: request.employee.id,
purchaseRequestId,
archiveId: archive.id,
isFirstArchive: !existingArchive,
});
} catch (error) {
fastify.log.error(
{ err: error, purchaseRequestId, purchaseOrderArchiveId: archive.id },
"Failed to enqueue purchase archive ERP events",
);
}
response = {
archiveOrder: mapPurchaseOrderArchive(archive),
};
@@ -1942,3 +2081,8 @@ async function purchaseRequestRoutes(fastify) {
}
module.exports = purchaseRequestRoutes;
module.exports.__testables = {
handlePurchaseArchiveErpSync,
parseArchiveBody,
};
+106
查看文件
@@ -1,10 +1,17 @@
const { z } = require("zod");
const { AppError } = require("../utils/AppError");
const { buildAuditLogData } = require("../utils/audit");
const { sendData } = require("../utils/reply");
const { resolvePermissionsForRoles, hasPermission, ROLE_PERMISSIONS, resolveEntityPermission } = require("../constants/permissions");
const { getWorkflowStepsSnapshot, resolveActionableStep, toMoneyString } = require("../utils/workflow");
const { consumeReservedLeave, releaseReservedLeave, formatDateOnly } = require("../services/leave");
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
const { confirmBudgetForEntity, releaseReservedBudgetIfAny } = require("../services/purchaseBudget");
const {
PROCUREMENT_ERP_TARGETS,
enqueuePurchaseCommitmentJournalExport,
loadPurchaseRequestErpContext,
} = require("../services/integrations/erpProcurement");
const {
createNotifications,
resolveRecipientsForAssignee,
@@ -97,6 +104,89 @@ function parseTaskId(taskId) {
return parsed.data;
}
async function handlePurchaseApprovalErpSync({
tx,
config,
request,
actorId,
purchaseRequestId,
loadContext = loadPurchaseRequestErpContext,
evaluateGate = evaluateFeatureFlag,
enqueueCommitment = enqueuePurchaseCommitmentJournalExport,
}) {
const context = await loadContext(tx, purchaseRequestId);
if (!context?.purchaseRequest) {
return { skipped: true, reason: 'purchase_request_not_found' };
}
const purchaseRequest = context.purchaseRequest;
const departmentId = purchaseRequest.department_id ?? request.employee.department_id ?? null;
const gate = await evaluateGate({
prisma: tx,
config,
flagKey: FEATURE_FLAG_KEYS.erpSync,
departmentId,
strictDepartment: true,
});
if (!gate.enabled) {
await tx.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: 'ERP_SYNC_SKIPPED_BY_FEATURE_FLAG',
targetType: 'purchase_request',
targetId: purchaseRequest.id,
extra: {
erpTarget: PROCUREMENT_ERP_TARGETS.commitmentJournal,
eventType: 'erp.journal.export',
purchaseRequestId: purchaseRequest.id,
purchaseOrderArchiveId: null,
gateReason: gate.reason,
featureFlag: FEATURE_FLAG_KEYS.erpSync,
departmentId,
},
}),
});
return { skipped: true, gate, purchaseRequest };
}
const enqueued = await enqueueCommitment(tx, config, {
purchaseRequest,
occurredAt: context.approvalOccurredAt ?? new Date(),
actorId,
requeueOnFailure: false,
});
await tx.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: 'ERP_SYNC_ENQUEUED',
targetType: 'purchase_request',
targetId: purchaseRequest.id,
extra: {
erpTarget: PROCUREMENT_ERP_TARGETS.commitmentJournal,
eventType: enqueued.eventType,
purchaseRequestId: purchaseRequest.id,
purchaseOrderArchiveId: null,
outboxId: enqueued.id,
duplicated: enqueued.duplicated,
requeued: enqueued.requeued,
gateReason: gate.reason,
featureFlag: FEATURE_FLAG_KEYS.erpSync,
departmentId,
},
}),
});
return {
skipped: false,
gate,
purchaseRequest,
enqueued,
};
}
function parseTaskListQuery(query) {
const parsed = TASK_LIST_QUERY_SCHEMA.safeParse(query ?? {});
if (!parsed.success) {
@@ -1372,6 +1462,21 @@ async function workflowRoutes(fastify) {
actorId: request.employee.id,
note: "approved_confirm_purchase_budget",
});
try {
await handlePurchaseApprovalErpSync({
tx,
config: fastify.config,
request,
actorId: request.employee.id,
purchaseRequestId: workflowInstance.entity_id,
});
} catch (error) {
fastify.log.error(
{ err: error, purchaseRequestId: workflowInstance.entity_id },
"Failed to enqueue purchase approval ERP events",
);
}
}
await tx.workflowHistory.create({
@@ -1905,5 +2010,6 @@ async function workflowRoutes(fastify) {
module.exports = workflowRoutes;
module.exports.__testables = {
handlePurchaseApprovalErpSync,
listAllowedActionsForTask,
};
+146 -41
查看文件
@@ -1,4 +1,8 @@
const { pushPaidReimbursementToErp, exportJournalToErp } = require('./erp');
const {
pushPaidReimbursementToErp,
exportJournalToErp,
exportProcurementToErp,
} = require('./erp');
const { sendInstantMessageByChannel } = require('../notifications/channels');
class IntegrationDispatchError extends Error {
@@ -22,71 +26,168 @@ function toDispatchError(result) {
});
}
function extractExternalId(response) {
if (!response) {
function extractResponseValue(response, key) {
if (!response || !key) {
return null;
}
if (typeof response.externalId === 'string' && response.externalId.trim()) {
return response.externalId.trim();
const directValue = response[key];
if (typeof directValue === 'string' && directValue.trim()) {
return directValue.trim();
}
if (
typeof response.body?.externalId === 'string' &&
response.body.externalId.trim()
) {
return response.body.externalId.trim();
const bodyValue = response.body?.[key];
if (typeof bodyValue === 'string' && bodyValue.trim()) {
return bodyValue.trim();
}
return null;
}
async function upsertErpBindingForPayload(prisma, payload, response) {
const entityType = String(payload?.entityType ?? '').trim();
const entityId = String(payload?.entityId ?? '').trim();
if (!prisma || !entityType || !entityId) {
function createBindingSpec(entityType, localId, externalId, externalCode) {
const normalizedEntityType = String(entityType ?? '').trim();
const normalizedLocalId = String(localId ?? '').trim();
if (!normalizedEntityType || !normalizedLocalId) {
return null;
}
return {
entityType: normalizedEntityType,
localId: normalizedLocalId,
externalId: typeof externalId === 'string' ? externalId.trim() || null : null,
externalCode: typeof externalCode === 'string' ? externalCode.trim() || null : null,
};
}
function resolveBindingSpecs(eventType, payload, response) {
if (eventType === 'erp.reimbursement.paid') {
return [
createBindingSpec(
'reimbursement_journal',
payload?.reimbursementId ?? payload?.entityId,
extractResponseValue(response, 'externalId'),
payload?.formNumber ?? payload?.documentNo ?? null,
),
].filter(Boolean);
}
if (eventType === 'erp.journal.export') {
const journalType = String(payload?.journalType ?? '').trim();
if (journalType === 'reimbursement_paid') {
return [
createBindingSpec(
'reimbursement_journal',
payload?.entityId,
extractResponseValue(response, 'externalId'),
payload?.documentNo ?? payload?.formNumber ?? null,
),
].filter(Boolean);
}
if (journalType === 'purchase_request_commitment') {
return [
createBindingSpec(
'purchase_request_commitment_journal',
payload?.references?.purchaseRequestId ?? payload?.entityId,
extractResponseValue(response, 'externalId'),
extractResponseValue(response, 'externalCode') ?? payload?.references?.requestNo ?? payload?.documentNo ?? null,
),
].filter(Boolean);
}
if (journalType === 'purchase_order_accrual') {
return [
createBindingSpec(
'purchase_order_accrual_journal',
payload?.references?.purchaseOrderArchiveId ?? payload?.entityId,
extractResponseValue(response, 'externalId'),
extractResponseValue(response, 'externalCode') ?? payload?.references?.poNo ?? payload?.documentNo ?? null,
),
].filter(Boolean);
}
}
if (eventType === 'erp.procurement.export') {
const archiveId = payload?.entityId;
const specs = [];
if (archiveId && (payload?.poNo || extractResponseValue(response, 'externalPoId') || extractResponseValue(response, 'externalPoNo'))) {
specs.push(
createBindingSpec(
'purchase_order_po',
archiveId,
extractResponseValue(response, 'externalPoId'),
extractResponseValue(response, 'externalPoNo') ?? payload?.poNo ?? null,
),
);
}
if (archiveId && (payload?.contractNo || extractResponseValue(response, 'externalContractId') || extractResponseValue(response, 'externalContractNo'))) {
specs.push(
createBindingSpec(
'purchase_order_contract',
archiveId,
extractResponseValue(response, 'externalContractId'),
extractResponseValue(response, 'externalContractNo') ?? payload?.contractNo ?? null,
),
);
}
return specs.filter(Boolean);
}
return [];
}
async function upsertErpBindings(prisma, eventType, payload, response) {
if (!prisma) {
return;
}
if (entityType !== 'reimbursement_form') {
const specs = resolveBindingSpecs(eventType, payload, response);
if (!specs.length) {
return;
}
await prisma.integrationBinding.upsert({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: 'reimbursement_journal',
local_id: entityId,
for (const spec of specs) {
await prisma.integrationBinding.upsert({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: spec.entityType,
local_id: spec.localId,
},
},
},
create: {
provider: 'erp',
entity_type: 'reimbursement_journal',
local_id: entityId,
external_id: extractExternalId(response),
external_code: payload?.documentNo ?? payload?.formNumber ?? null,
last_synced_at: new Date(),
},
update: {
external_id: extractExternalId(response),
external_code: payload?.documentNo ?? payload?.formNumber ?? null,
last_synced_at: new Date(),
},
});
create: {
provider: 'erp',
entity_type: spec.entityType,
local_id: spec.localId,
external_id: spec.externalId,
external_code: spec.externalCode,
last_synced_at: new Date(),
},
update: {
external_id: spec.externalId,
external_code: spec.externalCode,
last_synced_at: new Date(),
},
});
}
}
async function dispatchErpEvent({ prisma, config, eventType, payload }) {
const result =
eventType === 'erp.journal.export'
? await exportJournalToErp(config, payload)
: await pushPaidReimbursementToErp(config, payload);
eventType === 'erp.procurement.export'
? await exportProcurementToErp(config, payload)
: eventType === 'erp.journal.export'
? await exportJournalToErp(config, payload)
: await pushPaidReimbursementToErp(config, payload);
if (!result.ok) {
throw toDispatchError(result);
}
await upsertErpBindingForPayload(prisma, payload, result.response ?? null);
await upsertErpBindings(prisma, eventType, payload, result.response ?? null);
return {
channel: 'erp',
@@ -96,7 +197,11 @@ async function dispatchErpEvent({ prisma, config, eventType, payload }) {
}
async function dispatchOutboxEvent({ prisma, config, eventType, payload }) {
if (eventType === 'erp.reimbursement.paid' || eventType === 'erp.journal.export') {
if (
eventType === 'erp.reimbursement.paid' ||
eventType === 'erp.journal.export' ||
eventType === 'erp.procurement.export'
) {
return dispatchErpEvent({ prisma, config, eventType, payload });
}
+64 -1
查看文件
@@ -34,6 +34,13 @@ function resolveJournalExportEndpoint(config) {
);
}
function resolveProcurementExportEndpoint(config) {
return (
String(config.erpProcurementExportEndpoint ?? '').trim() ||
String(config.erpSyncEndpoint ?? '').trim()
);
}
async function parseResponseBody(response) {
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
@@ -192,12 +199,14 @@ async function exportJournalToErp(config, payload) {
const provider = normalizeProvider(config);
if (provider === 'mock') {
const identity = payload?.documentNo ?? payload?.formNumber ?? payload?.entityId ?? payload?.reimbursementId ?? 'UNKNOWN';
return {
ok: true,
code: 'mock_synced',
message: 'mock ERP synced',
response: {
externalId: `ERP-${payload?.documentNo ?? payload?.formNumber ?? payload?.entityId ?? payload?.reimbursementId ?? 'UNKNOWN'}`,
externalId: `ERP-${identity}`,
externalCode: `ERP-${identity}`,
},
};
}
@@ -227,6 +236,59 @@ async function exportJournalToErp(config, payload) {
};
}
async function exportProcurementToErp(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') {
const identity = payload?.poNo ?? payload?.contractNo ?? payload?.entityId ?? 'UNKNOWN';
return {
ok: true,
code: 'mock_synced',
message: 'mock ERP procurement synced',
response: {
externalId: `ERP-PROC-${identity}`,
externalCode: `ERP-PROC-${identity}`,
externalPoId: payload?.poNo ? `ERP-PO-${payload.poNo}` : null,
externalPoNo: payload?.poNo ? `ERP-PO-${payload.poNo}` : null,
externalContractId: payload?.contractNo ? `ERP-CT-${payload.contractNo}` : null,
externalContractNo: payload?.contractNo ? `ERP-CT-${payload.contractNo}` : null,
},
};
}
if (provider === 'http') {
return postJsonToErp(config, {
endpoint: resolveProcurementExportEndpoint(config),
timeoutMs: coerceTimeout(config.erpProcurementTimeoutMs, config.erpSyncTimeoutMs),
payload,
successCode: 'http_synced',
successMessage: 'ERP procurement synced',
missingEndpointCode: 'erp_procurement_endpoint_missing',
missingEndpointMessage: 'ERP procurement endpoint missing',
http4xxCode: 'erp_procurement_http_4xx',
http5xxCode: 'erp_procurement_http_5xx',
timeoutCode: 'erp_procurement_timeout',
networkCode: 'erp_procurement_network_error',
messagePrefix: 'ERP procurement sync',
});
}
return {
ok: false,
code: 'erp_sync_provider_invalid',
message: `Unsupported ERP sync provider: ${provider}`,
retryable: false,
};
}
function buildErpPayload(input) {
return buildReimbursementJournalPayload(input);
}
@@ -238,6 +300,7 @@ async function pushPaidReimbursementToErp(config, payload) {
module.exports = {
buildErpPayload,
exportJournalToErp,
exportProcurementToErp,
normalizeProvider,
pullMasterDataFromErp,
pushPaidReimbursementToErp,
@@ -0,0 +1,704 @@
const crypto = require('node:crypto');
const { enqueueIntegrationEvent } = require('./outbox');
const PROCUREMENT_TRACK_STATUSES = Object.freeze({
notTriggered: 'not_triggered',
skipped: 'skipped',
});
const PROCUREMENT_ERP_TARGETS = Object.freeze({
commitmentJournal: 'commitment_journal',
accrualJournal: 'accrual_journal',
archiveSummary: 'archive_summary',
});
function normalizeString(value) {
const text = String(value ?? '').trim();
return text || null;
}
function toIsoString(value) {
if (!value) {
return null;
}
try {
return new Date(value).toISOString();
} catch {
return null;
}
}
function normalizeMoney(value) {
if (value == null) {
return '0.00';
}
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed || '0.00';
}
if (typeof value?.toString === 'function') {
return value.toString();
}
return '0.00';
}
function resolveCurrencyCode(purchaseRequest) {
return normalizeString(purchaseRequest?.currency_code) ?? 'CNY';
}
function resolveLegalEntityCode(purchaseRequest) {
return normalizeString(purchaseRequest?.legal_entity?.code);
}
function resolveCostCenterCode(purchaseRequest) {
return normalizeString(purchaseRequest?.cost_center?.code);
}
function resolveSupplierCode(purchaseRequest) {
return normalizeString(purchaseRequest?.supplier?.code);
}
function resolveBudgetPoolCode(purchaseRequest) {
return normalizeString(purchaseRequest?.budget_pool?.code);
}
function resolveDocumentCategoryCode(purchaseRequest) {
return normalizeString(purchaseRequest?.document_category?.code);
}
function stableNormalizeJson(value) {
if (Array.isArray(value)) {
return value.map((item) => stableNormalizeJson(item));
}
if (value && typeof value === 'object' && value.constructor === Object) {
return Object.keys(value)
.sort()
.reduce((result, key) => {
result[key] = stableNormalizeJson(value[key]);
return result;
}, {});
}
return value;
}
function stableStringifyJson(value) {
return JSON.stringify(stableNormalizeJson(value));
}
function hashProcurementPayload(value) {
return crypto.createHash('sha256').update(stableStringifyJson(value)).digest('hex');
}
function buildPurchaseCommitmentJournalPayload(input) {
const purchaseRequest = input?.purchaseRequest ?? {};
return {
journalType: 'purchase_request_commitment',
sourceEventName: 'purchase_request.approved',
entityType: 'purchase_request',
entityId: purchaseRequest.id ?? null,
documentNo: purchaseRequest.request_no ?? null,
currencyCode: resolveCurrencyCode(purchaseRequest),
totalAmount: normalizeMoney(purchaseRequest.total_amount),
occurredAt:
toIsoString(input?.occurredAt) ??
toIsoString(purchaseRequest.updated_at) ??
toIsoString(purchaseRequest.created_at),
dimensions: {
departmentId: purchaseRequest.department_id ?? null,
applicantEmployeeId: purchaseRequest.applicant_id ?? null,
submitterEmployeeId: purchaseRequest.submitter_id ?? null,
legalEntityCode: resolveLegalEntityCode(purchaseRequest),
costCenterCode: resolveCostCenterCode(purchaseRequest),
supplierCode: resolveSupplierCode(purchaseRequest),
budgetPoolCode: resolveBudgetPoolCode(purchaseRequest),
},
references: {
purchaseRequestId: purchaseRequest.id ?? null,
documentCategoryCode: resolveDocumentCategoryCode(purchaseRequest),
requestNo: purchaseRequest.request_no ?? null,
},
};
}
function buildPurchaseAccrualJournalPayload(input) {
const purchaseRequest = input?.purchaseRequest ?? {};
const archive = input?.archive ?? purchaseRequest.order_archive ?? {};
return {
journalType: 'purchase_order_accrual',
sourceEventName: 'purchase_order.archived',
entityType: 'purchase_order_archive',
entityId: archive.id ?? null,
documentNo: archive.po_no ?? null,
currencyCode: resolveCurrencyCode(purchaseRequest),
totalAmount: normalizeMoney(purchaseRequest.total_amount),
occurredAt:
toIsoString(input?.occurredAt) ??
toIsoString(archive.archived_at) ??
toIsoString(purchaseRequest.updated_at) ??
toIsoString(purchaseRequest.created_at),
dimensions: {
departmentId: purchaseRequest.department_id ?? null,
applicantEmployeeId: purchaseRequest.applicant_id ?? null,
submitterEmployeeId: purchaseRequest.submitter_id ?? null,
legalEntityCode: resolveLegalEntityCode(purchaseRequest),
costCenterCode: resolveCostCenterCode(purchaseRequest),
supplierCode: resolveSupplierCode(purchaseRequest),
budgetPoolCode: resolveBudgetPoolCode(purchaseRequest),
},
references: {
purchaseRequestId: purchaseRequest.id ?? null,
purchaseOrderArchiveId: archive.id ?? null,
requestNo: purchaseRequest.request_no ?? null,
poNo: archive.po_no ?? null,
contractNo: archive.contract_no ?? null,
},
};
}
function buildPurchaseArchiveSummaryPayload(input) {
const purchaseRequest = input?.purchaseRequest ?? {};
const archive = input?.archive ?? purchaseRequest.order_archive ?? {};
const archivedFiles = Array.isArray(archive.archived_files)
? archive.archived_files.map((file) => ({
storagePath: file?.storagePath ?? null,
originalName: file?.originalName ?? null,
mimeType: file?.mimeType ?? null,
fileSize: Number(file?.fileSize ?? 0),
}))
: [];
return {
exportType: 'purchase_order_archive',
sourceEventName: 'purchase_order.archived',
entityType: 'purchase_order_archive',
entityId: archive.id ?? null,
purchaseRequestId: purchaseRequest.id ?? null,
requestNo: purchaseRequest.request_no ?? null,
poNo: archive.po_no ?? null,
contractNo: archive.contract_no ?? null,
currencyCode: resolveCurrencyCode(purchaseRequest),
totalAmount: normalizeMoney(purchaseRequest.total_amount),
archivedAt:
toIsoString(input?.archivedAt) ??
toIsoString(archive.archived_at) ??
toIsoString(purchaseRequest.updated_at) ??
toIsoString(purchaseRequest.created_at),
supplier: purchaseRequest.supplier
? {
id: purchaseRequest.supplier.id,
code: purchaseRequest.supplier.code ?? null,
name: purchaseRequest.supplier.name ?? null,
}
: {
id: purchaseRequest.supplier_id ?? null,
code: null,
name: null,
},
dimensions: {
legalEntityCode: resolveLegalEntityCode(purchaseRequest),
costCenterCode: resolveCostCenterCode(purchaseRequest),
departmentId: purchaseRequest.department_id ?? null,
},
files: archivedFiles,
};
}
function buildPurchaseCommitmentJournalDedupeKey(purchaseRequestId) {
return `purchase_request:${purchaseRequestId}:commitment`;
}
function buildPurchaseAccrualJournalDedupeKey(archiveId) {
return `purchase_order_archive:${archiveId}:accrual`;
}
function buildPurchaseArchiveSummaryDedupeKey(archiveId) {
return `purchase_order_archive:${archiveId}:summary`;
}
function mapIntegrationBinding(record) {
if (!record) {
return null;
}
return {
id: record.id,
provider: record.provider,
entityType: record.entity_type,
localId: record.local_id,
externalId: record.external_id ?? null,
externalCode: record.external_code ?? null,
lastSyncedAt: record.last_synced_at?.toISOString?.() ?? null,
};
}
function redactBinding(binding, canManage) {
if (!binding) {
return null;
}
if (canManage) {
return binding;
}
return {
...binding,
externalId: null,
externalCode: null,
};
}
function mapIntegrationOutboxState(record) {
if (!record) {
return null;
}
return {
id: record.id,
eventType: record.event_type,
status: record.status,
attempts: Number(record.attempts ?? 0),
lastError: record.last_error ?? null,
processedAt: record.processed_at?.toISOString?.() ?? null,
updatedAt: record.updated_at?.toISOString?.() ?? null,
};
}
async function findOutboxByKey(prisma, eventType, dedupeKey) {
if (!prisma || !eventType || !dedupeKey) {
return null;
}
return prisma.integrationOutbox.findUnique({
where: {
event_type_dedupe_key: {
event_type: eventType,
dedupe_key: dedupeKey,
},
},
});
}
async function findBindingByLocalId(prisma, entityType, localId) {
if (!prisma || !entityType || !localId) {
return null;
}
return prisma.integrationBinding.findUnique({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: entityType,
local_id: localId,
},
},
});
}
async function enqueuePurchaseCommitmentJournalExport(prisma, config, input) {
const payload =
input?.payload ??
buildPurchaseCommitmentJournalPayload({
purchaseRequest: input?.purchaseRequest,
occurredAt: input?.occurredAt,
});
const enqueued = await enqueueIntegrationEvent(prisma, {
eventType: 'erp.journal.export',
payload,
dedupeKey: buildPurchaseCommitmentJournalDedupeKey(payload.entityId),
maxAttempts: config.integrationOutboxMaxAttempts,
actorId: input?.actorId ?? null,
requeueOnFailure: input?.requeueOnFailure === true,
});
return {
...enqueued,
eventType: 'erp.journal.export',
erpTarget: PROCUREMENT_ERP_TARGETS.commitmentJournal,
payload,
};
}
async function enqueuePurchaseAccrualJournalExport(prisma, config, input) {
const payload =
input?.payload ??
buildPurchaseAccrualJournalPayload({
purchaseRequest: input?.purchaseRequest,
archive: input?.archive,
occurredAt: input?.occurredAt,
});
const enqueued = await enqueueIntegrationEvent(prisma, {
eventType: 'erp.journal.export',
payload,
dedupeKey: buildPurchaseAccrualJournalDedupeKey(payload.entityId),
maxAttempts: config.integrationOutboxMaxAttempts,
actorId: input?.actorId ?? null,
requeueOnFailure: input?.requeueOnFailure === true,
});
return {
...enqueued,
eventType: 'erp.journal.export',
erpTarget: PROCUREMENT_ERP_TARGETS.accrualJournal,
payload,
};
}
async function enqueuePurchaseArchiveSummaryExport(prisma, config, input) {
const payload =
input?.payload ??
buildPurchaseArchiveSummaryPayload({
purchaseRequest: input?.purchaseRequest,
archive: input?.archive,
archivedAt: input?.archivedAt,
});
const enqueued = await enqueueIntegrationEvent(prisma, {
eventType: 'erp.procurement.export',
payload,
dedupeKey: buildPurchaseArchiveSummaryDedupeKey(payload.entityId),
maxAttempts: config.integrationOutboxMaxAttempts,
actorId: input?.actorId ?? null,
requeueOnFailure: input?.requeueOnFailure === true,
resetOnPayloadChange: true,
});
return {
...enqueued,
eventType: 'erp.procurement.export',
erpTarget: PROCUREMENT_ERP_TARGETS.archiveSummary,
payload,
};
}
async function loadPurchaseRequestErpContext(prisma, purchaseRequestId) {
const purchaseRequest = await prisma.purchaseRequest.findUnique({
where: { id: purchaseRequestId },
select: {
id: true,
request_no: true,
applicant_id: true,
submitter_id: true,
department_id: true,
legal_entity_id: true,
cost_center_id: true,
supplier_id: true,
document_category_id: true,
budget_pool_id: true,
status: true,
currency_code: true,
total_amount: true,
created_at: true,
updated_at: true,
applicant: {
select: {
id: true,
employee_no: true,
name: true,
},
},
submitter: {
select: {
id: true,
employee_no: true,
name: true,
},
},
legal_entity: {
select: {
id: true,
code: true,
name: true,
},
},
cost_center: {
select: {
id: true,
code: true,
name: true,
},
},
supplier: {
select: {
id: true,
code: true,
name: true,
},
},
document_category: {
select: {
id: true,
code: true,
name: true,
},
},
budget_pool: {
select: {
id: true,
code: true,
name: true,
},
},
order_archive: {
select: {
id: true,
po_no: true,
contract_no: true,
archived_files: true,
archived_at: true,
archived_by: true,
},
},
workflow_instances: {
where: { entity_type: 'purchase_request' },
orderBy: { created_at: 'desc' },
take: 1,
select: { id: true },
},
},
});
if (!purchaseRequest) {
return null;
}
const workflowInstanceId = purchaseRequest.workflow_instances?.[0]?.id ?? null;
const approvalHistory = workflowInstanceId
? await prisma.workflowHistory.findFirst({
where: {
instance_id: workflowInstanceId,
action: 'approve',
},
orderBy: { created_at: 'desc' },
select: { created_at: true },
})
: null;
return {
purchaseRequest,
approvalOccurredAt:
approvalHistory?.created_at ?? purchaseRequest.updated_at ?? purchaseRequest.created_at ?? null,
};
}
function hasAnyBinding(binding) {
if (!binding) {
return false;
}
return Boolean(binding.externalId || binding.externalCode || binding.lastSyncedAt);
}
function resolveTrackStageStatus({ eligible, outbox, binding, bindings, gateEnabled }) {
if (outbox?.status) {
return outbox.status;
}
if (binding && hasAnyBinding(binding)) {
return 'succeeded';
}
if (bindings && Object.values(bindings).some((item) => hasAnyBinding(item))) {
return 'succeeded';
}
if (!eligible) {
return PROCUREMENT_TRACK_STATUSES.notTriggered;
}
if (!gateEnabled) {
return PROCUREMENT_TRACK_STATUSES.skipped;
}
return PROCUREMENT_TRACK_STATUSES.notTriggered;
}
function buildPurchaseTrackSummary(context) {
const purchaseRequest = context?.purchaseRequest ?? {};
const archive = purchaseRequest.order_archive ?? null;
return {
id: purchaseRequest.id,
requestNo: purchaseRequest.request_no ?? null,
status: purchaseRequest.status,
totalAmount: normalizeMoney(purchaseRequest.total_amount),
supplier: purchaseRequest.supplier
? {
id: purchaseRequest.supplier.id,
code: purchaseRequest.supplier.code ?? null,
name: purchaseRequest.supplier.name ?? null,
}
: null,
archiveOrder: archive
? {
id: archive.id,
poNo: archive.po_no,
contractNo: archive.contract_no ?? null,
archivedAt: toIsoString(archive.archived_at),
}
: null,
};
}
async function buildPurchaseRequestErpTrack(prisma, config, purchaseRequestId, options = {}) {
const context = options.context ?? (await loadPurchaseRequestErpContext(prisma, purchaseRequestId));
if (!context) {
return null;
}
const purchaseRequest = context.purchaseRequest;
const archive = purchaseRequest.order_archive ?? null;
const canManage = Boolean(options.canManage);
const gateEnabled = Boolean(options.gate?.effectiveEnabled ?? options.gate?.enabled ?? true);
const [
commitmentOutboxRow,
accrualOutboxRow,
summaryOutboxRow,
commitmentBindingRow,
accrualBindingRow,
poBindingRow,
contractBindingRow,
] = await Promise.all([
findOutboxByKey(
prisma,
'erp.journal.export',
buildPurchaseCommitmentJournalDedupeKey(purchaseRequest.id),
),
archive
? findOutboxByKey(
prisma,
'erp.journal.export',
buildPurchaseAccrualJournalDedupeKey(archive.id),
)
: Promise.resolve(null),
archive
? findOutboxByKey(
prisma,
'erp.procurement.export',
buildPurchaseArchiveSummaryDedupeKey(archive.id),
)
: Promise.resolve(null),
findBindingByLocalId(prisma, 'purchase_request_commitment_journal', purchaseRequest.id),
archive
? findBindingByLocalId(prisma, 'purchase_order_accrual_journal', archive.id)
: Promise.resolve(null),
archive ? findBindingByLocalId(prisma, 'purchase_order_po', archive.id) : Promise.resolve(null),
archive
? findBindingByLocalId(prisma, 'purchase_order_contract', archive.id)
: Promise.resolve(null),
]);
const commitmentPreview = buildPurchaseCommitmentJournalPayload({
purchaseRequest,
occurredAt: context.approvalOccurredAt,
});
const accrualPreview = archive
? buildPurchaseAccrualJournalPayload({
purchaseRequest,
archive,
occurredAt: archive.archived_at,
})
: {};
const summaryPreview = archive
? buildPurchaseArchiveSummaryPayload({
purchaseRequest,
archive,
archivedAt: archive.archived_at,
})
: {};
const commitmentBinding = redactBinding(mapIntegrationBinding(commitmentBindingRow), canManage);
const accrualBinding = redactBinding(mapIntegrationBinding(accrualBindingRow), canManage);
const poBinding = redactBinding(mapIntegrationBinding(poBindingRow), canManage);
const contractBinding = redactBinding(mapIntegrationBinding(contractBindingRow), canManage);
const commitmentOutbox = mapIntegrationOutboxState(commitmentOutboxRow);
const accrualOutbox = mapIntegrationOutboxState(accrualOutboxRow);
const summaryOutbox = mapIntegrationOutboxState(summaryOutboxRow);
const commitmentEligible = purchaseRequest.status === 'approved';
const archiveEligible = Boolean(archive);
return {
purchaseRequest: buildPurchaseTrackSummary(context),
stages: {
commitmentJournal: {
eligible: commitmentEligible,
reason: commitmentEligible ? null : 'purchase_request_not_approved',
status: resolveTrackStageStatus({
eligible: commitmentEligible,
outbox: commitmentOutbox,
binding: commitmentBinding,
gateEnabled,
}),
preview: commitmentPreview,
outbox: commitmentOutbox,
binding: commitmentBinding,
},
accrualJournal: {
eligible: archiveEligible,
reason: archiveEligible ? null : 'purchase_order_archive_missing',
status: resolveTrackStageStatus({
eligible: archiveEligible,
outbox: accrualOutbox,
binding: accrualBinding,
gateEnabled,
}),
preview: accrualPreview,
outbox: accrualOutbox,
binding: accrualBinding,
},
archiveSummary: {
eligible: archiveEligible,
reason: archiveEligible ? null : 'purchase_order_archive_missing',
status: resolveTrackStageStatus({
eligible: archiveEligible,
outbox: summaryOutbox,
bindings: {
po: poBinding,
contract: contractBinding,
},
gateEnabled,
}),
preview: summaryPreview,
outbox: summaryOutbox,
bindings: {
po: poBinding,
contract: contractBinding,
},
},
},
permissions: {
canRetry: Boolean(canManage && gateEnabled),
},
};
}
module.exports = {
PROCUREMENT_ERP_TARGETS,
PROCUREMENT_TRACK_STATUSES,
buildPurchaseAccrualJournalDedupeKey,
buildPurchaseAccrualJournalPayload,
buildPurchaseArchiveSummaryDedupeKey,
buildPurchaseArchiveSummaryPayload,
buildPurchaseCommitmentJournalDedupeKey,
buildPurchaseCommitmentJournalPayload,
buildPurchaseRequestErpTrack,
enqueuePurchaseAccrualJournalExport,
enqueuePurchaseArchiveSummaryExport,
enqueuePurchaseCommitmentJournalExport,
hashProcurementPayload,
loadPurchaseRequestErpContext,
stableStringifyJson,
};
+59 -26
查看文件
@@ -35,6 +35,55 @@ function formatDispatchError(error) {
return parts.join(' | ');
}
function stableNormalizeJson(value) {
if (Array.isArray(value)) {
return value.map((item) => stableNormalizeJson(item));
}
if (value && typeof value === 'object' && value.constructor === Object) {
return Object.keys(value)
.sort()
.reduce((result, key) => {
result[key] = stableNormalizeJson(value[key]);
return result;
}, {});
}
return value;
}
function hasIntegrationPayloadChanged(currentPayload, nextPayload) {
return JSON.stringify(stableNormalizeJson(currentPayload)) !== JSON.stringify(stableNormalizeJson(nextPayload));
}
async function resetExistingOutbox(prisma, existed, input) {
const reset = await prisma.integrationOutbox.update({
where: { id: existed.id },
data: {
status: OUTBOX_STATUSES.pending,
payload: input.payload,
attempts: 0,
max_attempts: input.maxAttempts,
last_error: null,
next_retry_at: null,
processed_at: null,
dead_letter_at: null,
updated_by: input.actorId ?? null,
},
select: {
id: true,
status: true,
},
});
return {
id: reset.id,
status: reset.status,
duplicated: false,
requeued: true,
};
}
async function enqueueIntegrationEvent(prisma, input) {
const dedupeKey = input.dedupeKey ?? null;
@@ -47,40 +96,23 @@ async function enqueueIntegrationEvent(prisma, input) {
dedupe_key: dedupeKey,
},
},
select: { id: true, status: true },
select: { id: true, status: true, payload: true },
})
: null;
if (existed) {
if (
input.resetOnPayloadChange &&
hasIntegrationPayloadChanged(existed.payload, input.payload)
) {
return resetExistingOutbox(prisma, existed, input);
}
if (
input.requeueOnFailure &&
[OUTBOX_STATUSES.failed, OUTBOX_STATUSES.dead_letter].includes(existed.status)
) {
const reset = await prisma.integrationOutbox.update({
where: { id: existed.id },
data: {
status: OUTBOX_STATUSES.pending,
payload: input.payload,
attempts: 0,
max_attempts: input.maxAttempts,
last_error: null,
next_retry_at: null,
processed_at: null,
dead_letter_at: null,
updated_by: input.actorId ?? null,
},
select: {
id: true,
status: true,
},
});
return {
id: reset.id,
status: reset.status,
duplicated: false,
requeued: true,
};
return resetExistingOutbox(prisma, existed, input);
}
return {
@@ -188,6 +220,7 @@ module.exports = {
OUTBOX_STATUSES,
enqueueIntegrationEvent,
fetchPendingOutboxEvents,
hasIntegrationPayloadChanged,
markOutboxProcessing,
markOutboxSucceeded,
markOutboxFailed,
+206 -110
查看文件
@@ -1,9 +1,9 @@
const {
IntegrationDispatchError,
dispatchOutboxEvent,
} = require("../../src/services/integrations/dispatcher");
} = require('../../src/services/integrations/dispatcher');
describe("dispatchOutboxEvent", () => {
describe('dispatchOutboxEvent', () => {
const originalFetch = global.fetch;
afterEach(() => {
@@ -11,25 +11,25 @@ describe("dispatchOutboxEvent", () => {
vi.restoreAllMocks();
});
it("handles mock ERP success", async () => {
it('handles mock ERP success', async () => {
const result = await dispatchOutboxEvent({
config: {
erpSyncEnabled: true,
erpSyncProvider: "mock",
erpSyncProvider: 'mock',
},
eventType: "erp.reimbursement.paid",
eventType: 'erp.reimbursement.paid',
payload: {
reimbursementId: "rb-1",
formNumber: "BX-001",
reimbursementId: 'rb-1',
formNumber: 'BX-001',
},
});
expect(result.channel).toBe("erp");
expect(result.code).toBe("mock_synced");
expect(result.response.externalId).toContain("BX-001");
expect(result.channel).toBe('erp');
expect(result.code).toBe('mock_synced');
expect(result.response.externalId).toContain('BX-001');
});
it("records integration binding for standard journal export", async () => {
it('records integration binding for reimbursement journal export', async () => {
const prisma = {
integrationBinding: {
upsert: vi.fn().mockResolvedValue({ id: 'binding-1' }),
@@ -44,6 +44,7 @@ describe("dispatchOutboxEvent", () => {
},
eventType: 'erp.journal.export',
payload: {
journalType: 'reimbursement_paid',
entityType: 'reimbursement_form',
entityId: 'rb-1',
documentNo: 'BX-20260308-0001',
@@ -64,23 +65,135 @@ describe("dispatchOutboxEvent", () => {
);
});
it("loads IM channel and dispatches mock wecom message", async () => {
it('records commitment binding for procurement journal export', async () => {
const prisma = {
integrationBinding: {
upsert: vi.fn().mockResolvedValue({ id: 'binding-1' }),
},
};
await dispatchOutboxEvent({
prisma,
config: { erpSyncEnabled: true, erpSyncProvider: 'mock' },
eventType: 'erp.journal.export',
payload: {
journalType: 'purchase_request_commitment',
entityType: 'purchase_request',
entityId: 'pr-1',
documentNo: 'PR-001',
references: { purchaseRequestId: 'pr-1', requestNo: 'PR-001' },
},
});
expect(prisma.integrationBinding.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: 'purchase_request_commitment_journal',
local_id: 'pr-1',
},
},
}),
);
});
it('records accrual binding for procurement journal export', async () => {
const prisma = {
integrationBinding: {
upsert: vi.fn().mockResolvedValue({ id: 'binding-1' }),
},
};
await dispatchOutboxEvent({
prisma,
config: { erpSyncEnabled: true, erpSyncProvider: 'mock' },
eventType: 'erp.journal.export',
payload: {
journalType: 'purchase_order_accrual',
entityType: 'purchase_order_archive',
entityId: 'archive-1',
documentNo: 'PO-001',
references: { purchaseOrderArchiveId: 'archive-1', poNo: 'PO-001' },
},
});
expect(prisma.integrationBinding.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: 'purchase_order_accrual_journal',
local_id: 'archive-1',
},
},
}),
);
});
it('records PO and contract bindings for procurement summary export', async () => {
const prisma = {
integrationBinding: {
upsert: vi.fn().mockResolvedValue({ id: 'binding-1' }),
},
};
await dispatchOutboxEvent({
prisma,
config: { erpSyncEnabled: true, erpSyncProvider: 'mock' },
eventType: 'erp.procurement.export',
payload: {
exportType: 'purchase_order_archive',
entityType: 'purchase_order_archive',
entityId: 'archive-1',
poNo: 'PO-001',
contractNo: 'CT-001',
},
});
expect(prisma.integrationBinding.upsert).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: 'purchase_order_po',
local_id: 'archive-1',
},
},
}),
);
expect(prisma.integrationBinding.upsert).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
where: {
provider_entity_type_local_id: {
provider: 'erp',
entity_type: 'purchase_order_contract',
local_id: 'archive-1',
},
},
}),
);
});
it('loads IM channel and dispatches mock wecom message', async () => {
const prisma = {
notificationChannel: {
findUnique: vi.fn().mockResolvedValue({
id: "channel-1",
channel_type: "wecom",
name: "采购经理群",
id: 'channel-1',
channel_type: 'wecom',
name: '采购经理群',
enabled: true,
config_json: {
mode: "mock",
mode: 'mock',
routing: {},
},
template_json: {
title: "{{title}}",
body: "{{body}}",
footer: "来自海音达工作台",
deepLinkLabel: "查看详情",
title: '{{title}}',
body: '{{body}}',
footer: '来自海音达工作台',
deepLinkLabel: '查看详情',
},
}),
},
@@ -91,18 +204,18 @@ describe("dispatchOutboxEvent", () => {
config: {
imNotifierEnabled: true,
},
eventType: "notification.im",
eventType: 'notification.im',
payload: {
channelId: "channel-1",
channelType: "wecom",
notificationType: "workflow.task_assigned",
title: "【待办】采购申请待审批",
body: "采购申请已流转到你,请及时处理。",
channelId: 'channel-1',
channelType: 'wecom',
notificationType: 'workflow.task_assigned',
title: '【待办】采购申请待审批',
body: '采购申请已流转到你,请及时处理。',
},
});
expect(prisma.notificationChannel.findUnique).toHaveBeenCalledWith({
where: { id: "channel-1" },
where: { id: 'channel-1' },
select: {
id: true,
channel_type: true,
@@ -112,12 +225,12 @@ describe("dispatchOutboxEvent", () => {
template_json: true,
},
});
expect(result.channel).toBe("im");
expect(result.code).toBe("mock_sent");
expect(result.previewMessage).toContain("采购申请待审批");
expect(result.channel).toBe('im');
expect(result.code).toBe('mock_sent');
expect(result.previewMessage).toContain('采购申请待审批');
});
it("safely skips missing IM channel", async () => {
it('safely skips missing IM channel', async () => {
const result = await dispatchOutboxEvent({
prisma: {
notificationChannel: {
@@ -127,28 +240,28 @@ describe("dispatchOutboxEvent", () => {
config: {
imNotifierEnabled: true,
},
eventType: "notification.im",
eventType: 'notification.im',
payload: {
channelId: "missing-channel",
channelType: "wecom",
channelId: 'missing-channel',
channelType: 'wecom',
},
});
expect(result.channel).toBe("im");
expect(result.code).toBe("channel_not_found");
expect(result.channel).toBe('im');
expect(result.code).toBe('channel_not_found');
expect(result.skipped).toBe(true);
});
it("safely skips disabled IM channel", async () => {
it('safely skips disabled IM channel', async () => {
const result = await dispatchOutboxEvent({
prisma: {
notificationChannel: {
findUnique: vi.fn().mockResolvedValue({
id: "channel-2",
channel_type: "wecom",
name: "disabled",
id: 'channel-2',
channel_type: 'wecom',
name: 'disabled',
enabled: false,
config_json: { mode: "mock", routing: {} },
config_json: { mode: 'mock', routing: {} },
template_json: null,
}),
},
@@ -156,22 +269,23 @@ describe("dispatchOutboxEvent", () => {
config: {
imNotifierEnabled: true,
},
eventType: "notification.im",
eventType: 'notification.im',
payload: {
channelId: "channel-2",
channelType: "wecom",
channelId: 'channel-2',
channelType: 'wecom',
},
});
expect(result.code).toBe("channel_disabled");
expect(result.code).toBe('channel_disabled');
expect(result.skipped).toBe(true);
});
it("maps wecom 4xx as non-retryable IM dispatch error", async () => {
it('maps wecom 4xx as non-retryable IM dispatch error', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
json: vi.fn().mockResolvedValue({ errcode: 40013, errmsg: "bad request" }),
json: vi.fn().mockResolvedValue({ errcode: 40013, errmsg: 'bad request' }),
headers: { get: () => 'application/json' },
});
await expect(
@@ -179,13 +293,13 @@ describe("dispatchOutboxEvent", () => {
prisma: {
notificationChannel: {
findUnique: vi.fn().mockResolvedValue({
id: "channel-3",
channel_type: "wecom",
name: "wecom-4xx",
id: 'channel-3',
channel_type: 'wecom',
name: 'wecom-4xx',
enabled: true,
config_json: {
mode: "wecom_webhook",
webhookUrl: "https://example.com/wecom",
mode: 'wecom_webhook',
webhookUrl: 'https://example.com/wecom',
timeoutMs: 500,
routing: {},
},
@@ -196,26 +310,27 @@ describe("dispatchOutboxEvent", () => {
config: {
imNotifierEnabled: true,
},
eventType: "notification.im",
eventType: 'notification.im',
payload: {
channelId: "channel-3",
channelType: "wecom",
title: "test",
body: "body",
channelId: 'channel-3',
channelType: 'wecom',
title: 'test',
body: 'body',
},
}),
).rejects.toMatchObject({
name: "IntegrationDispatchError",
code: "wecom_http_4xx",
name: 'IntegrationDispatchError',
code: 'wecom_http_4xx',
retryable: false,
});
});
it("maps wecom 5xx as retryable IM dispatch error", async () => {
it('maps wecom 5xx as retryable IM dispatch error', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 503,
json: vi.fn().mockResolvedValue({ errcode: 500, errmsg: "server error" }),
json: vi.fn().mockResolvedValue({ errcode: 500, errmsg: 'server error' }),
headers: { get: () => 'application/json' },
});
await expect(
@@ -223,13 +338,13 @@ describe("dispatchOutboxEvent", () => {
prisma: {
notificationChannel: {
findUnique: vi.fn().mockResolvedValue({
id: "channel-4",
channel_type: "wecom",
name: "wecom-5xx",
id: 'channel-4',
channel_type: 'wecom',
name: 'wecom-5xx',
enabled: true,
config_json: {
mode: "wecom_webhook",
webhookUrl: "https://example.com/wecom",
mode: 'wecom_webhook',
webhookUrl: 'https://example.com/wecom',
timeoutMs: 500,
routing: {},
},
@@ -240,36 +355,36 @@ describe("dispatchOutboxEvent", () => {
config: {
imNotifierEnabled: true,
},
eventType: "notification.im",
eventType: 'notification.im',
payload: {
channelId: "channel-4",
channelType: "wecom",
title: "test",
body: "body",
channelId: 'channel-4',
channelType: 'wecom',
title: 'test',
body: 'body',
},
}),
).rejects.toMatchObject({
name: "IntegrationDispatchError",
code: "wecom_http_5xx",
name: 'IntegrationDispatchError',
code: 'wecom_http_5xx',
retryable: true,
});
});
it("maps wecom timeout as retryable IM dispatch error", async () => {
global.fetch = vi.fn().mockRejectedValue({ name: "AbortError" });
it('maps wecom timeout as retryable IM dispatch error', async () => {
global.fetch = vi.fn().mockRejectedValue({ name: 'AbortError' });
await expect(
dispatchOutboxEvent({
prisma: {
notificationChannel: {
findUnique: vi.fn().mockResolvedValue({
id: "channel-5",
channel_type: "wecom",
name: "wecom-timeout",
id: 'channel-5',
channel_type: 'wecom',
name: 'wecom-timeout',
enabled: true,
config_json: {
mode: "wecom_webhook",
webhookUrl: "https://example.com/wecom",
mode: 'wecom_webhook',
webhookUrl: 'https://example.com/wecom',
timeoutMs: 500,
routing: {},
},
@@ -280,46 +395,27 @@ describe("dispatchOutboxEvent", () => {
config: {
imNotifierEnabled: true,
},
eventType: "notification.im",
eventType: 'notification.im',
payload: {
channelId: "channel-5",
channelType: "wecom",
title: "test",
body: "body",
channelId: 'channel-5',
channelType: 'wecom',
title: 'test',
body: 'body',
},
}),
).rejects.toMatchObject({
name: "IntegrationDispatchError",
code: "wecom_timeout",
name: 'IntegrationDispatchError',
code: 'wecom_timeout',
retryable: true,
});
});
it("throws non-retryable error for unsupported event", async () => {
it('throws error for unsupported event', async () => {
await expect(
dispatchOutboxEvent({
config: { erpSyncEnabled: true, erpSyncProvider: "mock" },
eventType: "unsupported.event",
payload: {},
config: {},
eventType: 'unknown.event',
}),
).rejects.toMatchObject({
name: "IntegrationDispatchError",
code: "unsupported_outbox_event",
retryable: false,
});
});
it("preserves error class semantics", () => {
const error = new IntegrationDispatchError({
code: "unit_test",
message: "unit test",
retryable: true,
statusCode: 503,
});
expect(error).toBeInstanceOf(Error);
expect(error.code).toBe("unit_test");
expect(error.retryable).toBe(true);
expect(error.statusCode).toBe(503);
).rejects.toThrow('unsupported_outbox_event:unknown.event');
});
});
@@ -0,0 +1,59 @@
const integrationsRoutes = require('../../../src/routes/integrations');
describe('Integrations procurement ERP route helpers', () => {
const {
canReadPurchaseRequest,
ensureProcurementTargetEligible,
normalizeProcurementTargets,
} = integrationsRoutes.__testables;
it('normalizes procurement targets in fixed order', () => {
expect(
normalizeProcurementTargets({
targets: ['archive_summary', 'commitment_journal', 'archive_summary'],
}),
).toEqual(['commitment_journal', 'archive_summary']);
});
it('respects purchase read permission rules', () => {
const purchaseRequest = {
applicant_id: 'employee-1',
submitter_id: 'employee-2',
};
expect(
canReadPurchaseRequest(
{ employee: { id: 'employee-1', permissionCodes: ['procurement.view_own'] } },
purchaseRequest,
),
).toBe(true);
expect(
canReadPurchaseRequest(
{ employee: { id: 'other', permissionCodes: ['procurement.view_own'] } },
purchaseRequest,
),
).toBe(false);
expect(
canReadPurchaseRequest(
{ employee: { id: 'other', permissionCodes: ['integration.manage', 'procurement.view_all'] } },
purchaseRequest,
),
).toBe(true);
});
it('rejects commitment target when purchase is not approved', () => {
expect(() =>
ensureProcurementTargetEligible('commitment_journal', {
purchaseRequest: { status: 'reviewing' },
}),
).toThrow('参数校验失败');
});
it('rejects archive targets when archive is missing', () => {
expect(() =>
ensureProcurementTargetEligible('accrual_journal', {
purchaseRequest: { status: 'approved', order_archive: null },
}),
).toThrow('参数校验失败');
});
});
@@ -0,0 +1,130 @@
const purchaseRequestRoutes = require('../../../src/routes/purchaseRequests');
describe('purchase archive ERP helper', () => {
const { handlePurchaseArchiveErpSync } = purchaseRequestRoutes.__testables;
function createRequest() {
return {
id: 'req-1',
ip: '127.0.0.1',
headers: {},
employee: {
id: 'actor-1',
department_id: 'dept-1',
permissionCodes: ['procurement.manage'],
},
};
}
function createTx() {
return {
auditLog: {
create: vi.fn().mockResolvedValue({ id: 'audit-1' }),
},
};
}
function createContext() {
return {
purchaseRequest: {
id: 'pr-1',
department_id: 'dept-1',
order_archive: {
id: 'archive-1',
po_no: 'PO-001',
contract_no: 'CT-001',
archived_at: new Date('2026-03-08T10:30:00.000Z'),
},
},
};
}
it('first archive enqueues accrual and summary', async () => {
const tx = createTx();
const loadContext = vi.fn().mockResolvedValue(createContext());
const evaluateGate = vi.fn().mockResolvedValue({
enabled: true,
reason: 'env_inherit_department_allowed',
});
const enqueueAccrual = vi.fn().mockResolvedValue({
id: 'outbox-accrual',
status: 'pending',
duplicated: false,
requeued: false,
eventType: 'erp.journal.export',
erpTarget: 'accrual_journal',
});
const enqueueSummary = vi.fn().mockResolvedValue({
id: 'outbox-summary',
status: 'pending',
duplicated: false,
requeued: false,
eventType: 'erp.procurement.export',
erpTarget: 'archive_summary',
});
const result = await handlePurchaseArchiveErpSync({
tx,
config: {},
request: createRequest(),
actorId: 'actor-1',
purchaseRequestId: 'pr-1',
archiveId: 'archive-1',
isFirstArchive: true,
loadContext,
evaluateGate,
enqueueAccrual,
enqueueSummary,
});
expect(enqueueAccrual).toHaveBeenCalledWith(
tx,
{},
expect.objectContaining({ requeueOnFailure: false }),
);
expect(enqueueSummary).toHaveBeenCalledWith(
tx,
{},
expect.objectContaining({ requeueOnFailure: false }),
);
expect(result.items).toHaveLength(2);
expect(tx.auditLog.create).toHaveBeenCalledTimes(2);
});
it('archive update only re-enqueues summary', async () => {
const tx = createTx();
const loadContext = vi.fn().mockResolvedValue(createContext());
const evaluateGate = vi.fn().mockResolvedValue({
enabled: true,
reason: 'env_inherit_department_allowed',
});
const enqueueAccrual = vi.fn();
const enqueueSummary = vi.fn().mockResolvedValue({
id: 'outbox-summary',
status: 'pending',
duplicated: false,
requeued: true,
eventType: 'erp.procurement.export',
erpTarget: 'archive_summary',
});
const result = await handlePurchaseArchiveErpSync({
tx,
config: {},
request: createRequest(),
actorId: 'actor-1',
purchaseRequestId: 'pr-1',
archiveId: 'archive-1',
isFirstArchive: false,
loadContext,
evaluateGate,
enqueueAccrual,
enqueueSummary,
});
expect(enqueueAccrual).not.toHaveBeenCalled();
expect(enqueueSummary).toHaveBeenCalled();
expect(result.items).toHaveLength(1);
expect(result.items[0].erpTarget).toBe('archive_summary');
});
});
@@ -0,0 +1,114 @@
const workflowRoutes = require('../../../src/routes/workflow');
describe('workflow purchase ERP helper', () => {
const { handlePurchaseApprovalErpSync } = workflowRoutes.__testables;
function createRequest() {
return {
id: 'req-1',
ip: '127.0.0.1',
headers: {},
employee: {
id: 'actor-1',
department_id: 'dept-1',
permissionCodes: ['procurement.manage'],
},
};
}
function createTx() {
return {
auditLog: {
create: vi.fn().mockResolvedValue({ id: 'audit-1' }),
},
};
}
it('auto enqueues commitment journal when gate is enabled', async () => {
const tx = createTx();
const loadContext = vi.fn().mockResolvedValue({
purchaseRequest: {
id: 'pr-1',
department_id: 'dept-1',
},
approvalOccurredAt: new Date('2026-03-08T10:00:00.000Z'),
});
const evaluateGate = vi.fn().mockResolvedValue({
enabled: true,
reason: 'env_inherit_department_allowed',
});
const enqueueCommitment = vi.fn().mockResolvedValue({
id: 'outbox-1',
status: 'pending',
duplicated: false,
requeued: false,
eventType: 'erp.journal.export',
});
const result = await handlePurchaseApprovalErpSync({
tx,
config: {},
request: createRequest(),
actorId: 'actor-1',
purchaseRequestId: 'pr-1',
loadContext,
evaluateGate,
enqueueCommitment,
});
expect(enqueueCommitment).toHaveBeenCalledWith(
tx,
{},
expect.objectContaining({
actorId: 'actor-1',
requeueOnFailure: false,
}),
);
expect(tx.auditLog.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: 'ERP_SYNC_ENQUEUED',
target_type: 'purchase_request',
target_id: 'pr-1',
}),
}),
);
expect(result.skipped).toBe(false);
});
it('writes skip audit when approval gate is disabled', async () => {
const tx = createTx();
const loadContext = vi.fn().mockResolvedValue({
purchaseRequest: {
id: 'pr-1',
department_id: 'dept-1',
},
approvalOccurredAt: new Date('2026-03-08T10:00:00.000Z'),
});
const evaluateGate = vi.fn().mockResolvedValue({ enabled: false, reason: 'flag_force_off' });
const enqueueCommitment = vi.fn();
const result = await handlePurchaseApprovalErpSync({
tx,
config: {},
request: createRequest(),
actorId: 'actor-1',
purchaseRequestId: 'pr-1',
loadContext,
evaluateGate,
enqueueCommitment,
});
expect(enqueueCommitment).not.toHaveBeenCalled();
expect(tx.auditLog.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: 'ERP_SYNC_SKIPPED_BY_FEATURE_FLAG',
target_type: 'purchase_request',
target_id: 'pr-1',
}),
}),
);
expect(result.skipped).toBe(true);
});
});
@@ -72,7 +72,7 @@ describe('ERP Journal Service', () => {
dedupe_key: 'reimbursement:rb-1:paid',
},
},
select: { id: true, status: true },
select: { id: true, status: true, payload: true },
});
expect(prisma.integrationOutbox.create).toHaveBeenCalled();
expect(result.eventType).toBe('erp.journal.export');
@@ -0,0 +1,144 @@
const {
buildPurchaseAccrualJournalPayload,
buildPurchaseArchiveSummaryPayload,
buildPurchaseCommitmentJournalPayload,
enqueuePurchaseArchiveSummaryExport,
hashProcurementPayload,
} = require('../../../src/services/integrations/erpProcurement');
describe('ERP Procurement Service', () => {
it('builds commitment payload with procurement dimensions', () => {
const payload = buildPurchaseCommitmentJournalPayload({
purchaseRequest: {
id: 'pr-1',
request_no: 'PR-001',
applicant_id: 'applicant-1',
submitter_id: 'submitter-1',
department_id: 'dept-1',
total_amount: { toString: () => '880.00' },
currency_code: 'CNY',
legal_entity: { code: 'HY' },
cost_center: { code: 'IT001' },
supplier: { code: 'SUP001' },
budget_pool: { code: 'BG-IT-2026' },
document_category: { code: 'PR_STANDARD' },
},
occurredAt: '2026-03-08T10:00:00.000Z',
});
expect(payload.journalType).toBe('purchase_request_commitment');
expect(payload.references.requestNo).toBe('PR-001');
expect(payload.dimensions.legalEntityCode).toBe('HY');
expect(payload.dimensions.costCenterCode).toBe('IT001');
expect(payload.dimensions.supplierCode).toBe('SUP001');
expect(payload.dimensions.budgetPoolCode).toBe('BG-IT-2026');
});
it('builds accrual payload from archive facts', () => {
const payload = buildPurchaseAccrualJournalPayload({
purchaseRequest: {
id: 'pr-1',
request_no: 'PR-001',
applicant_id: 'applicant-1',
submitter_id: 'submitter-1',
department_id: 'dept-1',
total_amount: '880.00',
currency_code: 'CNY',
legal_entity: { code: 'HY' },
cost_center: { code: 'IT001' },
supplier: { code: 'SUP001' },
budget_pool: { code: 'BG-IT-2026' },
},
archive: {
id: 'archive-1',
po_no: 'PO-001',
contract_no: 'CT-001',
archived_at: '2026-03-08T10:30:00.000Z',
},
});
expect(payload.journalType).toBe('purchase_order_accrual');
expect(payload.entityId).toBe('archive-1');
expect(payload.documentNo).toBe('PO-001');
expect(payload.references.contractNo).toBe('CT-001');
});
it('builds archive summary payload and hashes payload changes', () => {
const basePayload = buildPurchaseArchiveSummaryPayload({
purchaseRequest: {
id: 'pr-1',
request_no: 'PR-001',
department_id: 'dept-1',
total_amount: '880.00',
currency_code: 'CNY',
legal_entity: { code: 'HY' },
cost_center: { code: 'IT001' },
supplier: { id: 'sup-1', code: 'SUP001', name: '演示供应商' },
},
archive: {
id: 'archive-1',
po_no: 'PO-001',
contract_no: 'CT-001',
archived_at: '2026-03-08T10:30:00.000Z',
archived_files: [
{
storagePath: 'purchase-requests/pr-1/contract.pdf',
originalName: 'contract.pdf',
mimeType: 'application/pdf',
fileSize: 1024,
},
],
},
});
const changedPayload = {
...basePayload,
contractNo: 'CT-002',
};
expect(basePayload.files).toHaveLength(1);
expect(hashProcurementPayload(basePayload)).not.toBe(hashProcurementPayload(changedPayload));
});
it('resets archive summary outbox when payload changes', async () => {
const prisma = {
integrationOutbox: {
findUnique: vi.fn().mockResolvedValue({
id: 'outbox-1',
status: 'succeeded',
payload: { contractNo: 'CT-001', poNo: 'PO-001' },
}),
update: vi.fn().mockResolvedValue({ id: 'outbox-1', status: 'pending' }),
},
};
const result = await enqueuePurchaseArchiveSummaryExport(
prisma,
{ integrationOutboxMaxAttempts: 5 },
{
actorId: 'actor-1',
purchaseRequest: {
id: 'pr-1',
request_no: 'PR-001',
department_id: 'dept-1',
total_amount: '880.00',
currency_code: 'CNY',
supplier: { id: 'sup-1', code: 'SUP001', name: '演示供应商' },
legal_entity: { code: 'HY' },
cost_center: { code: 'IT001' },
},
archive: {
id: 'archive-1',
po_no: 'PO-001',
contract_no: 'CT-002',
archived_at: '2026-03-08T10:30:00.000Z',
archived_files: [],
},
},
);
expect(prisma.integrationOutbox.update).toHaveBeenCalled();
expect(result.requeued).toBe(true);
expect(result.eventType).toBe('erp.procurement.export');
});
});
@@ -33,11 +33,22 @@ describe('ERP Sync Services', () => {
it('returns mock synced when journal export provider is mock', async () => {
const result = await erp.exportJournalToErp(
{ erpSyncEnabled: true, erpSyncProvider: 'mock' },
{ documentNo: 'BX-001' },
{ journalType: 'purchase_request_commitment', documentNo: 'PR-001' },
);
expect(result.ok).toBe(true);
expect(result.code).toBe('mock_synced');
expect(result.response.externalId).toContain('BX-001');
expect(result.response.externalId).toContain('PR-001');
});
it('returns mock procurement result when provider is mock', async () => {
const result = await erp.exportProcurementToErp(
{ erpSyncEnabled: true, erpSyncProvider: 'mock' },
{ poNo: 'PO-001', contractNo: 'CT-001' },
);
expect(result.ok).toBe(true);
expect(result.code).toBe('mock_synced');
expect(result.response.externalPoNo).toContain('PO-001');
expect(result.response.externalContractNo).toContain('CT-001');
});
it('returns mock master data result when provider is mock', async () => {
@@ -74,6 +85,70 @@ describe('ERP Sync Services', () => {
expect(result.retryable).toBe(false);
});
it('handles http journal export 5xx errors', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 503,
headers: { get: () => 'application/json' },
json: vi.fn().mockResolvedValue({ code: 'service_unavailable' }),
});
const result = await erp.exportJournalToErp(
{
erpSyncEnabled: true,
erpSyncProvider: 'http',
erpJournalExportEndpoint: 'https://example.com/journals',
erpSyncTimeoutMs: 500,
},
{ journalType: 'purchase_order_accrual', documentNo: 'PO-001' },
);
expect(result.ok).toBe(false);
expect(result.code).toBe('erp_sync_http_5xx');
expect(result.retryable).toBe(true);
});
it('handles http procurement export 4xx errors', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
headers: { get: () => 'application/json' },
json: vi.fn().mockResolvedValue({ code: 'bad_request' }),
});
const result = await erp.exportProcurementToErp(
{
erpSyncEnabled: true,
erpSyncProvider: 'http',
erpProcurementExportEndpoint: 'https://example.com/procurement',
erpProcurementTimeoutMs: 500,
},
{ exportType: 'purchase_order_archive', poNo: 'PO-001' },
);
expect(result.ok).toBe(false);
expect(result.code).toBe('erp_procurement_http_4xx');
expect(result.retryable).toBe(false);
});
it('handles http procurement export timeout', async () => {
global.fetch = vi.fn().mockRejectedValue({ name: 'AbortError' });
const result = await erp.exportProcurementToErp(
{
erpSyncEnabled: true,
erpSyncProvider: 'http',
erpProcurementExportEndpoint: 'https://example.com/procurement',
erpProcurementTimeoutMs: 500,
},
{ exportType: 'purchase_order_archive', poNo: 'PO-001' },
);
expect(result.ok).toBe(false);
expect(result.code).toBe('erp_procurement_timeout');
expect(result.retryable).toBe(true);
});
it('handles http journal export timeout', async () => {
global.fetch = vi.fn().mockRejectedValue({ name: 'AbortError' });