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

这个提交包含在:
2026-02-10 11:25:18 +08:00
父节点 1b6e801b12
当前提交 bec21e1b38
共修改 15 个文件,包含 1718 行新增和 793 行删除
+4
查看文件
@@ -4,6 +4,10 @@
**日期**:2026-02-09
**目的**:描述系统当前实现(P5/F25 完备态)并为未来演进提供参考。
**相关文档**:
- [需求规格说明书](./requirements-specification.md)
- [实现状态矩阵(P5-P10)](./feature-matrix.md)
---
## 1. 部署视图 (As-Is)
+95
查看文件
@@ -0,0 +1,95 @@
# hyb-oa 实现状态矩阵(P5-P10)
**快照日期**:2026-02-10
**范围**:`F1-F42`(含 `F19b/F19c/F19d`)+ `R1-S2` + `P9A1-P9D1` + `P10E1-P10G1`,共 80 项。
**事实源**:`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/*.csv` 的执行合同职责。
- `首次规划 CSV` 为该 ID 首次出现的执行合同;`首次完成 CSV` 为三状态首次全 `DONE` 的执行合同。
- `规格书章节` 优先引用 `docs/requirements-specification.md`;规格未显式覆盖时标注 `N/A`。
| ID | 功能项 | 规格书章节 | 首次规划 CSV | 首次完成 CSV | 完成日期 | 当前状态 | 回归覆盖 | Notes |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| F1 | CSV快照收口(P5蓝图v2) | §16 迭代计划(执行合同收口) | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09 | DONE | manual | none |
| F2 | 费用类型只读API(expense-types) | §9.1-§9.2,§13.2/§13.3 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F3 | 费用类型管理API(system.settings) | §9.1-§9.2,§13.2/§13.3 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F4 | 报销单编辑与删除(补齐CRUD) | §4.2,§13.2 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-workflow-actions.sh | none |
| F5 | 报销明细CRUD与总金额重算 | §4.2,§13.2 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-workflow-actions.sh | none |
| F6 | 前端报销编辑器(明细+费用类型) | §4.2,§13.2 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | client:typecheck/build/test:e2e | none |
| F7 | 代提交(expense.proxy_submit) | §4.2.3-§4.2.4,§13.5 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-workflow-actions.sh | none |
| F8 | 行政代上传(owner≠uploaded_by) | §4.2.3-§4.2.4,§10.7 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-ocr.sh + regression-audit.sh | none |
| F9 | 票据解绑/重绑(bound->available) | §4.4,§10.4-§10.7 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-workflow-actions.sh | none |
| F10 | 判重例外(override duplicate) | §4.4,§10.7,§12.4 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-dedup.sh + regression-audit.sh | none |
| F11 | OCR失败重试API(次数/频控) | §4.4,§10.7 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-ocr.sh + regression-audit.sh | none |
| F12 | 90天未绑定自动归档(unused_timeout) | §4.4,§10.4-§10.7 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-ocr.sh | none |
| F13 | signed-url审计与下载行为记录 | §10.2,§10.7,§12.4 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-audit.sh | none |
| F14 | 站内通知基础设施(DB+API) | §4.6 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F15 | 邮件通知(SMTP/Nodemailer) | §4.6 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F16 | 前端通知入口(Bell) | §4.6 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | client:test:e2e | none |
| F17 | 报表导出(CSV/Excel) | §16 Phase 2(报表导出) | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F18 | 审批规则维护(system.settings) | §6,§13.3 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-workflow-actions.sh | none |
| F19 | 作业系统升级(pg-boss 基础设施) | §16 Phase 2(队列/作业) | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-all.sh | none |
| F19b | 作业迁移(OCR -> pg-boss) | §16 Phase 2(OCR队列化) | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-ocr.sh + regression-all.sh | none |
| F19c | 作业迁移(委派回收 -> pg-boss) | §16 Phase 2(委派回收队列化) | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-workflow-actions.sh | none |
| F19d | 作业迁移(超期归档 -> pg-boss) | §16 Phase 2(归档作业队列化) | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-ocr.sh + regression-all.sh | none |
| F20 | Worker进程拆分(可选) | §14(部署),§16 Phase 2 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F21 | 对象存储(MinIO/S3兼容) | §10.3,§16 Phase 2 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F22 | 可观测性增强(metrics/日志) | §14 非功能需求(可观测性) | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F23 | SSO/OIDC(可选,P7+) | §11.1(登录扩展),§16 Phase 2 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | 规格扩展项(P6+/P7+) |
| F24 | 工作流扩展到其他实体(P7+) | §5,§16 Phase 2 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | 规格扩展项(P6+/P7+) |
| F25 | 敏感字段加密与脱敏(P6+) | §12.1-§12.3 | 2026-02-09_11-17-07-p5-blueprint.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | 规格扩展项(P6+/P7+) |
| F26 | 部门API(departments) | §3.2,§4.1,§13.2 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F27 | 员工API对齐(新增别名 /api/employees) | §4.1,§13.2 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F28 | 票据人工修正与手工归档(invoice-pool patch/archive) | §4.4,§10.4-§10.7 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-audit.sh | none |
| F29 | 配置只读API(approval-rules/document-sequences) | §6,§8,§13.3 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F30 | 通知触发集成(workflow/pay/auth) | §4.6,§12.4 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F31 | Delegation Grants API对齐(新增别名/增强响应) | §4.2.4,§13.5 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F32 | 前端组织与员工最小运营 | §3.2,§4.1(前端运营) | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | client:typecheck/build | none |
| F33 | 前端行政代提交/代上传入口 | §4.2.3-§4.2.4 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | client:typecheck/build/test:e2e | none |
| F34 | 前端票据中心增强(编辑/归档/解绑/重试/例外) | §4.4,§10.7(前端增强) | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | client:typecheck/build/test:e2e | none |
| F35 | 前端错误码文案补齐(VALID/AUTH/PERM) | §13.6 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | client:typecheck/build | none |
| F36 | 首次登录强制改密(后端) | §11.2-§11.5,§13.6 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F37 | 登录失败锁定与解锁(AUTH_002) | §11.2-§11.5,§13.6 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F38 | 首次登录改密与锁定提示(前端) | §11.2-§11.5,§13.6(前端) | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | client:typecheck/build/test:e2e | none |
| F39 | 弱密码库拦截(Top 10k) | §11.2,§13.6 | 2026-02-09_12-34-42-p5-blueprint-v2.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | none |
| F40 | 组织/配置回归脚本(org+settings) | §16(回归工程化) | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-org-settings.sh | 治理/回归工程项 |
| F41 | 认证安全回归脚本(auth security) | §11,§16(认证回归) | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | server/scripts/regression-auth-security.sh | 治理/回归工程项 |
| F42 | 架构文档修订(As-Is/To-Be) | N/A(架构文档治理) | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09_13-39-02-p5-blueprint-v3.csv | 2026-02-09 | DONE | manual | 治理/回归工程项 |
| R1 | 历史TODO清账映射(A/C -> E/F) | N/A(治理项) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | manual | none |
| R2 | 规格与计划文档状态同步 | §16(执行合同与文档对齐) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | manual | none |
| R3 | 状态一致性自动校验与CI接入 | §16(门禁与漂移阻断) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | scripts/check-minimal.sh | none |
| V1 | 验真域模型与Provider抽象 | §4.4(发票治理扩展) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-verification.sh | none |
| V2 | 验真API与异步任务(pg-boss) | §4.4,§16(作业体系) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-verification.sh | none |
| V3 | 票据中心验真前端闭环 | §4.4(票据中心前端) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | client:typecheck/build | none |
| V4 | 验真回归脚本与总回归接入 | §16(回归工程化) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-verification.sh + regression-all.sh | none |
| D1 | 看板聚合API | §16 Phase 2(可视化看板) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-dashboard.sh | none |
| D2 | 前端Dashboard强化 | §16 Phase 2(可视化看板) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | client:typecheck/build | none |
| D3 | 看板导出联动 | §16 Phase 2(报表导出联动) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-dashboard.sh | none |
| B1 | 预算池与台账模型 | §16 Phase 2(预算管控) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-budget.sh | none |
| B2 | 预算API与提交流程拦截 | §16 Phase 2(预算管控) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-budget.sh | none |
| B3 | 预算前端运营页 | §16 Phase 2(预算运营) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | client:typecheck/build | none |
| B4 | 预算回归脚本 | §16(回归工程化) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-budget.sh | none |
| I1 | 集成框架(Outbox+Adapter) | §16 Phase 2(外部集成) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-integrations.sh | none |
| I2 | ERP最小集成(paid同步) | §16 Phase 2(ERP 集成) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-integrations.sh | 默认关闭,按需灰度 |
| I3 | 差旅单导入与报销关联 | §16 Phase 2(差旅闭环) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-integrations.sh | 默认关闭,按需灰度 |
| I4 | 通知渠道扩展(企微/钉钉) | §4.6(多渠道通知) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | server/scripts/regression-integrations.sh | 默认关闭,按需灰度 |
| S1 | 企业卡/虚拟卡管控预研 | N/A(ADR 决策项) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | manual | docs/adr/adr-enterprise-card-control.md |
| S2 | 移动端路线决策预研 | N/A(ADR 决策项) | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09_23-30-00-p6-p8-remaining-work-master.csv | 2026-02-09 | DONE | manual | docs/adr/adr-mobile-strategy.md |
| P9A1 | invoicePool拆分方案设计与边界冻结 | §16(维护性治理) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | manual | none |
| P9A2 | invoicePool验真路由独立化实施 | §16(维护性治理) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | server/scripts/regression-verification.sh | none |
| P9A3 | invoicePool共享select与响应映射收敛 | §16(维护性治理) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | server/scripts/regression-workflow-actions.sh + regression-verification.sh | none |
| P9B1 | Dashboard趋势改为SQL聚合 | §16(看板性能) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | server/scripts/regression-dashboard.sh | none |
| P9B2 | Dashboard聚合性能回归脚本补强 | §16(回归工程化) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | server/scripts/regression-dashboard.sh + regression-all.sh | none |
| P9C1 | feature-matrix纳入P6-P8能力 | §16(状态治理) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | manual | none |
| P9C2 | 矩阵一致性校验脚本扩展 | §16(门禁与漂移阻断) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | scripts/check-minimal.sh | none |
| P9D1 | P9整体验收与回归基线 | §16(回归基线) | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv | 2026-02-10 | DONE | scripts/check-minimal.sh + server/scripts/regression-all.sh | none |
| P10E1 | ERP适配器配置模型收口 | §16(外部集成硬化) | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10 | DONE | server/src/config.js 静态检查 | none |
| P10E2 | ERP真实HTTP适配器实现 | §16(ERP 同步硬化) | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10 | DONE | server/scripts/regression-integrations.sh | 4xx dead_letter / 5xx+timeout retry |
| P10E3 | Outbox失败分类与重试语义强化 | §16(Outbox 可靠性) | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10 | DONE | server/scripts/regression-integrations.sh | none |
| P10E4 | 集成回归脚本引入本地Mock ERP | §16(回归工程化) | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10 | DONE | server/scripts/regression-integrations.sh | 脚本内嵌 Node mock server |
| P10M1 | invoicePool二阶段拆分(读路径) | §16(维护性治理) | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10 | DONE | node --check invoicePool 主/子模块 | none |
| P10M2 | invoicePool二阶段拆分回归与基线更新 | §16(回归与文档) | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10 | DONE | server/scripts/regression-verification.sh + regression-workflow-actions.sh | none |
| P10G1 | 矩阵与执行合同同步到P10 | §16(状态治理) | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10_10-35-30-p10-production-hardening.csv | 2026-02-10 | DONE | scripts/check-minimal.sh | 覆盖 P5-P10 全量 |
@@ -0,0 +1,8 @@
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
P10E1,ERP适配器配置模型收口,补齐ERP真实对接所需配置项(endpoint/auth/timeout/retry)并保持默认关闭,配置项命名一致且默认不影响现有mock行为,cd server && node --check src/config.js && node --check src/services/integrations/erp.js,manual,DONE,DONE,DONE,server/src/config.js | server/.env.example | server/src/services/integrations/erp.js,[],回滚=保持ERP_SYNC_ENABLED=false
P10E2,ERP真实HTTP适配器实现,在现有erp adapter中新增HTTP调用分支并保留mock分支作为降级路径,ERP enabled时可向mock ERP服务发送请求并拿到可解析响应,manual: 启动本地mock ERP服务后调用 /api/integrations/erp/sync/:id?runNow=1 验证成功与失败路径,manual,DONE,DONE,DONE,server/src/services/integrations/erp.js | server/src/services/integrations/dispatcher.js,"[""P10E1""]",不引入重型依赖优先复用Node内置fetch
P10E3,Outbox失败分类与重试语义强化,区分可重试错误与不可重试错误并准确写入failed/dead_letter状态,重试/死信行为可预测且审计信息可定位,cd server && node --check src/services/integrations/outbox.js && node --check src/jobs/integrationOutboxJob.js,manual,DONE,DONE,DONE,server/src/services/integrations/outbox.js | server/src/jobs/integrationOutboxJob.js | server/src/services/integrations/dispatcher.js,"[""P10E2""]",保持历史outbox记录不回写覆盖
P10E4,集成回归脚本引入本地Mock ERP,增强regression-integrations脚本覆盖真实HTTP适配器(成功+超时+错误码),CI/本地可在无外部凭据条件下稳定回归ERP链路,cd server && ./scripts/regression-integrations.sh,manual,DONE,DONE,DONE,server/scripts/regression-integrations.sh | server/src/scripts/*.js,"[""P10E3""]",默认仍不依赖真实外部ERP
P10M1,invoicePool二阶段拆分(读路径),继续将invoicePool读路径(list/detail/file/signed-url)拆分为子模块并维持主入口兼容,主文件体量继续下降且接口行为无变化,cd server && node --check src/routes/invoicePool.js && node --check src/routes/invoicePool/*.js,manual,DONE,DONE,DONE,server/src/routes/invoicePool.js | server/src/routes/invoicePool/*.js | server/src/routes/invoicePool/shared/*.js,[],延续P9拆分策略不改路径
P10M2,invoicePool二阶段拆分回归与基线更新,补充拆分后的定向回归并更新README中的拆分维护说明,拆分后验证与文档一致且可回滚,cd server && ./scripts/regression-verification.sh && ./scripts/regression-workflow-actions.sh,manual,DONE,DONE,DONE,server/README.md | server/scripts/regression-verification.sh | server/scripts/regression-workflow-actions.sh,"[""P10M1""]",回滚=恢复子模块注册到主文件内联
P10G1,矩阵与执行合同同步到P10,在feature-matrix新增P10项并扩展校验脚本事实源列表,矩阵可展示P5-P10全局能力且check-minimal可阻断漂移,cd /home/shunli/Projects/hyb-oa && ./scripts/check-minimal.sh,manual,DONE,DONE,DONE,docs/feature-matrix.md | scripts/validate-feature-matrix.py | scripts/check-minimal.sh,"[""P10E4"",""P10M2""]",保持历史CSV快照只读
1 ID Title Description Acceptance Test_Method Tools Dev_Status Review1_Status Regression_Status Files Dependencies Notes
2 P10E1 ERP适配器配置模型收口 补齐ERP真实对接所需配置项(endpoint/auth/timeout/retry)并保持默认关闭 配置项命名一致且默认不影响现有mock行为 cd server && node --check src/config.js && node --check src/services/integrations/erp.js manual DONE DONE DONE server/src/config.js | server/.env.example | server/src/services/integrations/erp.js [] 回滚=保持ERP_SYNC_ENABLED=false
3 P10E2 ERP真实HTTP适配器实现 在现有erp adapter中新增HTTP调用分支并保留mock分支作为降级路径 ERP enabled时可向mock ERP服务发送请求并拿到可解析响应 manual: 启动本地mock ERP服务后调用 /api/integrations/erp/sync/:id?runNow=1 验证成功与失败路径 manual DONE DONE DONE server/src/services/integrations/erp.js | server/src/services/integrations/dispatcher.js ["P10E1"] 不引入重型依赖优先复用Node内置fetch
4 P10E3 Outbox失败分类与重试语义强化 区分可重试错误与不可重试错误并准确写入failed/dead_letter状态 重试/死信行为可预测且审计信息可定位 cd server && node --check src/services/integrations/outbox.js && node --check src/jobs/integrationOutboxJob.js manual DONE DONE DONE server/src/services/integrations/outbox.js | server/src/jobs/integrationOutboxJob.js | server/src/services/integrations/dispatcher.js ["P10E2"] 保持历史outbox记录不回写覆盖
5 P10E4 集成回归脚本引入本地Mock ERP 增强regression-integrations脚本覆盖真实HTTP适配器(成功+超时+错误码) CI/本地可在无外部凭据条件下稳定回归ERP链路 cd server && ./scripts/regression-integrations.sh manual DONE DONE DONE server/scripts/regression-integrations.sh | server/src/scripts/*.js ["P10E3"] 默认仍不依赖真实外部ERP
6 P10M1 invoicePool二阶段拆分(读路径) 继续将invoicePool读路径(list/detail/file/signed-url)拆分为子模块并维持主入口兼容 主文件体量继续下降且接口行为无变化 cd server && node --check src/routes/invoicePool.js && node --check src/routes/invoicePool/*.js manual DONE DONE DONE server/src/routes/invoicePool.js | server/src/routes/invoicePool/*.js | server/src/routes/invoicePool/shared/*.js [] 延续P9拆分策略不改路径
7 P10M2 invoicePool二阶段拆分回归与基线更新 补充拆分后的定向回归并更新README中的拆分维护说明 拆分后验证与文档一致且可回滚 cd server && ./scripts/regression-verification.sh && ./scripts/regression-workflow-actions.sh manual DONE DONE DONE server/README.md | server/scripts/regression-verification.sh | server/scripts/regression-workflow-actions.sh ["P10M1"] 回滚=恢复子模块注册到主文件内联
8 P10G1 矩阵与执行合同同步到P10 在feature-matrix新增P10项并扩展校验脚本事实源列表 矩阵可展示P5-P10全局能力且check-minimal可阻断漂移 cd /home/shunli/Projects/hyb-oa && ./scripts/check-minimal.sh manual DONE DONE DONE docs/feature-matrix.md | scripts/validate-feature-matrix.py | scripts/check-minimal.sh ["P10E4","P10M2"] 保持历史CSV快照只读
+36 -3
查看文件
@@ -3,40 +3,73 @@ set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
echo "=== [1/3] Server Prisma Validate ==="
echo "=== [1/4] Server Prisma Validate ==="
(
cd "$ROOT_DIR/server"
npm run prisma:validate
)
echo ""
echo "=== [2/3] Server Static Checks ==="
echo "=== [2/4] Server Static Checks ==="
(
cd "$ROOT_DIR/server"
node --check src/routes/reimbursements.js
node --check src/routes/workflow.js
node --check src/routes/delegations.js
node --check src/routes/invoicePool.js
node --check src/routes/invoicePool/verification.js
node --check src/routes/invoicePool/read.js
node --check src/routes/invoicePool/shared/selects.js
node --check src/routes/invoicePool/shared/mappers.js
node --check src/routes/invoicePool/shared/schemas.js
node --check src/routes/invoicePool/shared/helpers.js
node --check src/routes/audit.js
node --check src/routes/users.js
node --check src/routes/dashboard.js
node --check src/routes/budgets.js
node --check src/routes/integrations.js
node --check src/routes/travelOrders.js
node --check src/routes/notifications.js
node --check src/jobs/delegationRevokeJob.js
node --check src/jobs/ocrJob.js
node --check src/jobs/pgBossJobs.js
node --check src/jobs/verificationJob.js
node --check src/jobs/integrationOutboxJob.js
node --check src/jobs/integrationOutboxWorker.js
node --check src/services/ocr/index.js
node --check src/services/verification/index.js
node --check src/services/integrations/outbox.js
node --check src/services/integrations/erp.js
node --check src/services/integrations/dispatcher.js
bash -n scripts/regression-workflow-actions.sh
bash -n scripts/regression-audit.sh
bash -n scripts/regression-ocr.sh
bash -n scripts/regression-org-settings.sh
bash -n scripts/regression-auth-security.sh
bash -n scripts/regression-verification.sh
bash -n scripts/regression-dashboard.sh
bash -n scripts/regression-budget.sh
bash -n scripts/regression-integrations.sh
bash -n scripts/regression-all.sh
)
echo ""
echo "=== [3/3] Client Typecheck + Build ==="
echo "=== [3/4] Client Typecheck + Build ==="
(
cd "$ROOT_DIR/client"
npm run typecheck
npm run build
)
echo ""
echo "=== [4/4] Feature Matrix Consistency ==="
(
cd "$ROOT_DIR"
python3 scripts/validate-feature-matrix.py
)
echo ""
echo "[OK] Minimal checks passed"
+149
查看文件
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Validate docs/feature-matrix.md against execution-contract CSV sources.
Checks:
- feature-matrix contains exactly one row per ID in CSV fact sources
- every ID from CSVs appears in matrix
- matrix does not contain unknown IDs
- every matrix row status equals DONE
- every fact-source CSV row is fully DONE on Dev/Review1/Regression axes
"""
from __future__ import annotations
import csv
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
MATRIX_PATH = ROOT / "docs" / "feature-matrix.md"
CSV_FACT_SOURCES = [
ROOT / "issues" / "2026-02-09_13-39-02-p5-blueprint-v3.csv",
ROOT / "issues" / "2026-02-09_23-30-00-p6-p8-remaining-work-master.csv",
ROOT / "issues" / "2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv",
ROOT / "issues" / "2026-02-10_10-35-30-p10-production-hardening.csv",
]
ID_PATTERN = re.compile(r"^[A-Z][0-9][0-9A-Za-z]*$")
STATUS_INDEX = 6
def load_csv_rows(path: Path) -> list[dict[str, str]]:
with path.open(encoding="utf-8", newline="") as fp:
return list(csv.DictReader(fp))
def collect_expected_ids_and_source_status(paths: list[Path]) -> tuple[list[str], list[str]]:
ids: list[str] = []
source_errors: list[str] = []
for path in paths:
rows = load_csv_rows(path)
for row in rows:
row_id = (row.get("ID") or "").strip()
if not row_id:
continue
ids.append(row_id)
dev_status = (row.get("Dev_Status") or "").strip().upper()
review_status = (row.get("Review1_Status") or "").strip().upper()
regression_status = (row.get("Regression_Status") or "").strip().upper()
if not (dev_status == review_status == regression_status == "DONE"):
source_errors.append(
f"{path.name}:{row_id} source status not all DONE "
f"(Dev={dev_status}, Review1={review_status}, Regression={regression_status})"
)
return ids, source_errors
def load_matrix_rows(path: Path) -> list[list[str]]:
rows: list[list[str]] = []
for line in path.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if not stripped.startswith("|"):
continue
if stripped.startswith("| ---"):
continue
parts = [part.strip() for part in stripped.strip("|").split("|")]
if not parts:
continue
row_id = parts[0]
if not ID_PATTERN.match(row_id):
continue
rows.append(parts)
return rows
def main() -> int:
errors: list[str] = []
if not MATRIX_PATH.exists():
errors.append(f"Missing matrix file: {MATRIX_PATH}")
for source in CSV_FACT_SOURCES:
if not source.exists():
errors.append(f"Missing csv file: {source}")
if errors:
for err in errors:
print(f"[ERR] {err}")
return 1
expected_ids, source_status_errors = collect_expected_ids_and_source_status(CSV_FACT_SOURCES)
matrix_rows = load_matrix_rows(MATRIX_PATH)
matrix_ids = [row[0] for row in matrix_rows]
expected_id_set = set(expected_ids)
matrix_id_set = set(matrix_ids)
missing_in_matrix = sorted(expected_id_set - matrix_id_set)
extra_in_matrix = sorted(matrix_id_set - expected_id_set)
if missing_in_matrix:
errors.append(f"IDs missing in matrix: {missing_in_matrix}")
if extra_in_matrix:
errors.append(f"Extra IDs in matrix: {extra_in_matrix}")
duplicate_matrix_ids = sorted({item for item in matrix_ids if matrix_ids.count(item) > 1})
if duplicate_matrix_ids:
errors.append(f"Duplicate IDs in matrix: {duplicate_matrix_ids}")
if len(matrix_ids) != len(expected_ids):
errors.append(f"Row count mismatch: matrix={len(matrix_ids)} expected={len(expected_ids)}")
duplicate_expected_ids = sorted({item for item in expected_ids if expected_ids.count(item) > 1})
if duplicate_expected_ids:
errors.append(f"Duplicate IDs in fact-source CSVs: {duplicate_expected_ids}")
for row in matrix_rows:
if len(row) <= STATUS_INDEX:
errors.append(f"Malformed matrix row (too few columns): {row}")
continue
status = row[STATUS_INDEX].upper()
if status != "DONE":
errors.append(f"Non-DONE status in matrix for {row[0]}: {row[STATUS_INDEX]}")
errors.extend(source_status_errors)
if errors:
print("[ERR] feature-matrix validation failed")
for err in errors:
print(f" - {err}")
return 1
source_names = ", ".join(path.name for path in CSV_FACT_SOURCES)
print(
f"[OK] feature-matrix matches fact sources ({source_names}) "
f"(IDs/status/count)"
)
return 0
if __name__ == "__main__":
sys.exit(main())
+22
查看文件
@@ -55,6 +55,14 @@ OCR_POLL_CRON="* * * * *"
OCR_MAX_ATTEMPTS="3"
OCR_TIMEOUT_MS="5000"
# ===== 发票验真(P6)=====
INVOICE_VERIFICATION_ENABLED="false"
VERIFICATION_PROVIDER="mock" # mock|tax
VERIFICATION_POLL_CRON="* * * * *"
VERIFICATION_MAX_ATTEMPTS="3"
VERIFICATION_RETRY_COOLDOWN_SECONDS="60"
VERIFICATION_TIMEOUT_MS="5000"
INVOICE_ARCHIVE_CRON="30 2 * * *"
INVOICE_ARCHIVE_UNUSED_DAYS="90"
INVOICE_ARCHIVE_BATCH_SIZE="200"
@@ -62,6 +70,20 @@ TENCENT_SECRET_ID=""
TENCENT_SECRET_KEY=""
TENCENT_OCR_REGION="ap-beijing"
# ===== 预算与集成(P7-P8)=====
BUDGET_CONTROL_MODE="warn" # warn|block
ERP_SYNC_ENABLED="false"
ERP_SYNC_PROVIDER="mock" # mock|http
ERP_SYNC_ENDPOINT=""
ERP_SYNC_TIMEOUT_MS="5000"
ERP_SYNC_AUTH_TOKEN=""
TRAVEL_SYNC_ENABLED="false"
IM_NOTIFIER_ENABLED="false"
INTEGRATION_OUTBOX_CRON="* * * * *"
INTEGRATION_OUTBOX_BATCH_SIZE="20"
INTEGRATION_OUTBOX_MAX_ATTEMPTS="5"
INTEGRATION_OUTBOX_RETRY_SECONDS="120"
# ===== 试运行引导管理员(E20,可选)=====
# TRIALRUN_ADMIN_EMAIL="[email protected]"
# TRIALRUN_ADMIN_PHONE="13800000000"
+79
查看文件
@@ -442,3 +442,82 @@ npm run job:ocr-once
### 8.2 磁盘空间不足(ENOSPC)
- 在受控环境中制造磁盘满条件后重试上传。
- 预期:错误路径可观测(日志中能定位到 I/O 错误),不要求纳入日常 CI 冒烟。
---
## 9. P6-P10 增量能力(验真 / 看板 / 预算 / 集成 / 生产硬化)
### 9.1 特性开关(默认值)
- `INVOICE_VERIFICATION_ENABLED=false`
- `VERIFICATION_PROVIDER=mock`
- `BUDGET_CONTROL_MODE=warn`
- `ERP_SYNC_ENABLED=false`
- `ERP_SYNC_PROVIDER=mock`
- `ERP_SYNC_ENDPOINT=`
- `ERP_SYNC_TIMEOUT_MS=5000`
- `ERP_SYNC_AUTH_TOKEN=`
- `TRAVEL_SYNC_ENABLED=false`
- `IM_NOTIFIER_ENABLED=false`
建议:先在测试组织灰度开启,再逐步扩大范围。
### 9.2 新增 API 摘要
- 发票验真:
- `POST /api/invoice-pool/:id/verify`
- `GET /api/invoice-pool/:id/verification`
- `POST /api/invoice-pool/:id/verification/retry`
- 看板聚合:
- `GET /api/dashboard/expense-overview`
- `GET /api/dashboard/trends`
- `GET /api/dashboard/top-categories`
- `GET /api/dashboard/approval-efficiency`
- 预算管理:
- `GET /api/budgets`
- `POST /api/budgets`
- `PATCH /api/budgets/:id`
- `POST /api/budgets/:id/archive`
- 外部集成:
- `POST /api/integrations/erp/sync/:reimbursementId`
- `POST /api/travel/orders/import`
- `GET /api/notifications/channels`
- `POST /api/notifications/channels/test`
### 9.3 新增回归脚本
```bash
cd /home/shunli/Projects/hyb-oa/server
./scripts/regression-verification.sh
./scripts/regression-dashboard.sh
./scripts/regression-budget.sh
./scripts/regression-integrations.sh
```
可通过总回归开关启用:
```bash
cd /home/shunli/Projects/hyb-oa/server
RUN_VERIFICATION_REGRESSION=1 \
RUN_DASHBOARD_REGRESSION=1 \
RUN_BUDGET_REGRESSION=1 \
RUN_INTEGRATIONS_REGRESSION=1 \
./scripts/regression-all.sh
```
### 9.4 单次任务脚本(调试)
```bash
cd /home/shunli/Projects/hyb-oa/server
VERIFICATION_RECORD_ID=<uuid> npm run job:verification-once
npm run job:integration-outbox-once
```
### 9.5 回滚建议
1. 先关闭特性开关(验真/ERP/差旅/IM)。
2. 再停止相关任务调度(verification / integration outbox)。
3. 不回滚审计与历史台账数据,保持可追溯。
### 9.6 P9/P10 维护性与硬化说明
- 票据路由拆分:验真端点已拆到 `src/routes/invoicePool/verification.js`,读路径端点已拆到 `src/routes/invoicePool/read.js`,主入口仍为 `src/routes/invoicePool.js`,API 路径不变。
- Shared 抽象:`src/routes/invoicePool/shared/{selects,mappers,schemas,helpers}.js` 统一验真映射与票据查询 `select`,避免字段漂移。
- 看板聚合:`/api/dashboard/trends` 与 `/api/dashboard/top-categories` 已改为数据库聚合(groupBy),降低大数据量下内存聚合开销。
- 看板回归:`./scripts/regression-dashboard.sh` 新增重复请求一致性断言;可通过 `DASHBOARD_PERF_CHECK=1` 打印趋势接口耗时探针。
- ERP硬化回归:`./scripts/regression-integrations.sh` 内嵌最小 Node Mock ERP 服务,覆盖 success / 4xx(dead_letter) / 5xx(retry) / timeout(retry)。
- 矩阵门禁:`scripts/validate-feature-matrix.py` 默认校验 P5 + P6-P8 + P9 + P10 四事实源;`./scripts/check-minimal.sh` 会自动执行该校验。
+375
查看文件
@@ -0,0 +1,375 @@
#!/usr/bin/env bash
set -euo pipefail
ERP_SYNC_TIMEOUT_MS="${ERP_SYNC_TIMEOUT_MS:-300}"
MOCK_ERP_PORT="${MOCK_ERP_PORT:-$((3900 + RANDOM % 500))}"
if ! command -v node >/dev/null 2>&1; then
echo "[ERROR] node not found" >&2
exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
echo "[ERROR] curl not found" >&2
exit 1
fi
if ! command -v jq >/dev/null 2>&1; then
echo "[ERROR] jq not found" >&2
exit 1
fi
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"
if [[ -z "${DATABASE_URL:-}" && -f ".env" ]]; then
set -a
# shellcheck disable=SC1091
source .env
set +a
fi
if [[ -z "${DATABASE_URL:-}" ]]; then
echo "[ERROR] DATABASE_URL is required (export it or provide server/.env)" >&2
exit 1
fi
TMP_DIR="$(mktemp -d)"
RUN_SUFFIX="$(date +%s)-$RANDOM"
MOCK_SERVER_PID=""
cleanup() {
if [[ -n "$MOCK_SERVER_PID" ]] && kill -0 "$MOCK_SERVER_PID" >/dev/null 2>&1; then
kill "$MOCK_SERVER_PID" >/dev/null 2>&1 || true
wait "$MOCK_SERVER_PID" >/dev/null 2>&1 || true
fi
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
start_mock_erp_server() {
local server_file="$TMP_DIR/mock-erp-server.js"
cat >"$server_file" <<'NODE'
const http = require("node:http");
const { URL } = require("node:url");
const port = Number(process.argv[2] || 3900);
function sendJson(res, status, payload) {
res.statusCode = status;
res.setHeader("content-type", "application/json; charset=utf-8");
res.end(JSON.stringify(payload));
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || `127.0.0.1:${port}`}`);
if (req.method === "GET" && url.pathname === "/health") {
return sendJson(res, 200, { ok: true, mode: "health" });
}
if (req.method === "POST" && url.pathname === "/erp/reimbursements/paid") {
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,
scenario: "timeout",
externalId: `ERP-TIMEOUT-${Date.now()}`,
reimbursementId: parsedBody?.reimbursementId || null,
});
}, 1500);
return;
}
if (mode === "client") {
return sendJson(res, 422, {
ok: false,
scenario: "client",
code: "invalid_payload",
message: "mock client error",
});
}
if (mode === "server") {
return sendJson(res, 503, {
ok: false,
scenario: "server",
code: "service_unavailable",
message: "mock server error",
});
}
return sendJson(res, 200, {
ok: true,
scenario: "success",
externalId: `ERP-${parsedBody?.formNumber || parsedBody?.reimbursementId || Date.now()}`,
reimbursementId: parsedBody?.reimbursementId || null,
});
}
sendJson(res, 404, { ok: false, message: "not_found" });
});
server.listen(port, "127.0.0.1", () => {
process.stdout.write(`mock-erp-listening:${port}\n`);
});
NODE
node "$server_file" "$MOCK_ERP_PORT" >"$TMP_DIR/mock-erp.log" 2>&1 &
MOCK_SERVER_PID="$!"
for _ in $(seq 1 30); do
if curl -sS "http://127.0.0.1:$MOCK_ERP_PORT/health" >/dev/null 2>&1; then
return 0
fi
sleep 0.2
done
echo "[ERROR] mock ERP server failed to start" >&2
cat "$TMP_DIR/mock-erp.log" >&2 || true
exit 1
}
create_paid_reimbursement_and_enqueue() {
local scenario="$1"
DATABASE_URL="$DATABASE_URL" RUN_SUFFIX="$RUN_SUFFIX" SCENARIO="$scenario" node <<'NODE'
require("dotenv/config");
const { createPrismaClient } = require("./src/prismaClient");
const { getConfig } = require("./src/config");
const { buildErpPayload } = require("./src/services/integrations/erp");
const { enqueueIntegrationEvent } = require("./src/services/integrations/outbox");
(async () => {
const runSuffix = process.env.RUN_SUFFIX;
const scenario = process.env.SCENARIO;
const config = getConfig();
const { prisma, pool } = createPrismaClient();
await prisma.$connect();
try {
const owner = await prisma.employee.findFirst({
where: {
email: {
in: ["[email protected]", "[email protected]"],
},
},
select: { id: true, department_id: true },
orderBy: { created_at: "asc" },
});
if (!owner) {
throw new Error("employee/finance_mgr not found");
}
const reimbursement = await prisma.reimbursementForm.create({
data: {
form_number: `BX-P10-${scenario}-${runSuffix}`.slice(0, 60),
submitter_id: owner.id,
owner_id: owner.id,
department_id: owner.department_id,
reimbursement_date: new Date("2026-02-10T00:00:00.000Z"),
total_amount: "100.00",
status: "paid",
payment_voucher_no: `PV-${scenario}-${runSuffix}`.slice(0, 60),
payment_date: new Date("2026-02-10T00:00:00.000Z"),
paid_at: new Date(),
created_by: owner.id,
updated_by: owner.id,
},
select: {
id: true,
form_number: true,
owner_id: true,
submitter_id: true,
total_amount: true,
payment_voucher_no: true,
payment_date: true,
paid_at: true,
},
});
const payload = buildErpPayload({ reimbursement });
const enqueued = await enqueueIntegrationEvent(prisma, {
eventType: "erp.reimbursement.paid",
payload,
dedupeKey: reimbursement.id,
maxAttempts: config.integrationOutboxMaxAttempts,
actorId: owner.id,
});
process.stdout.write(
JSON.stringify({
scenario,
reimbursementId: reimbursement.id,
outboxId: enqueued.id,
duplicated: enqueued.duplicated,
}),
);
} finally {
await prisma.$disconnect();
await pool.end();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
NODE
}
query_outbox_state() {
local outbox_id="$1"
DATABASE_URL="$DATABASE_URL" OUTBOX_ID="$outbox_id" node <<'NODE'
require("dotenv/config");
const { createPrismaClient } = require("./src/prismaClient");
(async () => {
const outboxId = process.env.OUTBOX_ID;
const { prisma, pool } = createPrismaClient();
await prisma.$connect();
try {
const row = await prisma.integrationOutbox.findUnique({
where: { id: outboxId },
select: {
id: true,
status: true,
attempts: true,
next_retry_at: true,
dead_letter_at: true,
last_error: true,
},
});
if (!row) {
throw new Error(`outbox not found: ${outboxId}`);
}
process.stdout.write(
JSON.stringify({
id: row.id,
status: row.status,
attempts: row.attempts,
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,
}),
);
} finally {
await prisma.$disconnect();
await pool.end();
}
})().catch((error) => {
console.error(error);
process.exit(1);
});
NODE
}
run_outbox_once() {
local endpoint="$1"
ERP_SYNC_ENABLED=true \
ERP_SYNC_PROVIDER=http \
ERP_SYNC_ENDPOINT="$endpoint" \
ERP_SYNC_TIMEOUT_MS="$ERP_SYNC_TIMEOUT_MS" \
ERP_SYNC_AUTH_TOKEN="" \
npm run --silent job:integration-outbox-once >"$TMP_DIR/outbox-once.log"
}
assert_mode_semantics() {
local mode="$1"
local state_json="$2"
case "$mode" in
success)
jq -e '.status == "succeeded" and .nextRetryAt == null and .deadLetterAt == null' <<<"$state_json" >/dev/null
;;
client)
jq -e '.status == "dead_letter" and .attempts == 1 and .deadLetterAt != null and .nextRetryAt == null' <<<"$state_json" >/dev/null
jq -e '.lastError | tostring | test("422|erp_sync_http_4xx")' <<<"$state_json" >/dev/null
;;
server)
jq -e '.status == "failed" and .attempts == 1 and .deadLetterAt == null and .nextRetryAt != null' <<<"$state_json" >/dev/null
jq -e '.lastError | tostring | test("503|erp_sync_http_5xx")' <<<"$state_json" >/dev/null
;;
timeout)
jq -e '.status == "failed" and .attempts == 1 and .deadLetterAt == null and .nextRetryAt != null' <<<"$state_json" >/dev/null
jq -e '.lastError | tostring | test("erp_sync_timeout|timeout")' <<<"$state_json" >/dev/null
;;
*)
echo "[ERROR] unsupported mode assertion: $mode" >&2
exit 1
;;
esac
}
run_mode_case() {
local mode="$1"
local created_json
created_json="$(create_paid_reimbursement_and_enqueue "$mode")"
local outbox_id
outbox_id="$(jq -er '.outboxId' <<<"$created_json")"
local endpoint="http://127.0.0.1:$MOCK_ERP_PORT/erp/reimbursements/paid?mode=$mode"
local state_json=""
local status=""
for _ in $(seq 1 8); do
run_outbox_once "$endpoint"
state_json="$(query_outbox_state "$outbox_id")"
status="$(jq -r '.status' <<<"$state_json")"
if [[ "$status" != "pending" && "$status" != "processing" ]]; then
break
fi
sleep 0.2
done
if [[ "$status" == "pending" || "$status" == "processing" ]]; then
echo "[ERROR] mode=$mode did not finish processing" >&2
echo "$state_json" >&2
exit 1
fi
if ! assert_mode_semantics "$mode" "$state_json"; then
echo "[ERROR] mode=$mode semantics assertion failed" >&2
echo "$state_json" >&2
exit 1
fi
echo "[OK] mode=$mode outbox_status=$status"
}
echo "[1/6] Start embedded mock ERP server"
start_mock_erp_server
echo "[2/6] ERP success path => succeeded"
run_mode_case "success"
echo "[3/6] ERP 4xx path => dead_letter"
run_mode_case "client"
echo "[4/6] ERP 5xx path => failed(retryable)"
run_mode_case "server"
echo "[5/6] ERP timeout path => failed(retryable)"
run_mode_case "timeout"
echo "[6/6] Done"
echo "[OK] Integrations regression passed"
+23
查看文件
@@ -90,6 +90,29 @@ function getConfig() {
ocrMaxAttempts: Number(process.env.OCR_MAX_ATTEMPTS ?? 3),
ocrTimeoutMs: Number(process.env.OCR_TIMEOUT_MS ?? 5000),
invoiceVerificationEnabled: process.env.INVOICE_VERIFICATION_ENABLED === "true",
verificationProvider: process.env.VERIFICATION_PROVIDER ?? "mock",
verificationPollCron: process.env.VERIFICATION_POLL_CRON ?? "* * * * *",
verificationMaxAttempts: Number(process.env.VERIFICATION_MAX_ATTEMPTS ?? 3),
verificationRetryCooldownSeconds: Number(
process.env.VERIFICATION_RETRY_COOLDOWN_SECONDS ?? 60,
),
verificationTimeoutMs: Number(process.env.VERIFICATION_TIMEOUT_MS ?? 5000),
budgetControlMode: process.env.BUDGET_CONTROL_MODE ?? "warn",
erpSyncEnabled: process.env.ERP_SYNC_ENABLED === "true",
erpSyncProvider: process.env.ERP_SYNC_PROVIDER ?? "mock",
erpSyncEndpoint: process.env.ERP_SYNC_ENDPOINT ?? "",
erpSyncTimeoutMs: Number(process.env.ERP_SYNC_TIMEOUT_MS ?? 5000),
erpSyncAuthToken: process.env.ERP_SYNC_AUTH_TOKEN ?? "",
travelSyncEnabled: process.env.TRAVEL_SYNC_ENABLED === "true",
imNotifierEnabled: process.env.IM_NOTIFIER_ENABLED === "true",
integrationOutboxCron: process.env.INTEGRATION_OUTBOX_CRON ?? "* * * * *",
integrationOutboxBatchSize: Number(process.env.INTEGRATION_OUTBOX_BATCH_SIZE ?? 20),
integrationOutboxMaxAttempts: Number(process.env.INTEGRATION_OUTBOX_MAX_ATTEMPTS ?? 5),
integrationOutboxRetrySeconds: Number(process.env.INTEGRATION_OUTBOX_RETRY_SECONDS ?? 120),
invoiceArchiveCron: process.env.INVOICE_ARCHIVE_CRON ?? "30 2 * * *",
invoiceArchiveUnusedDays: Number(process.env.INVOICE_ARCHIVE_UNUSED_DAYS ?? 90),
invoiceArchiveBatchSize: Number(process.env.INVOICE_ARCHIVE_BATCH_SIZE ?? 200),
+124
查看文件
@@ -0,0 +1,124 @@
const cron = require("node-cron");
const {
fetchPendingOutboxEvents,
markOutboxFailed,
markOutboxProcessing,
markOutboxSucceeded,
} = require("../services/integrations/outbox");
const { dispatchOutboxEvent } = require("../services/integrations/dispatcher");
async function runIntegrationOutboxOnce(prisma, config, logger) {
const items = await fetchPendingOutboxEvents(prisma, {
batchSize: config.integrationOutboxBatchSize,
});
let succeeded = 0;
let failed = 0;
for (const item of items) {
await markOutboxProcessing(prisma, item.id, null);
try {
await dispatchOutboxEvent({
config,
eventType: item.event_type,
payload: item.payload,
});
await markOutboxSucceeded(prisma, item.id, null);
succeeded += 1;
} catch (error) {
const retryable = typeof error?.retryable === "boolean" ? error.retryable : true;
await markOutboxFailed(prisma, config, item, error, null, { retryable });
failed += 1;
logger.error(
{
err: error,
retryable,
outboxId: item.id,
eventType: item.event_type,
},
"Integration outbox dispatch failed",
);
}
}
return {
total: items.length,
succeeded,
failed,
};
}
function startIntegrationOutboxJob(fastify) {
let running = false;
const task = cron.schedule(fastify.config.integrationOutboxCron, async () => {
if (running) {
return;
}
running = true;
try {
const result = await runIntegrationOutboxOnce(
fastify.prisma,
fastify.config,
fastify.log,
);
fastify.metrics?.jobRunsTotal?.inc?.({
job: "integration.outbox.dispatch",
driver: "cron",
outcome: "success",
});
if (result.succeeded > 0) {
fastify.metrics?.jobProcessedTotal?.inc?.(
{
job: "integration.outbox.dispatch",
driver: "cron",
kind: "succeeded",
},
result.succeeded,
);
}
if (result.failed > 0) {
fastify.metrics?.jobProcessedTotal?.inc?.(
{
job: "integration.outbox.dispatch",
driver: "cron",
kind: "failed",
},
result.failed,
);
}
} catch (error) {
fastify.log.error({ err: error }, "Integration outbox job failed");
fastify.metrics?.jobRunsTotal?.inc?.({
job: "integration.outbox.dispatch",
driver: "cron",
outcome: "failure",
});
} finally {
running = false;
}
});
fastify.addHook("onClose", async () => {
task.stop();
task.destroy();
});
fastify.log.info(
{
cron: fastify.config.integrationOutboxCron,
batchSize: fastify.config.integrationOutboxBatchSize,
},
"Integration outbox job scheduled",
);
return task;
}
module.exports = {
runIntegrationOutboxOnce,
startIntegrationOutboxJob,
};
+14 -790
查看文件
@@ -7,11 +7,14 @@ const { sendData } = require("../utils/reply");
const { buildAuditLogData } = require("../utils/audit");
const { compactDateString } = require("../utils/date");
const { sha256Hex } = require("../utils/crypto");
const { signPayload, verifyToken } = require("../utils/signedUrl");
const { toMoneyString } = require("../utils/workflow");
const { findActiveDelegationForDelegate } = require("../utils/delegation");
const { isOcrEnabledForType } = require("../services/ocr");
const { openReadStream, StorageNotFoundError, writeBuffer } = require("../services/storage");
const { registerInvoiceVerificationRoutes } = require("./invoicePool/verification");
const { registerInvoicePoolReadRoutes } = require("./invoicePool/read");
const { normalizeInvoiceResponse } = require("./invoicePool/shared/mappers");
const { buildInvoiceDetailSelect } = require("./invoicePool/shared/selects");
const { writeBuffer } = require("../services/storage");
const MIME_ALLOWLIST = new Set([
"application/pdf",
@@ -52,13 +55,6 @@ const overrideDuplicateBodySchema = z
})
.strict();
const invoiceListQuerySchema = z.object({
page: z.coerce.number().int().min(1).optional(),
pageSize: z.coerce.number().int().min(1).max(100).optional(),
status: z.enum(["pending_ocr", "ocr_failed", "available", "bound", "archived"]).optional(),
ownerScope: z.enum(["own", "all"]).optional(),
});
const DEDUP_CONSTRAINT_NAMES = new Set([
"invoice_pool_file_sha256_dedup_ux",
"invoice_pool_invoice_code_number_dedup_ux",
@@ -148,36 +144,6 @@ function isInvoiceDedupConflict(error) {
return isFieldBasedDedup(fieldTokens);
}
function ensureInvoiceReadableByUser(request, invoice) {
const roleCodes = request.employee.roleCodes;
if (
roleCodes.includes("admin") ||
roleCodes.includes("finance") ||
roleCodes.includes("finance_mgr")
) {
return true;
}
if (
invoice.owner_employee_id === request.employee.id ||
invoice.uploaded_by_employee_id === request.employee.id
) {
return true;
}
if (invoice.linked_reimbursement) {
const reimbursement = invoice.linked_reimbursement;
if (
reimbursement.owner_id === request.employee.id ||
reimbursement.submitter_id === request.employee.id
) {
return true;
}
}
return false;
}
function normalizeMoneyInput(value) {
if (value == null) {
return null;
@@ -218,205 +184,9 @@ function parseDateOnlyString(value) {
return new Date(`${trimmed}T00:00:00.000Z`);
}
function sanitizeFilename(fileName) {
if (!fileName) return "file";
return fileName.replace(/[\r\n"]/g, "_");
}
function parseInvoiceListQuery(query) {
const parsed = invoiceListQuerySchema.safeParse(query ?? {});
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: parsed.error.flatten(),
});
}
return {
page: parsed.data.page ?? 1,
pageSize: parsed.data.pageSize ?? 20,
status: parsed.data.status,
ownerScope: parsed.data.ownerScope,
};
}
function mapInvoiceSummary(item) {
return {
id: item.id,
status: item.status,
ocrType: item.ocr_type,
ocrProvider: item.ocr_provider,
ocrAttempts: item.ocr_attempts,
ocrLastError: item.ocr_last_error,
ocrCompletedAt: item.ocr_completed_at?.toISOString?.() ?? null,
invoiceCode: item.invoice_code,
invoiceNumber: item.invoice_number,
invoiceDate: item.invoice_date?.toISOString?.()?.slice(0, 10) ?? null,
amount: toMoneyString(item.amount),
taxAmount: toMoneyString(item.tax_amount),
totalAmount: toMoneyString(item.total_amount),
linkedReimbursementId: item.linked_reimbursement_id,
linkedItemId: item.linked_item_id,
originalName: item.original_name,
mimeType: item.mime_type,
fileSize: item.file_size,
owner: item.owner_employee
? {
id: item.owner_employee.id,
employeeNo: item.owner_employee.employee_no,
name: item.owner_employee.name,
}
: null,
uploadedBy: item.uploaded_by_employee
? {
id: item.uploaded_by_employee.id,
employeeNo: item.uploaded_by_employee.employee_no,
name: item.uploaded_by_employee.name,
}
: null,
createdAt: item.created_at?.toISOString?.() ?? null,
updatedAt: item.updated_at?.toISOString?.() ?? null,
};
}
function normalizeInvoiceResponse(invoice) {
return {
id: invoice.id,
status: invoice.status,
archivedReason: invoice.archived_reason ?? null,
archivedAt: invoice.archived_at?.toISOString?.() ?? null,
ownerEmployeeId: invoice.owner_employee_id,
uploadedByEmployeeId: invoice.uploaded_by_employee_id,
originalName: invoice.original_name ?? null,
mimeType: invoice.mime_type ?? null,
fileSize: invoice.file_size ?? null,
fileSha256: invoice.file_sha256 ?? null,
remarks: invoice.remarks ?? null,
ocrType: invoice.ocr_type,
ocrProvider: invoice.ocr_provider,
ocrAttempts: invoice.ocr_attempts,
ocrLastRequestedAt: invoice.ocr_last_requested_at?.toISOString?.() ?? null,
ocrLastError: invoice.ocr_last_error,
ocrCompletedAt: invoice.ocr_completed_at?.toISOString?.() ?? null,
invoiceCode: invoice.invoice_code,
invoiceNumber: invoice.invoice_number,
invoiceDate: invoice.invoice_date ? invoice.invoice_date.toISOString().slice(0, 10) : null,
sellerName: invoice.seller_name ?? null,
buyerName: invoice.buyer_name ?? null,
amount: toMoneyString(invoice.amount),
taxAmount: toMoneyString(invoice.tax_amount),
totalAmount: toMoneyString(invoice.total_amount),
linkedReimbursementId: invoice.linked_reimbursement_id,
linkedItemId: invoice.linked_item_id,
isDuplicateOverride: invoice.is_duplicate_override ?? false,
overrideRefFormNumber: invoice.override_ref_form_number ?? null,
overrideReason: invoice.override_reason ?? null,
overriddenBy: invoice.overridden_by ?? null,
createdAt: invoice.created_at?.toISOString?.() ?? null,
updatedAt: invoice.updated_at?.toISOString?.() ?? null,
};
}
async function invoicePoolRoutes(fastify) {
fastify.get(
"/invoice-pool",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const query = parseInvoiceListQuery(request.query);
const canViewOwn = fastify.hasPermission(request.employee, "invoice.view_own");
const canManage = fastify.hasPermission(request.employee, "invoice.manage");
if (!canViewOwn && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const ownerScope = query.ownerScope ?? (canManage ? "all" : "own");
if (ownerScope === "all" && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const skip = (query.page - 1) * query.pageSize;
const where = {
...(query.status ? { status: query.status } : {}),
...(ownerScope === "all"
? {}
: {
OR: [
{ owner_employee_id: request.employee.id },
{ uploaded_by_employee_id: request.employee.id },
{
linked_reimbursement: {
OR: [
{ owner_id: request.employee.id },
{ submitter_id: request.employee.id },
],
},
},
],
}),
};
const [items, total] = await Promise.all([
fastify.prisma.invoicePool.findMany({
where,
orderBy: { created_at: "desc" },
skip,
take: query.pageSize,
select: {
id: true,
status: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
original_name: true,
mime_type: true,
file_size: true,
created_at: true,
updated_at: true,
owner_employee: {
select: { id: true, employee_no: true, name: true },
},
uploaded_by_employee: {
select: { id: true, employee_no: true, name: true },
},
},
}),
fastify.prisma.invoicePool.count({ where }),
]);
return sendData(reply, request, {
page: query.page,
pageSize: query.pageSize,
total,
ownerScope,
items: items.map(mapInvoiceSummary),
});
},
);
registerInvoicePoolReadRoutes(fastify);
fastify.post(
"/invoice-pool/upload",
@@ -626,107 +396,7 @@ async function invoicePoolRoutes(fastify) {
},
);
fastify.get(
"/invoice-pool/:id",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
linked_reimbursement: {
select: {
owner_id: true,
submitter_id: true,
},
},
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess && invoice.linked_reimbursement_id) {
const pendingTask = await fastify.prisma.workflowTask.findFirst({
where: {
status: "pending",
workflow_instance: {
entity_type: "reimbursement",
entity_id: invoice.linked_reimbursement_id,
current_status: "pending",
},
OR: [
{ assignee_id: request.employee.id },
{ assignee_role: { in: request.employee.roleCodes } },
],
},
select: { id: true },
});
canAccess = Boolean(pendingTask);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
return sendData(reply, request, normalizeInvoiceResponse(invoice));
},
);
registerInvoiceVerificationRoutes(fastify);
fastify.patch(
"/invoice-pool/:id",
@@ -783,41 +453,7 @@ async function invoicePoolRoutes(fastify) {
const current = await tx.invoicePool.findUnique({
where: { id: invoiceId },
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
if (!current) {
@@ -955,41 +591,7 @@ async function invoicePoolRoutes(fastify) {
const updated = await tx.invoicePool.update({
where: { id: invoiceId },
data: updateData,
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
const changes = {};
@@ -1128,41 +730,7 @@ async function invoicePoolRoutes(fastify) {
if (current.status === "archived" && current.archived_reason === "manual") {
return tx.invoicePool.findUnique({
where: { id: invoiceId },
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
}
@@ -1184,41 +752,7 @@ async function invoicePoolRoutes(fastify) {
archived_at: now,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
await tx.auditLog.create({
@@ -1330,41 +864,7 @@ async function invoicePoolRoutes(fastify) {
linked_item_id: null,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
});
@@ -1491,41 +991,7 @@ async function invoicePoolRoutes(fastify) {
ocr_lock_owner: null,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
await tx.auditLog.create({
@@ -1702,41 +1168,7 @@ async function invoicePoolRoutes(fastify) {
overridden_by: request.employee.id,
updated_by: request.employee.id,
},
select: {
id: true,
status: true,
archived_reason: true,
archived_at: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
original_name: true,
mime_type: true,
file_size: true,
file_sha256: true,
remarks: true,
ocr_type: true,
ocr_provider: true,
ocr_attempts: true,
ocr_last_requested_at: true,
ocr_last_error: true,
ocr_completed_at: true,
invoice_code: true,
invoice_number: true,
invoice_date: true,
seller_name: true,
buyer_name: true,
amount: true,
tax_amount: true,
total_amount: true,
linked_reimbursement_id: true,
linked_item_id: true,
is_duplicate_override: true,
override_ref_form_number: true,
override_reason: true,
overridden_by: true,
created_at: true,
updated_at: true,
},
select: buildInvoiceDetailSelect(),
});
await tx.auditLog.create({
@@ -1760,214 +1192,6 @@ async function invoicePoolRoutes(fastify) {
},
);
fastify.post(
"/invoice-pool/:id/signed-url",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
id: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
linked_reimbursement_id: true,
linked_reimbursement: {
select: {
owner_id: true,
submitter_id: true,
},
},
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess && invoice.linked_reimbursement_id) {
const pendingTask = await fastify.prisma.workflowTask.findFirst({
where: {
status: "pending",
workflow_instance: {
entity_type: "reimbursement",
entity_id: invoice.linked_reimbursement_id,
current_status: "pending",
},
OR: [
{ assignee_id: request.employee.id },
{ assignee_role: { in: request.employee.roleCodes } },
],
},
select: { id: true },
});
canAccess = Boolean(pendingTask);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const expiresAt = Date.now() + fastify.config.signedUrlTtlSeconds * 1000;
const token = signPayload(
{
invoiceId: invoice.id,
actorId: request.employee.id,
exp: expiresAt,
},
fastify.config.jwtSecret,
);
const origin =
fastify.config.appOrigin ||
`${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
const signedUrl = `${origin}/api/invoice-pool/${invoice.id}/file?token=${encodeURIComponent(token)}`;
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "INVOICE_SIGNED_URL_ISSUED",
targetType: "invoice_pool",
targetId: invoice.id,
extra: {
invoiceId: invoice.id,
expiresAt,
},
}),
});
return sendData(reply, request, {
signedUrl,
expiresAt: new Date(expiresAt).toISOString(),
});
},
);
fastify.get("/invoice-pool/:id/file", async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
const token = request.query?.token;
if (!parsedInvoiceId.success || typeof token !== "string") {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const verified = verifyToken(token, fastify.config.jwtSecret);
if (!verified.ok) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const payload = verified.payload;
const parsedActorId = z.string().uuid().safeParse(payload?.actorId);
if (
payload?.invoiceId !== parsedInvoiceId.data ||
typeof payload?.exp !== "number" ||
payload.exp <= Date.now() ||
!parsedActorId.success
) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const actorId = parsedActorId.data;
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
storage_path: true,
mime_type: true,
original_name: true,
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let stream = null;
try {
const opened = await openReadStream({
config: fastify.config,
storagePath: invoice.storage_path,
});
stream = opened.stream;
} catch (error) {
if (error instanceof StorageNotFoundError) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
throw new AppError({
code: "SYS_001",
message: "服务器内部错误",
statusCode: 500,
details: {},
});
}
try {
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: "INVOICE_FILE_DOWNLOADED",
targetType: "invoice_pool",
targetId: parsedInvoiceId.data,
extra: {
invoiceId: parsedInvoiceId.data,
exp: payload.exp,
},
}),
});
} catch (error) {
fastify.log.error({ err: error, invoiceId: parsedInvoiceId.data }, "Audit log write failed");
}
reply.type(invoice.mime_type || "application/octet-stream");
reply.header(
"content-disposition",
`inline; filename=\"${sanitizeFilename(invoice.original_name)}\"`,
);
return reply.send(stream);
});
fastify.post(
"/invoice-pool/:id/bind",
{
+413
查看文件
@@ -0,0 +1,413 @@
const { z } = require("zod");
const { AppError } = require("../../utils/AppError");
const { sendData } = require("../../utils/reply");
const { buildAuditLogData } = require("../../utils/audit");
const { signPayload, verifyToken } = require("../../utils/signedUrl");
const { openReadStream, StorageNotFoundError } = require("../../services/storage");
const {
mapInvoiceSummary,
normalizeInvoiceResponse,
} = require("./shared/mappers");
const {
buildInvoiceDetailSelect,
buildInvoiceSummarySelect,
} = require("./shared/selects");
const invoiceListQuerySchema = z.object({
page: z.coerce.number().int().min(1).optional(),
pageSize: z.coerce.number().int().min(1).max(100).optional(),
status: z.enum(["pending_ocr", "ocr_failed", "available", "bound", "archived"]).optional(),
ownerScope: z.enum(["own", "all"]).optional(),
});
function sanitizeFilename(fileName) {
if (!fileName) return "file";
return fileName.replace(/[\r\n"]/g, "_");
}
function parseInvoiceListQuery(query) {
const parsed = invoiceListQuerySchema.safeParse(query ?? {});
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: parsed.error.flatten(),
});
}
return {
page: parsed.data.page ?? 1,
pageSize: parsed.data.pageSize ?? 20,
status: parsed.data.status,
ownerScope: parsed.data.ownerScope,
};
}
function ensureInvoiceReadableByUser(request, invoice) {
const roleCodes = request.employee.roleCodes;
if (
roleCodes.includes("admin") ||
roleCodes.includes("finance") ||
roleCodes.includes("finance_mgr")
) {
return true;
}
if (
invoice.owner_employee_id === request.employee.id ||
invoice.uploaded_by_employee_id === request.employee.id
) {
return true;
}
if (invoice.linked_reimbursement) {
const reimbursement = invoice.linked_reimbursement;
if (
reimbursement.owner_id === request.employee.id ||
reimbursement.submitter_id === request.employee.id
) {
return true;
}
}
return false;
}
async function hasPendingTaskAccess(fastify, request, linkedReimbursementId) {
if (!linkedReimbursementId) {
return false;
}
const pendingTask = await fastify.prisma.workflowTask.findFirst({
where: {
status: "pending",
workflow_instance: {
entity_type: "reimbursement",
entity_id: linkedReimbursementId,
current_status: "pending",
},
OR: [
{ assignee_id: request.employee.id },
{ assignee_role: { in: request.employee.roleCodes } },
],
},
select: { id: true },
});
return Boolean(pendingTask);
}
function registerInvoicePoolReadRoutes(fastify) {
fastify.get(
"/invoice-pool",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const query = parseInvoiceListQuery(request.query);
const canViewOwn = fastify.hasPermission(request.employee, "invoice.view_own");
const canManage = fastify.hasPermission(request.employee, "invoice.manage");
if (!canViewOwn && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const ownerScope = query.ownerScope ?? (canManage ? "all" : "own");
if (ownerScope === "all" && !canManage) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const skip = (query.page - 1) * query.pageSize;
const where = {
...(query.status ? { status: query.status } : {}),
...(ownerScope === "all"
? {}
: {
OR: [
{ owner_employee_id: request.employee.id },
{ uploaded_by_employee_id: request.employee.id },
{
linked_reimbursement: {
OR: [
{ owner_id: request.employee.id },
{ submitter_id: request.employee.id },
],
},
},
],
}),
};
const [items, total] = await Promise.all([
fastify.prisma.invoicePool.findMany({
where,
orderBy: { created_at: "desc" },
skip,
take: query.pageSize,
select: buildInvoiceSummarySelect(),
}),
fastify.prisma.invoicePool.count({ where }),
]);
return sendData(reply, request, {
page: query.page,
pageSize: query.pageSize,
total,
ownerScope,
items: items.map(mapInvoiceSummary),
});
},
);
fastify.get(
"/invoice-pool/:id",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: buildInvoiceDetailSelect({ includeLinkedReimbursement: true }),
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess) {
canAccess = await hasPendingTaskAccess(fastify, request, invoice.linked_reimbursement_id);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
return sendData(reply, request, normalizeInvoiceResponse(invoice));
},
);
fastify.post(
"/invoice-pool/:id/signed-url",
{
preHandler: fastify.authenticate,
},
async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
if (!parsedInvoiceId.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
id: true,
owner_employee_id: true,
uploaded_by_employee_id: true,
linked_reimbursement_id: true,
linked_reimbursement: {
select: {
owner_id: true,
submitter_id: true,
},
},
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let canAccess = ensureInvoiceReadableByUser(request, invoice);
if (!canAccess) {
canAccess = await hasPendingTaskAccess(fastify, request, invoice.linked_reimbursement_id);
}
if (!canAccess) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const expiresAt = Date.now() + fastify.config.signedUrlTtlSeconds * 1000;
const token = signPayload(
{
invoiceId: invoice.id,
actorId: request.employee.id,
exp: expiresAt,
},
fastify.config.jwtSecret,
);
const origin =
fastify.config.appOrigin ||
`${request.protocol}://${request.headers.host ?? "localhost:3000"}`;
const signedUrl = `${origin}/api/invoice-pool/${invoice.id}/file?token=${encodeURIComponent(token)}`;
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "INVOICE_SIGNED_URL_ISSUED",
targetType: "invoice_pool",
targetId: invoice.id,
extra: {
invoiceId: invoice.id,
expiresAt,
},
}),
});
return sendData(reply, request, {
signedUrl,
expiresAt: new Date(expiresAt).toISOString(),
});
},
);
fastify.get("/invoice-pool/:id/file", async (request, reply) => {
const parsedInvoiceId = z.string().uuid().safeParse(request.params?.id);
const token = request.query?.token;
if (!parsedInvoiceId.success || typeof token !== "string") {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const verified = verifyToken(token, fastify.config.jwtSecret);
if (!verified.ok) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const payload = verified.payload;
const parsedActorId = z.string().uuid().safeParse(payload?.actorId);
if (
payload?.invoiceId !== parsedInvoiceId.data ||
typeof payload?.exp !== "number" ||
payload.exp <= Date.now() ||
!parsedActorId.success
) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
const actorId = parsedActorId.data;
const invoice = await fastify.prisma.invoicePool.findUnique({
where: { id: parsedInvoiceId.data },
select: {
storage_path: true,
mime_type: true,
original_name: true,
},
});
if (!invoice) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
let stream = null;
try {
const opened = await openReadStream({
config: fastify.config,
storagePath: invoice.storage_path,
});
stream = opened.stream;
} catch (error) {
if (error instanceof StorageNotFoundError) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
throw new AppError({
code: "SYS_001",
message: "服务器内部错误",
statusCode: 500,
details: {},
});
}
try {
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId,
action: "INVOICE_FILE_DOWNLOADED",
targetType: "invoice_pool",
targetId: parsedInvoiceId.data,
extra: {
invoiceId: parsedInvoiceId.data,
exp: payload.exp,
},
}),
});
} catch (error) {
fastify.log.error({ err: error, invoiceId: parsedInvoiceId.data }, "Audit log write failed");
}
reply.type(invoice.mime_type || "application/octet-stream");
reply.header(
"content-disposition",
`inline; filename=\"${sanitizeFilename(invoice.original_name)}\"`,
);
return reply.send(stream);
});
}
module.exports = {
registerInvoicePoolReadRoutes,
};
@@ -0,0 +1,58 @@
const { pushPaidReimbursementToErp } = require("./erp");
class IntegrationDispatchError extends Error {
constructor({ code, message, retryable, statusCode, response }) {
super(message || code || "integration_dispatch_failed");
this.name = "IntegrationDispatchError";
this.code = code || "integration_dispatch_failed";
this.retryable = typeof retryable === "boolean" ? retryable : true;
this.statusCode = Number.isFinite(statusCode) ? Number(statusCode) : null;
this.response = response ?? null;
}
}
function toDispatchError(result) {
return new IntegrationDispatchError({
code: result?.code,
message: result?.message,
retryable: result?.retryable,
statusCode: result?.httpStatus,
response: result?.response,
});
}
async function dispatchOutboxEvent({ config, eventType, payload }) {
if (eventType === "erp.reimbursement.paid") {
const result = await pushPaidReimbursementToErp(config, payload);
if (!result.ok) {
throw toDispatchError(result);
}
return {
channel: "erp",
code: result.code,
response: result.response ?? null,
};
}
if (eventType === "notification.im") {
return {
channel: "im",
code: "mock_sent",
response: {
channelType: payload.channelType,
},
};
}
throw new IntegrationDispatchError({
code: "unsupported_outbox_event",
message: `unsupported_outbox_event:${eventType}`,
retryable: false,
});
}
module.exports = {
IntegrationDispatchError,
dispatchOutboxEvent,
};
+157
查看文件
@@ -0,0 +1,157 @@
function buildErpPayload(input) {
return {
reimbursementId: input.reimbursement.id,
formNumber: input.reimbursement.form_number,
ownerEmployeeId: input.reimbursement.owner_id,
submitterEmployeeId: input.reimbursement.submitter_id,
totalAmount: input.reimbursement.total_amount?.toString?.() ?? null,
paymentVoucherNo: input.reimbursement.payment_voucher_no ?? null,
paymentDate: input.reimbursement.payment_date
? new Date(input.reimbursement.payment_date).toISOString().slice(0, 10)
: null,
paidAt: input.reimbursement.paid_at ? new Date(input.reimbursement.paid_at).toISOString() : null,
};
}
function normalizeProvider(config) {
return String(config.erpSyncProvider ?? "mock").trim().toLowerCase() || "mock";
}
function buildAuthHeaders(config) {
const token = String(config.erpSyncAuthToken ?? "").trim();
if (!token) {
return {};
}
return {
authorization: `Bearer ${token}`,
};
}
async function postToErpHttp(config, payload) {
const endpoint = String(config.erpSyncEndpoint ?? "").trim();
if (!endpoint) {
return {
ok: false,
code: "erp_sync_endpoint_missing",
message: "ERP sync endpoint missing",
retryable: false,
};
}
const timeoutMs = Math.max(100, Number(config.erpSyncTimeoutMs ?? 5000));
const controller = new AbortController();
const timer = setTimeout(() => {
controller.abort();
}, timeoutMs);
try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"content-type": "application/json",
...buildAuthHeaders(config),
},
body: JSON.stringify(payload),
signal: controller.signal,
});
let responseBody = null;
const contentType = response.headers.get("content-type") || "";
if (contentType.includes("application/json")) {
try {
responseBody = await response.json();
} catch {
responseBody = null;
}
} else {
try {
responseBody = await response.text();
} catch {
responseBody = null;
}
}
if (response.ok) {
return {
ok: true,
code: "http_synced",
message: "ERP synced",
response: {
status: response.status,
body: responseBody,
},
};
}
const retryable = response.status >= 500;
return {
ok: false,
code: retryable ? "erp_sync_http_5xx" : "erp_sync_http_4xx",
message: `ERP sync HTTP ${response.status}`,
retryable,
httpStatus: response.status,
response: {
status: response.status,
body: responseBody,
},
};
} catch (error) {
if (error?.name === "AbortError") {
return {
ok: false,
code: "erp_sync_timeout",
message: `ERP sync timeout (${timeoutMs}ms)`,
retryable: true,
};
}
return {
ok: false,
code: "erp_sync_network_error",
message: String(error?.message ?? error ?? "ERP sync network error"),
retryable: true,
};
} finally {
clearTimeout(timer);
}
}
async function pushPaidReimbursementToErp(config, payload) {
if (!config.erpSyncEnabled) {
return {
ok: false,
code: "erp_sync_disabled",
message: "ERP sync disabled",
retryable: false,
};
}
const provider = normalizeProvider(config);
if (provider === "mock") {
return {
ok: true,
code: "mock_synced",
message: "mock ERP synced",
response: {
externalId: `ERP-${payload.formNumber ?? payload.reimbursementId}`,
},
};
}
if (provider === "http") {
return postToErpHttp(config, payload);
}
return {
ok: false,
code: "erp_sync_provider_invalid",
message: `Unsupported ERP sync provider: ${provider}`,
retryable: false,
};
}
module.exports = {
buildErpPayload,
pushPaidReimbursementToErp,
};
+161
查看文件
@@ -0,0 +1,161 @@
const OUTBOX_STATUSES = {
pending: "pending",
processing: "processing",
succeeded: "succeeded",
failed: "failed",
dead_letter: "dead_letter",
};
function nextRetryAt(config, attempts) {
const waitSeconds = Math.max(30, Number(config.integrationOutboxRetrySeconds ?? 120));
const backoff = waitSeconds * Math.max(1, attempts);
return new Date(Date.now() + backoff * 1000);
}
function formatDispatchError(error) {
const code = error?.code ? String(error.code) : null;
const statusCode = Number.isFinite(error?.statusCode) ? Number(error.statusCode) : null;
const message = String(error?.message ?? error ?? "integration_outbox_error").trim();
const parts = [];
if (code) {
parts.push(code);
}
if (statusCode != null) {
parts.push(`HTTP ${statusCode}`);
}
if (message) {
parts.push(message);
}
if (!parts.length) {
return "integration_outbox_error";
}
return parts.join(" | ");
}
async function enqueueIntegrationEvent(prisma, input) {
const dedupeKey = input.dedupeKey ?? null;
const existed =
dedupeKey != null
? await prisma.integrationOutbox.findUnique({
where: {
event_type_dedupe_key: {
event_type: input.eventType,
dedupe_key: dedupeKey,
},
},
select: { id: true, status: true },
})
: null;
if (existed) {
return {
id: existed.id,
status: existed.status,
duplicated: true,
};
}
const created = await prisma.integrationOutbox.create({
data: {
event_type: input.eventType,
status: OUTBOX_STATUSES.pending,
payload: input.payload,
dedupe_key: dedupeKey,
max_attempts: input.maxAttempts,
created_by: input.actorId ?? null,
updated_by: input.actorId ?? null,
},
select: {
id: true,
status: true,
},
});
return {
id: created.id,
status: created.status,
duplicated: false,
};
}
async function fetchPendingOutboxEvents(prisma, options) {
const batchSize = Math.max(1, Number(options.batchSize ?? 20));
const now = new Date();
return prisma.integrationOutbox.findMany({
where: {
status: {
in: [OUTBOX_STATUSES.pending, OUTBOX_STATUSES.failed],
},
OR: [{ next_retry_at: null }, { next_retry_at: { lte: now } }],
},
orderBy: [{ created_at: "asc" }],
take: batchSize,
});
}
async function markOutboxProcessing(prisma, id, actorId) {
return prisma.integrationOutbox.update({
where: { id },
data: {
status: OUTBOX_STATUSES.processing,
updated_by: actorId ?? null,
},
});
}
async function markOutboxSucceeded(prisma, id, actorId) {
return prisma.integrationOutbox.update({
where: { id },
data: {
status: OUTBOX_STATUSES.succeeded,
processed_at: new Date(),
last_error: null,
updated_by: actorId ?? null,
},
});
}
async function markOutboxFailed(prisma, config, item, error, actorId, options = {}) {
const attempts = Number(item.attempts ?? 0) + 1;
const maxAttempts = Math.max(
1,
Number(item.max_attempts ?? config.integrationOutboxMaxAttempts ?? 5),
);
const retryable =
typeof options.retryable === "boolean"
? options.retryable
: typeof error?.retryable === "boolean"
? error.retryable
: true;
const deadByAttempts = retryable && attempts >= maxAttempts;
const deadByPolicy = !retryable;
const dead = deadByPolicy || deadByAttempts;
return prisma.integrationOutbox.update({
where: { id: item.id },
data: {
attempts,
status: dead ? OUTBOX_STATUSES.dead_letter : OUTBOX_STATUSES.failed,
dead_letter_at: dead ? new Date() : null,
next_retry_at: dead ? null : nextRetryAt(config, attempts),
last_error: formatDispatchError(error).slice(0, 500),
updated_by: actorId ?? null,
},
});
}
module.exports = {
OUTBOX_STATUSES,
enqueueIntegrationEvent,
fetchPendingOutboxEvents,
markOutboxProcessing,
markOutboxSucceeded,
markOutboxFailed,
};