feat(core): add audit log infrastructure (Phase 6)

- Add audit_logs database migration with indexes
- Add AuditLog struct in erp-core with builder pattern
- Support old/new value tracking, IP address, user agent

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
iven
2026-04-11 12:31:27 +08:00
parent c0523e19b4
commit bddd33ac2f
4 changed files with 138 additions and 0 deletions

View File

@@ -25,6 +25,7 @@ mod m20260412_000022_create_process_variables;
mod m20260413_000023_create_message_templates;
mod m20260413_000024_create_messages;
mod m20260413_000025_create_message_subscriptions;
mod m20260413_000026_create_audit_logs;
pub struct Migrator;
@@ -57,6 +58,7 @@ impl MigratorTrait for Migrator {
Box::new(m20260413_000023_create_message_templates::Migration),
Box::new(m20260413_000024_create_messages::Migration),
Box::new(m20260413_000025_create_message_subscriptions::Migration),
Box::new(m20260413_000026_create_audit_logs::Migration),
]
}
}

View File

@@ -0,0 +1,68 @@
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(AuditLogs::Table)
.if_not_exists()
.col(
ColumnDef::new(AuditLogs::Id)
.uuid()
.not_null()
.primary_key(),
)
.col(ColumnDef::new(AuditLogs::TenantId).uuid().not_null())
.col(ColumnDef::new(AuditLogs::UserId).uuid().null())
.col(ColumnDef::new(AuditLogs::Action).string().not_null())
.col(ColumnDef::new(AuditLogs::ResourceType).string().not_null())
.col(ColumnDef::new(AuditLogs::ResourceId).uuid().null())
.col(ColumnDef::new(AuditLogs::OldValue).json().null())
.col(ColumnDef::new(AuditLogs::NewValue).json().null())
.col(ColumnDef::new(AuditLogs::IpAddress).string().null())
.col(ColumnDef::new(AuditLogs::UserAgent).text().null())
.col(ColumnDef::new(AuditLogs::CreatedAt).timestamp_with_time_zone().not_null())
.to_owned(),
)
.await?;
manager.get_connection().execute(sea_orm::Statement::from_string(
sea_orm::DatabaseBackend::Postgres,
"CREATE INDEX idx_audit_logs_tenant ON audit_logs (tenant_id)".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_audit_logs_resource ON audit_logs (resource_type, resource_id)".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(AuditLogs::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum AuditLogs {
Table,
Id,
TenantId,
UserId,
Action,
ResourceType,
ResourceId,
OldValue,
NewValue,
IpAddress,
UserAgent,
CreatedAt,
}