refactor: migrate to clean architecture with trait-based DI (v0.2.0)

Complete architectural overhaul across all 12 crates:

- Replace validator crate with zod-rs for all DTO validation
- Replace manual pagination with paginator-rs/paginator-sea-orm
- Migrate all modules (iam, cms, gacha, dimentorin) to clean architecture:
  domain → application → infrastructure layers
- Introduce trait-based DI (Arc<dyn Trait>) at every layer for repositories and services
- Delete all v1/ legacy SurrealDB-era code across every crate
- Replace opaque response helpers with typed IntoResponse structs (ApiSuccess, ApiCreated, ApiPaginated, ApiMessage)
- Remove dual_mode_repository, migration_validation_errors, validator.rs dead code
- Zero cargo clippy warnings; release build clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
maulanasdqn
2026-04-02 13:39:52 +07:00
co-authored by Claude Sonnet 4.6
parent 1b3366d735
commit e432a1a743
379 changed files with 9013 additions and 30532 deletions
@@ -0,0 +1,40 @@
use std::sync::Arc;
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::gacha_items::domain::{GachaItemEntity, GachaItemRepository, GachaItemService};
pub struct GachaItemServiceImpl {
repo: Arc<dyn GachaItemRepository>,
}
impl GachaItemServiceImpl {
pub fn new(repo: Arc<dyn GachaItemRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl GachaItemService for GachaItemServiceImpl {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<GachaItemEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: Uuid) -> Result<GachaItemEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(&self, entity: GachaItemEntity) -> Result<(), AppError> {
self.repo.create(entity).await
}
async fn update(&self, entity: GachaItemEntity) -> Result<(), AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
}
@@ -0,0 +1,3 @@
pub mod gacha_item_service;
pub use gacha_item_service::GachaItemServiceImpl;
@@ -0,0 +1,23 @@
use chrono::{DateTime, Utc};
use serde_json::Value;
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct GachaItemEntity {
pub id: Uuid,
pub item_code: String,
pub name: String,
pub description: String,
pub rarity: String,
pub type_: String,
pub category: String,
pub value: i32,
pub weight: f64,
pub stock: i32,
pub is_limited: bool,
pub metadata: Option<Value>,
pub is_deleted: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub deleted_at: Option<DateTime<Utc>>,
}
@@ -0,0 +1,7 @@
pub mod gacha_item;
pub mod repository;
pub mod service;
pub use gacha_item::GachaItemEntity;
pub use repository::GachaItemRepository;
pub use service::GachaItemService;
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_item::GachaItemEntity;
#[async_trait]
pub trait GachaItemRepository: Send + Sync {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<GachaItemEntity>, AppError>;
async fn find_by_id(&self, id: Uuid) -> Result<GachaItemEntity, AppError>;
async fn create(&self, entity: GachaItemEntity) -> Result<(), AppError>;
async fn update(&self, entity: GachaItemEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_item::GachaItemEntity;
#[async_trait]
pub trait GachaItemService: Send + Sync {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<GachaItemEntity>, AppError>;
async fn get(&self, id: Uuid) -> Result<GachaItemEntity, AppError>;
async fn create(&self, entity: GachaItemEntity) -> Result<(), AppError>;
async fn update(&self, entity: GachaItemEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,92 @@
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use utoipa::ToSchema;
use uuid::Uuid;
use crate::gacha_items::domain::gacha_item::GachaItemEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaItemCreateRequestDto {
pub item_code: String,
pub name: String,
pub description: String,
pub rarity: String,
pub type_: String,
pub category: String,
pub value: i32,
pub weight: f64,
pub stock: i32,
pub is_limited: bool,
pub metadata: Option<Value>,
}
impl ZodValidate for GachaItemCreateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
impl From<GachaItemCreateRequestDto> for GachaItemEntity {
fn from(dto: GachaItemCreateRequestDto) -> Self {
GachaItemEntity {
id: Uuid::new_v4(),
item_code: dto.item_code,
name: dto.name,
description: dto.description,
rarity: dto.rarity,
type_: dto.type_,
category: dto.category,
value: dto.value,
weight: dto.weight,
stock: dto.stock,
is_limited: dto.is_limited,
metadata: dto.metadata,
is_deleted: false,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
deleted_at: None,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaItemUpdateRequestDto {
pub item_code: String,
pub name: String,
pub description: String,
pub rarity: String,
pub type_: String,
pub category: String,
pub value: i32,
pub weight: f64,
pub stock: i32,
pub is_limited: bool,
pub metadata: Option<Value>,
}
impl ZodValidate for GachaItemUpdateRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaItemDto {
pub id: String,
pub name: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<GachaItemEntity> for GachaItemDto {
fn from(e: GachaItemEntity) -> Self {
GachaItemDto {
id: e.id.to_string(),
name: e.name,
is_deleted: e.is_deleted,
created_at: Some(e.created_at.to_rfc3339()),
updated_at: Some(e.updated_at.to_rfc3339()),
}
}
}
@@ -0,0 +1,166 @@
use std::sync::Arc;
use axum::{Extension, extract::Path, http::HeaderMap, response::IntoResponse};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::{ApiSuccess, ApiPaginated, ApiMessage};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_utils::AppError;
use super::dto::{GachaItemCreateRequestDto, GachaItemDto, GachaItemUpdateRequestDto};
use crate::gacha_items::domain::{GachaItemEntity, GachaItemService};
#[utoipa::path(
get,
security(("Bearer" = [])),
path = "/v1/gacha/items",
params(
("page" = Option<i64>, Query, description = "Page number"),
("per_page" = Option<i64>, Query, description = "Items per page"),
("search" = Option<String>, Query, description = "Search keyword"),
("sort_by" = Option<String>, Query, description = "Sort by field"),
("order" = Option<String>, Query, description = "Order ASC or DESC"),
),
responses(
(status = 200, description = "[ADMIN] Get gacha item list")
),
tag = "Gacha"
)]
pub async fn get_gacha_item_list(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaItemService>>,
PaginationQuery(params): PaginationQuery,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadListGachaItems], {
let result = service.list(params).await?;
let mapped = PaginatorResponse {
data: result.data.into_iter().map(GachaItemDto::from).collect::<Vec<_>>(),
meta: result.meta,
};
Ok(ApiPaginated(mapped))
})
}
#[utoipa::path(
get,
security(("Bearer" = [])),
path = "/v1/gacha/items/detail/{id}",
params(
("id" = String, Path, description = "Gacha Item ID")
),
responses(
(status = 200, description = "[ADMIN] Get gacha item by ID", body = ResponseSuccessDto<GachaItemDto>)
),
tag = "Gacha"
)]
pub async fn get_gacha_item_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaItemService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadDetailGachaItems], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let item = service.get(uuid).await?;
Ok(ApiSuccess(GachaItemDto::from(item)))
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/items/create",
request_body = GachaItemCreateRequestDto,
responses(
(status = 201, description = "[ADMIN] Create gacha item")
),
tag = "Gacha"
)]
pub async fn post_create_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaItemService>>,
ValidatedJson(payload): ValidatedJson<GachaItemCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::CreateGachaItems], {
let entity: GachaItemEntity = payload.into();
service.create(entity).await?;
Ok(ApiMessage::created("Gacha item created"))
})
}
#[utoipa::path(
put,
security(("Bearer" = [])),
path = "/v1/gacha/items/update/{id}",
params(
("id" = String, Path, description = "Gacha Item ID")
),
request_body = GachaItemUpdateRequestDto,
responses(
(status = 200, description = "[ADMIN] Update gacha item")
),
tag = "Gacha"
)]
pub async fn put_update_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaItemService>>,
Path(id): Path<String>,
ValidatedJson(payload): ValidatedJson<GachaItemUpdateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::UpdateGachaItems], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let existing = service.get(uuid).await?;
let entity = GachaItemEntity {
id: existing.id,
item_code: payload.item_code,
name: payload.name,
description: payload.description,
rarity: payload.rarity,
type_: payload.type_,
category: payload.category,
value: payload.value,
weight: payload.weight,
stock: payload.stock,
is_limited: payload.is_limited,
metadata: payload.metadata,
is_deleted: existing.is_deleted,
created_at: existing.created_at,
updated_at: chrono::Utc::now(),
deleted_at: existing.deleted_at,
};
service.update(entity).await?;
Ok(ApiMessage::ok("Gacha item updated"))
})
}
#[utoipa::path(
delete,
security(("Bearer" = [])),
path = "/v1/gacha/items/delete/{id}",
params(
("id" = String, Path, description = "Gacha Item ID")
),
responses(
(status = 200, description = "[ADMIN] Delete gacha item (soft delete)")
),
tag = "Gacha"
)]
pub async fn delete_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaItemService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::DeleteGachaItems], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
service.delete(uuid).await?;
Ok(ApiMessage::ok("Gacha item deleted"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::gacha_item_router;
@@ -0,0 +1,26 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, post, put}, Extension};
use sea_orm::DatabaseConnection;
use crate::gacha_items::application::GachaItemServiceImpl;
use crate::gacha_items::domain::GachaItemService;
use crate::gacha_items::infrastructure::persistence::PostgresGachaItemRepository;
use super::handlers::{
delete_gacha_item, get_gacha_item_by_id, get_gacha_item_list,
post_create_gacha_item, put_update_gacha_item,
};
fn build_service(db: DatabaseConnection) -> Arc<dyn GachaItemService> {
let repo = Arc::new(PostgresGachaItemRepository::new(db));
Arc::new(GachaItemServiceImpl::new(repo))
}
pub fn gacha_item_router(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/", get(get_gacha_item_list))
.route("/detail/{id}", get(get_gacha_item_by_id))
.route("/create", post(post_create_gacha_item))
.route("/update/{id}", put(put_update_gacha_item))
.route("/delete/{id}", delete(delete_gacha_item))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_gacha_item_repository;
pub use postgres_gacha_item_repository::PostgresGachaItemRepository;
@@ -0,0 +1,170 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, QueryOrder, PaginatorTrait};
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::gacha::gacha_items::{
Entity as GachaItemsEntity, Column as GachaItemsColumn,
ActiveModel as GachaItemsActiveModel, Model as GachaItemsModel,
};
use crate::gacha_items::domain::{gacha_item::GachaItemEntity, repository::GachaItemRepository};
fn to_entity(model: GachaItemsModel) -> GachaItemEntity {
GachaItemEntity {
id: model.id,
item_code: model.item_code,
name: model.name,
description: model.description,
rarity: model.rarity,
type_: model.type_,
category: model.category,
value: model.value,
weight: model.weight,
stock: model.stock,
is_limited: model.is_limited,
metadata: model.metadata,
is_deleted: model.deleted_at.is_some(),
created_at: model.created_at,
updated_at: model.updated_at,
deleted_at: model.deleted_at,
}
}
pub struct PostgresGachaItemRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresGachaItemRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl GachaItemRepository for PostgresGachaItemRepository {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<GachaItemEntity>, AppError> {
let page = params.page.max(1);
let per_page = params.per_page.clamp(1, 100);
let mut query = GachaItemsEntity::find()
.filter(GachaItemsColumn::DeletedAt.is_null());
if let Some(ref search) = params.search {
query = query.filter(GachaItemsColumn::Name.contains(&search.query));
}
query = match params.sort_by.as_deref() {
Some("name") => match params.sort_direction {
Some(SortDirection::Desc) => query.order_by(GachaItemsColumn::Name, Order::Desc),
_ => query.order_by(GachaItemsColumn::Name, Order::Asc),
},
_ => match params.sort_direction {
Some(SortDirection::Asc) => query.order_by(GachaItemsColumn::CreatedAt, Order::Asc),
_ => query.order_by(GachaItemsColumn::CreatedAt, Order::Desc),
},
};
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
let total = paginator
.num_items()
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let items = paginator
.fetch_page((page - 1) as u64)
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let data = items.into_iter().map(to_entity).collect();
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
Ok(PaginatorResponse { data, meta })
}
async fn find_by_id(&self, id: Uuid) -> Result<GachaItemEntity, AppError> {
let item = GachaItemsEntity::find_by_id(id)
.filter(GachaItemsColumn::DeletedAt.is_null())
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha item not found".to_string()))?;
Ok(to_entity(item))
}
async fn create(&self, entity: GachaItemEntity) -> Result<(), AppError> {
let active_model = GachaItemsActiveModel {
id: ActiveValue::Set(entity.id),
item_code: ActiveValue::Set(entity.item_code),
name: ActiveValue::Set(entity.name),
description: ActiveValue::Set(entity.description),
rarity: ActiveValue::Set(entity.rarity),
type_: ActiveValue::Set(entity.type_),
category: ActiveValue::Set(entity.category),
value: ActiveValue::Set(entity.value),
weight: ActiveValue::Set(entity.weight),
stock: ActiveValue::Set(entity.stock),
is_limited: ActiveValue::Set(entity.is_limited),
metadata: ActiveValue::Set(entity.metadata),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::Set(None),
};
GachaItemsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn update(&self, entity: GachaItemEntity) -> Result<(), AppError> {
let mut active_model: GachaItemsActiveModel = GachaItemsEntity::find_by_id(entity.id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha item not found".to_string()))?
.into();
active_model.item_code = ActiveValue::Set(entity.item_code);
active_model.name = ActiveValue::Set(entity.name);
active_model.description = ActiveValue::Set(entity.description);
active_model.rarity = ActiveValue::Set(entity.rarity);
active_model.type_ = ActiveValue::Set(entity.type_);
active_model.category = ActiveValue::Set(entity.category);
active_model.value = ActiveValue::Set(entity.value);
active_model.weight = ActiveValue::Set(entity.weight);
active_model.stock = ActiveValue::Set(entity.stock);
active_model.is_limited = ActiveValue::Set(entity.is_limited);
active_model.metadata = ActiveValue::Set(entity.metadata);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
let mut active_model: GachaItemsActiveModel = GachaItemsEntity::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha item not found".to_string()))?
.into();
active_model.deleted_at = ActiveValue::Set(Some(chrono::Utc::now()));
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod application;
pub mod domain;
pub mod infrastructure;
pub use infrastructure::http::gacha_item_router;