feat: implement on_tenant_created/deleted hooks and update ErpModule trait

- ErpModule trait hooks now accept db and event_bus parameters
- AuthModule.on_tenant_created: seeds default roles, permissions,
  and admin user for new tenants using existing seed_tenant_auth()
- AuthModule.on_tenant_deleted: soft-deletes all users for the tenant
- Updated all other modules (config, workflow, message) to match
  the new trait signature
This commit is contained in:
iven
2026-04-15 01:27:33 +08:00
parent e44d6063be
commit d8a0ac7519
5 changed files with 94 additions and 14 deletions

View File

@@ -136,13 +136,53 @@ impl ErpModule for AuthModule {
// Auth 模块暂无跨模块事件订阅需求
}
async fn on_tenant_created(&self, _tenant_id: Uuid) -> AppResult<()> {
// TODO: 创建默认角色和管理员用户
async fn on_tenant_created(
&self,
tenant_id: Uuid,
db: &sea_orm::DatabaseConnection,
_event_bus: &EventBus,
) -> AppResult<()> {
let password = std::env::var("ERP__SUPER_ADMIN_PASSWORD")
.unwrap_or_else(|_| "Admin@2026".to_string());
crate::service::seed::seed_tenant_auth(db, tenant_id, &password)
.await
.map_err(|e| erp_core::error::AppError::Internal(e.to_string()))?;
tracing::info!(tenant_id = %tenant_id, "Tenant auth initialized");
Ok(())
}
async fn on_tenant_deleted(&self, _tenant_id: Uuid) -> AppResult<()> {
// TODO: 软删除该租户下所有用户
async fn on_tenant_deleted(
&self,
tenant_id: Uuid,
db: &sea_orm::DatabaseConnection,
) -> AppResult<()> {
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, Set};
use chrono::Utc;
let now = Utc::now();
// 软删除该租户下所有用户
let users = crate::entity::user::Entity::find()
.filter(crate::entity::user::Column::TenantId.eq(tenant_id))
.filter(crate::entity::user::Column::DeletedAt.is_null())
.all(db)
.await
.map_err(|e| erp_core::error::AppError::Internal(e.to_string()))?;
for user_model in users {
let current_version = user_model.version;
let active: crate::entity::user::ActiveModel = user_model.into();
let mut to_update: crate::entity::user::ActiveModel = active;
to_update.deleted_at = Set(Some(now));
to_update.updated_at = Set(now);
to_update.version = Set(current_version + 1);
let _ = to_update
.update(db)
.await
.map_err(|e| erp_core::error::AppError::Internal(e.to_string()))?;
}
tracing::info!(tenant_id = %tenant_id, "Tenant users soft-deleted");
Ok(())
}