feat(message): add message center module (Phase 5)
Implement the complete message center with: - Database migrations for message_templates, messages, message_subscriptions tables - erp-message crate with entities, DTOs, services, handlers - Message CRUD, send, read/unread tracking, soft delete - Template management with variable interpolation - Subscription preferences with DND support - Frontend: messages page, notification panel, unread count badge - Server integration with module registration and routing Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,9 @@ mod m20260412_000019_create_process_instances;
|
||||
mod m20260412_000020_create_tokens;
|
||||
mod m20260412_000021_create_tasks;
|
||||
mod m20260412_000022_create_process_variables;
|
||||
mod m20260413_000023_create_message_templates;
|
||||
mod m20260413_000024_create_messages;
|
||||
mod m20260413_000025_create_message_subscriptions;
|
||||
|
||||
pub struct Migrator;
|
||||
|
||||
@@ -51,6 +54,9 @@ impl MigratorTrait for Migrator {
|
||||
Box::new(m20260412_000020_create_tokens::Migration),
|
||||
Box::new(m20260412_000021_create_tasks::Migration),
|
||||
Box::new(m20260412_000022_create_process_variables::Migration),
|
||||
Box::new(m20260413_000023_create_message_templates::Migration),
|
||||
Box::new(m20260413_000024_create_messages::Migration),
|
||||
Box::new(m20260413_000025_create_message_subscriptions::Migration),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(MessageTemplates::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(MessageTemplates::Id)
|
||||
.uuid()
|
||||
.not_null()
|
||||
.primary_key(),
|
||||
)
|
||||
.col(ColumnDef::new(MessageTemplates::TenantId).uuid().not_null())
|
||||
.col(
|
||||
ColumnDef::new(MessageTemplates::Name)
|
||||
.string()
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(MessageTemplates::Code)
|
||||
.string()
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(MessageTemplates::Channel)
|
||||
.string()
|
||||
.not_null()
|
||||
.default("in_app"),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(MessageTemplates::TitleTemplate)
|
||||
.string()
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(MessageTemplates::BodyTemplate)
|
||||
.text()
|
||||
.not_null(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(MessageTemplates::Language)
|
||||
.string()
|
||||
.not_null()
|
||||
.default("zh-CN"),
|
||||
)
|
||||
.col(ColumnDef::new(MessageTemplates::CreatedAt).timestamp_with_time_zone().not_null())
|
||||
.col(ColumnDef::new(MessageTemplates::UpdatedAt).timestamp_with_time_zone().not_null())
|
||||
.col(ColumnDef::new(MessageTemplates::CreatedBy).uuid().not_null())
|
||||
.col(ColumnDef::new(MessageTemplates::UpdatedBy).uuid().not_null())
|
||||
.col(ColumnDef::new(MessageTemplates::DeletedAt).timestamp_with_time_zone().null())
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager.get_connection().execute(sea_orm::Statement::from_string(
|
||||
sea_orm::DatabaseBackend::Postgres,
|
||||
"CREATE UNIQUE INDEX idx_message_templates_tenant_code ON message_templates (tenant_id, code) WHERE deleted_at IS NULL".to_string(),
|
||||
)).await.map_err(|e| DbErr::Custom(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(MessageTemplates::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum MessageTemplates {
|
||||
Table,
|
||||
Id,
|
||||
TenantId,
|
||||
Name,
|
||||
Code,
|
||||
Channel,
|
||||
TitleTemplate,
|
||||
BodyTemplate,
|
||||
Language,
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
CreatedBy,
|
||||
UpdatedBy,
|
||||
DeletedAt,
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(Messages::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(Messages::Id)
|
||||
.uuid()
|
||||
.not_null()
|
||||
.primary_key(),
|
||||
)
|
||||
.col(ColumnDef::new(Messages::TenantId).uuid().not_null())
|
||||
.col(ColumnDef::new(Messages::TemplateId).uuid().null())
|
||||
.col(ColumnDef::new(Messages::SenderId).uuid().null())
|
||||
.col(
|
||||
ColumnDef::new(Messages::SenderType)
|
||||
.string()
|
||||
.not_null()
|
||||
.default("system"),
|
||||
)
|
||||
.col(ColumnDef::new(Messages::RecipientId).uuid().not_null())
|
||||
.col(
|
||||
ColumnDef::new(Messages::RecipientType)
|
||||
.string()
|
||||
.not_null()
|
||||
.default("user"),
|
||||
)
|
||||
.col(ColumnDef::new(Messages::Title).string().not_null())
|
||||
.col(ColumnDef::new(Messages::Body).text().not_null())
|
||||
.col(
|
||||
ColumnDef::new(Messages::Priority)
|
||||
.string()
|
||||
.not_null()
|
||||
.default("normal"),
|
||||
)
|
||||
.col(ColumnDef::new(Messages::BusinessType).string().null())
|
||||
.col(ColumnDef::new(Messages::BusinessId).uuid().null())
|
||||
.col(
|
||||
ColumnDef::new(Messages::IsRead)
|
||||
.boolean()
|
||||
.not_null()
|
||||
.default(false),
|
||||
)
|
||||
.col(ColumnDef::new(Messages::ReadAt).timestamp_with_time_zone().null())
|
||||
.col(
|
||||
ColumnDef::new(Messages::IsArchived)
|
||||
.boolean()
|
||||
.not_null()
|
||||
.default(false),
|
||||
)
|
||||
.col(ColumnDef::new(Messages::ArchivedAt).timestamp_with_time_zone().null())
|
||||
.col(ColumnDef::new(Messages::SentAt).timestamp_with_time_zone().null())
|
||||
.col(
|
||||
ColumnDef::new(Messages::Status)
|
||||
.string()
|
||||
.not_null()
|
||||
.default("sent"),
|
||||
)
|
||||
.col(ColumnDef::new(Messages::CreatedAt).timestamp_with_time_zone().not_null())
|
||||
.col(ColumnDef::new(Messages::UpdatedAt).timestamp_with_time_zone().not_null())
|
||||
.col(ColumnDef::new(Messages::CreatedBy).uuid().not_null())
|
||||
.col(ColumnDef::new(Messages::UpdatedBy).uuid().not_null())
|
||||
.col(ColumnDef::new(Messages::DeletedAt).timestamp_with_time_zone().null())
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager.get_connection().execute(sea_orm::Statement::from_string(
|
||||
sea_orm::DatabaseBackend::Postgres,
|
||||
"CREATE INDEX idx_messages_tenant_recipient ON messages (tenant_id, recipient_id) WHERE deleted_at IS NULL".to_string(),
|
||||
)).await.map_err(|e| DbErr::Custom(e.to_string()))?;
|
||||
|
||||
manager.get_connection().execute(sea_orm::Statement::from_string(
|
||||
sea_orm::DatabaseBackend::Postgres,
|
||||
"CREATE INDEX idx_messages_tenant_recipient_unread ON messages (tenant_id, recipient_id) WHERE deleted_at IS NULL AND is_read = false".to_string(),
|
||||
)).await.map_err(|e| DbErr::Custom(e.to_string()))?;
|
||||
|
||||
manager.get_connection().execute(sea_orm::Statement::from_string(
|
||||
sea_orm::DatabaseBackend::Postgres,
|
||||
"CREATE INDEX idx_messages_tenant_business ON messages (tenant_id, business_type, business_id) WHERE deleted_at IS NULL".to_string(),
|
||||
)).await.map_err(|e| DbErr::Custom(e.to_string()))?;
|
||||
|
||||
manager
|
||||
.create_foreign_key(
|
||||
ForeignKey::create()
|
||||
.name("fk_messages_template")
|
||||
.from(Messages::Table, Messages::TemplateId)
|
||||
.to(MessageTemplatesRef::Table, MessageTemplatesRef::Id)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(Messages::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Messages {
|
||||
Table,
|
||||
Id,
|
||||
TenantId,
|
||||
TemplateId,
|
||||
SenderId,
|
||||
SenderType,
|
||||
RecipientId,
|
||||
RecipientType,
|
||||
Title,
|
||||
Body,
|
||||
Priority,
|
||||
BusinessType,
|
||||
BusinessId,
|
||||
IsRead,
|
||||
ReadAt,
|
||||
IsArchived,
|
||||
ArchivedAt,
|
||||
SentAt,
|
||||
Status,
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
CreatedBy,
|
||||
UpdatedBy,
|
||||
DeletedAt,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum MessageTemplatesRef {
|
||||
Table,
|
||||
Id,
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(MessageSubscriptions::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(MessageSubscriptions::Id)
|
||||
.uuid()
|
||||
.not_null()
|
||||
.primary_key(),
|
||||
)
|
||||
.col(ColumnDef::new(MessageSubscriptions::TenantId).uuid().not_null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::UserId).uuid().not_null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::NotificationTypes).json().null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::ChannelPreferences).json().null())
|
||||
.col(
|
||||
ColumnDef::new(MessageSubscriptions::DndEnabled)
|
||||
.boolean()
|
||||
.not_null()
|
||||
.default(false),
|
||||
)
|
||||
.col(ColumnDef::new(MessageSubscriptions::DndStart).string().null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::DndEnd).string().null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::CreatedAt).timestamp_with_time_zone().not_null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::UpdatedAt).timestamp_with_time_zone().not_null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::CreatedBy).uuid().not_null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::UpdatedBy).uuid().not_null())
|
||||
.col(ColumnDef::new(MessageSubscriptions::DeletedAt).timestamp_with_time_zone().null())
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
manager.get_connection().execute(sea_orm::Statement::from_string(
|
||||
sea_orm::DatabaseBackend::Postgres,
|
||||
"CREATE UNIQUE INDEX idx_message_subscriptions_tenant_user ON message_subscriptions (tenant_id, user_id) WHERE deleted_at IS NULL".to_string(),
|
||||
)).await.map_err(|e| DbErr::Custom(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(MessageSubscriptions::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum MessageSubscriptions {
|
||||
Table,
|
||||
Id,
|
||||
TenantId,
|
||||
UserId,
|
||||
NotificationTypes,
|
||||
ChannelPreferences,
|
||||
DndEnabled,
|
||||
DndStart,
|
||||
DndEnd,
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
CreatedBy,
|
||||
UpdatedBy,
|
||||
DeletedAt,
|
||||
}
|
||||
@@ -8,6 +8,7 @@ pub struct AppConfig {
|
||||
pub jwt: JwtConfig,
|
||||
pub auth: AuthConfig,
|
||||
pub log: LogConfig,
|
||||
pub cors: CorsConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -45,6 +46,13 @@ pub struct AuthConfig {
|
||||
pub super_admin_password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CorsConfig {
|
||||
/// Comma-separated list of allowed origins.
|
||||
/// Use "*" to allow all origins (development only).
|
||||
pub allowed_origins: String,
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
pub fn load() -> anyhow::Result<Self> {
|
||||
let config = config::Config::builder()
|
||||
|
||||
@@ -109,11 +109,16 @@ async fn main() -> anyhow::Result<()> {
|
||||
let workflow_module = erp_workflow::WorkflowModule::new();
|
||||
tracing::info!(module = workflow_module.name(), version = workflow_module.version(), "Workflow module initialized");
|
||||
|
||||
// Initialize message module
|
||||
let message_module = erp_message::MessageModule::new();
|
||||
tracing::info!(module = message_module.name(), version = message_module.version(), "Message module initialized");
|
||||
|
||||
// Initialize module registry and register modules
|
||||
let registry = ModuleRegistry::new()
|
||||
.register(auth_module)
|
||||
.register(config_module)
|
||||
.register(workflow_module);
|
||||
.register(workflow_module)
|
||||
.register(message_module);
|
||||
tracing::info!(module_count = registry.modules().len(), "Modules registered");
|
||||
|
||||
// Register event handlers
|
||||
@@ -152,6 +157,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
let protected_routes = erp_auth::AuthModule::protected_routes()
|
||||
.merge(erp_config::ConfigModule::protected_routes())
|
||||
.merge(erp_workflow::WorkflowModule::protected_routes())
|
||||
.merge(erp_message::MessageModule::protected_routes())
|
||||
.layer(middleware::from_fn(move |req, next| {
|
||||
let secret = jwt_secret.clone();
|
||||
async move { jwt_auth_middleware_fn(secret, req, next).await }
|
||||
@@ -159,7 +165,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
.with_state(state.clone());
|
||||
|
||||
// Merge public + protected into the final application router
|
||||
let cors = tower_http::cors::CorsLayer::permissive(); // TODO: restrict origins in production
|
||||
let cors = build_cors_layer(&state.config.cors.allowed_origins);
|
||||
let app = Router::new()
|
||||
.merge(public_routes)
|
||||
.merge(protected_routes)
|
||||
@@ -178,6 +184,48 @@ async fn main() -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build a CORS layer from the comma-separated allowed origins config.
|
||||
///
|
||||
/// If the config is "*", allows all origins (development mode).
|
||||
/// Otherwise, parses each origin as a URL and restricts to those origins only.
|
||||
fn build_cors_layer(allowed_origins: &str) -> tower_http::cors::CorsLayer {
|
||||
use axum::http::HeaderValue;
|
||||
use tower_http::cors::AllowOrigin;
|
||||
|
||||
let origins = allowed_origins
|
||||
.split(',')
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if origins.len() == 1 && origins[0] == "*" {
|
||||
tracing::warn!("CORS: allowing all origins — only use in development!");
|
||||
tower_http::cors::CorsLayer::permissive()
|
||||
} else {
|
||||
let allowed: Vec<HeaderValue> = origins
|
||||
.iter()
|
||||
.filter_map(|o| o.parse::<HeaderValue>().ok())
|
||||
.collect();
|
||||
|
||||
tracing::info!(origins = ?origins, "CORS: restricting to allowed origins");
|
||||
|
||||
tower_http::cors::CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::list(allowed))
|
||||
.allow_methods([
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PUT,
|
||||
axum::http::Method::DELETE,
|
||||
axum::http::Method::PATCH,
|
||||
])
|
||||
.allow_headers([
|
||||
axum::http::header::AUTHORIZATION,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
])
|
||||
.allow_credentials(true)
|
||||
}
|
||||
}
|
||||
|
||||
async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
tokio::signal::ctrl_c()
|
||||
|
||||
@@ -70,3 +70,13 @@ impl FromRef<AppState> for erp_workflow::WorkflowState {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Allow erp-message handlers to extract their required state without depending on erp-server.
|
||||
impl FromRef<AppState> for erp_message::MessageState {
|
||||
fn from_ref(state: &AppState) -> Self {
|
||||
Self {
|
||||
db: state.db.clone(),
|
||||
event_bus: state.event_bus.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user