Files
erp/wiki/erp-core.md
iven 9568dd7875 chore: apply cargo fmt across workspace and update docs
- Run cargo fmt on all Rust crates for consistent formatting
- Update CLAUDE.md with WASM plugin commands and dev.ps1 instructions
- Update wiki: add WASM plugin architecture, rewrite dev environment docs
- Minor frontend cleanup (unused imports)
2026-04-15 00:49:20 +08:00

3.0 KiB
Raw Permalink Blame History

erp-core

设计思想

erp-core 是整个 ERP 平台的 L1 基础层,所有业务模块的唯一共同依赖。它的职责是定义跨模块共享的契约,而非实现业务逻辑。

核心设计决策:

  • AppError 统一错误体系 — 6 种错误变体映射到 HTTP 状态码,业务 crate 只需 ? 传播错误,由 Axum IntoResponse 自动转换
  • EventBus 进程内广播 — 用 tokio::sync::broadcast 实现发布/订阅,模块间零耦合通信
  • ErpModule 插件 trait — 每个业务模块实现此 traitModuleRegistry 统一注册路由和事件处理器
  • BaseFields 强制多租户 — 所有实体的基础字段模板,确保 tenant_id 从第一天就存在

代码逻辑

错误处理链

业务 crate (thiserror) → AppError → IntoResponse → HTTP JSON 响应
数据库 (sea_orm::DbErr) → From 转换 → AppError (自动识别 duplicate key → Conflict)

错误响应统一格式:{ "error": "not_found", "message": "资源不存在", "details": null }

事件总线

发布者: EventBus::publish(DomainEvent) → broadcast channel
订阅者: EventBus::subscribe() → Receiver<DomainEvent>
事件字段: id(UUIDv7), event_type("user.created"), tenant_id, payload(JSON), timestamp, correlation_id

事件类型命名规则:{模块}.{动作}user.created, workflow.task.completed

模块注册

业务模块实现 ErpModule trait → ModuleRegistry::register() →
  build_router(): 折叠所有模块的 register_routes() → Axum Router
  register_handlers(): 注册所有模块的事件处理器 → EventBus

共享类型

  • TenantContext — 中间件注入的租户上下文tenant_id, user_id, roles, permissions
  • Pagination / PaginatedResponse<T> — 分页查询标准化(每页上限 100
  • ApiResponse<T> — API 统一信封 { success, data, message }

关联模块

  • erp-server — 消费所有 erp-core 类型和 trait是唯一组装点
  • erp-auth — 实现 ErpModule trait发布认证事件
  • erp-workflow — 实现 ErpModule trait订阅业务事件
  • erp-message — 实现 ErpModule trait订阅通知事件
  • erp-config — 实现 ErpModule trait
  • database — 迁移表结构必须与 BaseFields 对齐
  • wasm-plugin — WASM 插件通过 Host Bridge 桥接 EventBus

关键文件

文件 职责
crates/erp-core/src/error.rs AppError 定义、HTTP 映射、From 转换
crates/erp-core/src/events.rs DomainEvent、EventBus、EventHandler trait
crates/erp-core/src/module.rs ErpModule trait、ModuleRegistry
crates/erp-core/src/types.rs BaseFields、Pagination、ApiResponse、TenantContext
crates/erp-core/src/lib.rs 模块导出入口

当前状态

已实现Phase 1 可用。 但以下部分尚未被 erp-server 集成:

  • ModuleRegistry 未在 main.rs 中使用
  • EventBus 未创建实例
  • TenantContext 未通过中间件注入