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
+8 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "imphnen-gacha"
version = "0.1.0"
version = "0.2.0"
edition = "2024"
[dependencies]
@@ -14,7 +14,8 @@ serde_json.workspace = true
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
validator.workspace = true
zod-rs.workspace = true
zod-rs-util.workspace = true
axum-test.workspace = true
rand.workspace = true
tokio.workspace = true
@@ -27,3 +28,8 @@ log.workspace = true
tracing.workspace = true
sea-orm.workspace = true
uuid = "1.18"
paginator-rs.workspace = true
paginator-utils.workspace = true
paginator-sea-orm.workspace = true
paginator-axum.workspace = true
async-trait.workspace = true
@@ -0,0 +1,28 @@
use std::sync::Arc;
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::gacha_claims::domain::{
GachaClaimDetail, GachaClaimEntity, GachaClaimRepository, GachaClaimService,
};
pub struct GachaClaimServiceImpl {
repo: Arc<dyn GachaClaimRepository>,
}
impl GachaClaimServiceImpl {
pub fn new(repo: Arc<dyn GachaClaimRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl GachaClaimService for GachaClaimServiceImpl {
async fn get_claim(&self, id: Uuid) -> Result<GachaClaimDetail, AppError> {
self.repo.find_by_id(id).await
}
async fn create_claim(&self, entity: GachaClaimEntity) -> Result<(), AppError> {
self.repo.create(entity).await
}
}
@@ -0,0 +1,3 @@
pub mod gacha_claim_service;
pub use gacha_claim_service::GachaClaimServiceImpl;
@@ -0,0 +1,33 @@
use chrono::{DateTime, Utc};
use serde_json::Value;
use uuid::Uuid;
use imphnen_entities::UsersDetailQueryDto;
use crate::gacha_items::domain::gacha_item::GachaItemEntity;
#[derive(Clone, Debug)]
pub struct GachaClaimEntity {
pub id: Uuid,
pub user_id: Uuid,
pub gacha_item_id: Uuid,
pub claim_id: Uuid,
pub claim_type: String,
pub status: String,
pub quantity: i32,
pub metadata: Option<Value>,
pub is_deleted: bool,
pub claimed_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub deleted_at: Option<DateTime<Utc>>,
}
/// Denormalized struct for claim detail responses with nested user and item data.
#[derive(Clone, Debug)]
pub struct GachaClaimDetail {
pub id: Uuid,
pub user: UsersDetailQueryDto,
pub item: GachaItemEntity,
pub is_deleted: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -0,0 +1,7 @@
pub mod gacha_claim;
pub mod repository;
pub mod service;
pub use gacha_claim::{GachaClaimDetail, GachaClaimEntity};
pub use repository::GachaClaimRepository;
pub use service::GachaClaimService;
@@ -0,0 +1,10 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_claim::{GachaClaimDetail, GachaClaimEntity};
#[async_trait]
pub trait GachaClaimRepository: Send + Sync {
async fn find_by_id(&self, id: Uuid) -> Result<GachaClaimDetail, AppError>;
async fn create(&self, entity: GachaClaimEntity) -> Result<(), AppError>;
}
@@ -0,0 +1,10 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_claim::{GachaClaimDetail, GachaClaimEntity};
#[async_trait]
pub trait GachaClaimService: Send + Sync {
async fn get_claim(&self, id: Uuid) -> Result<GachaClaimDetail, AppError>;
async fn create_claim(&self, entity: GachaClaimEntity) -> Result<(), AppError>;
}
@@ -0,0 +1,41 @@
use imphnen_libs::ZodValidate;
use imphnen_iam::users::infrastructure::http::dto::UsersDetailItemDto;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::gacha_claims::domain::gacha_claim::GachaClaimDetail;
use crate::gacha_items::infrastructure::http::dto::GachaItemDto;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaClaimCreateRequestDto {
pub user_id: String,
pub item_id: String,
}
impl ZodValidate for GachaClaimCreateRequestDto {
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 GachaClaimDetailDto {
pub id: String,
pub user: UsersDetailItemDto,
pub item: GachaItemDto,
pub is_deleted: bool,
pub created_at: String,
pub updated_at: String,
}
impl From<GachaClaimDetail> for GachaClaimDetailDto {
fn from(detail: GachaClaimDetail) -> Self {
GachaClaimDetailDto {
id: detail.id.to_string(),
user: UsersDetailItemDto::from(&detail.user),
item: GachaItemDto::from(detail.item),
is_deleted: detail.is_deleted,
created_at: detail.created_at.to_rfc3339(),
updated_at: detail.updated_at.to_rfc3339(),
}
}
}
@@ -0,0 +1,77 @@
use std::sync::Arc;
use axum::{Extension, extract::Path, http::HeaderMap, response::IntoResponse};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::{ApiSuccess, ApiMessage};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_utils::AppError;
use uuid::Uuid;
use super::dto::{GachaClaimCreateRequestDto, GachaClaimDetailDto};
use crate::gacha_claims::domain::{GachaClaimEntity, GachaClaimService};
#[utoipa::path(
get,
security(("Bearer" = [])),
path = "/v1/gacha/claims/detail/{id}",
params(
("id" = String, Path, description = "Gacha Claim ID")
),
responses(
(status = 200, description = "[ADMIN] Get gacha claim by ID", body = ResponseSuccessDto<GachaClaimDetailDto>)
),
tag = "Gacha"
)]
pub async fn get_gacha_claim_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaClaimService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadDetailGachaClaims], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let detail = service.get_claim(uuid).await?;
Ok(ApiSuccess(GachaClaimDetailDto::from(detail)))
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/claims/create",
request_body = GachaClaimCreateRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new gacha claim")
),
tag = "Gacha"
)]
pub async fn post_create_gacha_claim(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaClaimService>>,
ValidatedJson(payload): ValidatedJson<GachaClaimCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::CreateGachaClaims], {
let user_id = Uuid::parse_str(&payload.user_id)
.map_err(|e| AppError::BadRequestError(format!("Invalid user_id UUID: {e}")))?;
let item_id = Uuid::parse_str(&payload.item_id)
.map_err(|e| AppError::BadRequestError(format!("Invalid item_id UUID: {e}")))?;
let entity = GachaClaimEntity {
id: Uuid::new_v4(),
user_id,
gacha_item_id: item_id,
claim_id: Uuid::new_v4(),
claim_type: "standard".to_string(),
status: "claimed".to_string(),
quantity: 1,
metadata: None,
is_deleted: false,
claimed_at: chrono::Utc::now(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
deleted_at: None,
};
service.create_claim(entity).await?;
Ok(ApiMessage::created("Gacha claim created"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::gacha_claim_router;
@@ -0,0 +1,20 @@
use std::sync::Arc;
use axum::{Router, routing::{get, post}, Extension};
use sea_orm::DatabaseConnection;
use crate::gacha_claims::application::GachaClaimServiceImpl;
use crate::gacha_claims::domain::GachaClaimService;
use crate::gacha_claims::infrastructure::persistence::PostgresGachaClaimRepository;
use super::handlers::{get_gacha_claim_by_id, post_create_gacha_claim};
fn build_service(db: DatabaseConnection, state: std::sync::Arc<imphnen_libs::AppState>) -> Arc<dyn GachaClaimService> {
let repo = Arc::new(PostgresGachaClaimRepository::new(db, state));
Arc::new(GachaClaimServiceImpl::new(repo))
}
pub fn gacha_claim_router(db: DatabaseConnection, state: std::sync::Arc<imphnen_libs::AppState>) -> Router {
let service = build_service(db, state);
Router::new()
.route("/detail/{id}", get(get_gacha_claim_by_id))
.route("/create", post(post_create_gacha_claim))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_gacha_claim_repository;
pub use postgres_gacha_claim_repository::PostgresGachaClaimRepository;
@@ -0,0 +1,105 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::ActiveValue;
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::gacha::gacha_claims::{
Entity as GachaClaimsEntity, ActiveModel as GachaClaimsActiveModel,
};
use imphnen_entities::seaorm::gacha::gacha_items::Entity as GachaItemsEntity;
use imphnen_libs::AppState;
use crate::gacha_claims::domain::{
gacha_claim::{GachaClaimDetail, GachaClaimEntity},
repository::GachaClaimRepository,
};
use crate::gacha_items::domain::gacha_item::GachaItemEntity;
pub struct PostgresGachaClaimRepository {
db: Arc<DatabaseConnection>,
state: Arc<AppState>,
}
impl PostgresGachaClaimRepository {
pub fn new(db: DatabaseConnection, state: Arc<AppState>) -> Self {
Self {
db: Arc::new(db),
state,
}
}
}
#[async_trait]
impl GachaClaimRepository for PostgresGachaClaimRepository {
async fn find_by_id(&self, id: Uuid) -> Result<GachaClaimDetail, AppError> {
let claim = GachaClaimsEntity::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha claim not found".to_string()))?;
let user = self.state.user_lookup_service
.get_user_by_id(claim.user_id, self.state.as_ref())
.await
.map(|info| info.basic_info)
.map_err(|e| AppError::InternalServerError(format!("Failed to fetch user: {e}")))?;
let item_model = GachaItemsEntity::find_by_id(claim.gacha_item_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()))?;
let item = GachaItemEntity {
id: item_model.id,
item_code: item_model.item_code,
name: item_model.name,
description: item_model.description,
rarity: item_model.rarity,
type_: item_model.type_,
category: item_model.category,
value: item_model.value,
weight: item_model.weight,
stock: item_model.stock,
is_limited: item_model.is_limited,
metadata: item_model.metadata,
is_deleted: item_model.deleted_at.is_some(),
created_at: item_model.created_at,
updated_at: item_model.updated_at,
deleted_at: item_model.deleted_at,
};
Ok(GachaClaimDetail {
id: claim.id,
user,
item,
is_deleted: claim.deleted_at.is_some(),
created_at: claim.created_at,
updated_at: claim.updated_at,
})
}
async fn create(&self, entity: GachaClaimEntity) -> Result<(), AppError> {
let active_model = GachaClaimsActiveModel {
id: ActiveValue::Set(entity.id),
user_id: ActiveValue::Set(entity.user_id),
gacha_item_id: ActiveValue::Set(entity.gacha_item_id),
claim_id: ActiveValue::Set(entity.claim_id),
claim_type: ActiveValue::Set(entity.claim_type),
status: ActiveValue::Set(entity.status),
quantity: ActiveValue::Set(entity.quantity),
metadata: ActiveValue::Set(entity.metadata),
created_at: ActiveValue::Set(entity.created_at),
updated_at: ActiveValue::Set(entity.updated_at),
deleted_at: ActiveValue::Set(entity.deleted_at),
claimed_at: ActiveValue::Set(entity.claimed_at),
};
GachaClaimsEntity::insert(active_model)
.exec(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_claim_router;
@@ -0,0 +1,30 @@
use std::sync::Arc;
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::gacha_credits::domain::{GachaCreditEntity, GachaCreditRepository, GachaCreditService};
pub struct GachaCreditServiceImpl {
repo: Arc<dyn GachaCreditRepository>,
}
impl GachaCreditServiceImpl {
pub fn new(repo: Arc<dyn GachaCreditRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl GachaCreditService for GachaCreditServiceImpl {
async fn get_credits(&self, user_id: Uuid) -> Result<Option<GachaCreditEntity>, AppError> {
self.repo.find_by_user_id(user_id).await
}
async fn add_credits(&self, user_id: Uuid, amount: i32) -> Result<(), AppError> {
self.repo.add_credit(user_id, amount).await
}
async fn consume_credit(&self, user_id: Uuid) -> Result<(), AppError> {
self.repo.consume_credit(user_id).await
}
}
@@ -0,0 +1,3 @@
pub mod gacha_credit_service;
pub use gacha_credit_service::GachaCreditServiceImpl;
@@ -0,0 +1,12 @@
use chrono::NaiveDateTime;
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct GachaCreditEntity {
pub id: Uuid,
pub user_id: Uuid,
pub available_rolls: i32,
pub is_deleted: bool,
pub created_at: Option<NaiveDateTime>,
pub updated_at: Option<NaiveDateTime>,
}
@@ -0,0 +1,7 @@
pub mod gacha_credit;
pub mod repository;
pub mod service;
pub use gacha_credit::GachaCreditEntity;
pub use repository::GachaCreditRepository;
pub use service::GachaCreditService;
@@ -0,0 +1,11 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_credit::GachaCreditEntity;
#[async_trait]
pub trait GachaCreditRepository: Send + Sync {
async fn find_by_user_id(&self, user_id: Uuid) -> Result<Option<GachaCreditEntity>, AppError>;
async fn add_credit(&self, user_id: Uuid, amount: i32) -> Result<(), AppError>;
async fn consume_credit(&self, user_id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,11 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_credit::GachaCreditEntity;
#[async_trait]
pub trait GachaCreditService: Send + Sync {
async fn get_credits(&self, user_id: Uuid) -> Result<Option<GachaCreditEntity>, AppError>;
async fn add_credits(&self, user_id: Uuid, amount: i32) -> Result<(), AppError>;
async fn consume_credit(&self, user_id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,38 @@
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::gacha_credits::domain::gacha_credit::GachaCreditEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaCreditAddRequestDto {
pub amount: i32,
}
impl ZodValidate for GachaCreditAddRequestDto {
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 GachaCreditDto {
pub id: String,
pub user_id: String,
pub available_rolls: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<GachaCreditEntity> for GachaCreditDto {
fn from(e: GachaCreditEntity) -> Self {
GachaCreditDto {
id: e.id.to_string(),
user_id: e.user_id.to_string(),
available_rolls: e.available_rolls,
is_deleted: e.is_deleted,
created_at: e.created_at.map(|d| d.to_string()),
updated_at: e.updated_at.map(|d| d.to_string()),
}
}
}
@@ -0,0 +1,100 @@
use std::sync::Arc;
use axum::{Extension, http::HeaderMap, response::IntoResponse};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::{ApiSuccess, ApiMessage, extract_email};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_utils::AppError;
use uuid::Uuid;
use super::dto::{GachaCreditAddRequestDto, GachaCreditDto};
use crate::gacha_credits::domain::GachaCreditService;
#[utoipa::path(
get,
security(("Bearer" = [])),
path = "/v1/gacha/credits",
responses(
(status = 200, description = "[ADMIN] Get current user credits", body = ResponseSuccessDto<GachaCreditDto>)
),
tag = "Gacha"
)]
pub async fn get_user_credits(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaCreditService>>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers.clone(), state, [PermissionsEnum::ReadDetailGachaItems], {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Unauthorized".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user = user_info.basic_info;
let user_id = Uuid::parse_str(&user.id)
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
match service.get_credits(user_id).await? {
Some(credit) => Ok(ApiSuccess(GachaCreditDto::from(credit))),
None => Ok(ApiSuccess(GachaCreditDto {
id: "".to_string(),
user_id: user.id,
available_rolls: 0,
is_deleted: false,
created_at: None,
updated_at: None,
})),
}
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/credits/add",
request_body = GachaCreditAddRequestDto,
responses(
(status = 200, description = "[ADMIN] Add credits to current user")
),
tag = "Gacha"
)]
pub async fn post_add_credits(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaCreditService>>,
ValidatedJson(payload): ValidatedJson<GachaCreditAddRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers.clone(), state, [PermissionsEnum::CreateGachaItems], {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Unauthorized".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user_id = Uuid::parse_str(&user_info.basic_info.id)
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
service.add_credits(user_id, payload.amount).await?;
Ok(ApiMessage::ok(format!("Added {} credits successfully", payload.amount)))
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/credits/consume",
responses(
(status = 200, description = "[USER] Consume 1 credit for the current user")
),
tag = "Gacha"
)]
pub async fn post_consume_credit(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaCreditService>>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers.clone(), state, [PermissionsEnum::UpdateGachaItems], {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Unauthorized".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user_id = Uuid::parse_str(&user_info.basic_info.id)
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
service.consume_credit(user_id).await?;
Ok(ApiMessage::ok("Consumed 1 credit successfully"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::gacha_credit_router;
@@ -0,0 +1,21 @@
use std::sync::Arc;
use axum::{Router, routing::{get, post}, Extension};
use sea_orm::DatabaseConnection;
use crate::gacha_credits::application::GachaCreditServiceImpl;
use crate::gacha_credits::domain::GachaCreditService;
use crate::gacha_credits::infrastructure::persistence::PostgresGachaCreditRepository;
use super::handlers::{get_user_credits, post_add_credits, post_consume_credit};
fn build_service(db: DatabaseConnection) -> Arc<dyn GachaCreditService> {
let repo = Arc::new(PostgresGachaCreditRepository::new(db));
Arc::new(GachaCreditServiceImpl::new(repo))
}
pub fn gacha_credit_router(db: DatabaseConnection) -> Router {
let service = build_service(db);
Router::new()
.route("/", get(get_user_credits))
.route("/add", post(post_add_credits))
.route("/consume", post(post_consume_credit))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_gacha_credit_repository;
pub use postgres_gacha_credit_repository::PostgresGachaCreditRepository;
@@ -0,0 +1,105 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::ActiveValue;
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::gacha::gacha_credits::{
self, Entity as GachaCreditsEntity, Column as GachaCreditsColumn,
ActiveModel as GachaCreditsActiveModel,
};
use crate::gacha_credits::domain::{gacha_credit::GachaCreditEntity, repository::GachaCreditRepository};
fn to_entity(model: gacha_credits::Model) -> GachaCreditEntity {
GachaCreditEntity {
id: model.id,
user_id: model.user_id,
available_rolls: model.available_rolls,
is_deleted: model.is_deleted,
created_at: model.created_at,
updated_at: model.updated_at,
}
}
pub struct PostgresGachaCreditRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresGachaCreditRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl GachaCreditRepository for PostgresGachaCreditRepository {
async fn find_by_user_id(&self, user_id: Uuid) -> Result<Option<GachaCreditEntity>, AppError> {
let result = GachaCreditsEntity::find()
.filter(GachaCreditsColumn::UserId.eq(user_id))
.filter(GachaCreditsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(result.map(to_entity))
}
async fn add_credit(&self, user_id: Uuid, amount: i32) -> Result<(), AppError> {
let existing = GachaCreditsEntity::find()
.filter(GachaCreditsColumn::UserId.eq(user_id))
.filter(GachaCreditsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
if let Some(credit) = existing {
let mut active_model: GachaCreditsActiveModel = credit.clone().into();
active_model.available_rolls = ActiveValue::Set(credit.available_rolls + amount);
active_model.updated_at = ActiveValue::Set(Some(chrono::Utc::now().naive_utc()));
GachaCreditsEntity::update(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
} else {
let active_model = GachaCreditsActiveModel {
id: ActiveValue::Set(Uuid::new_v4()),
user_id: ActiveValue::Set(user_id),
available_rolls: ActiveValue::Set(amount),
is_deleted: ActiveValue::Set(false),
created_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
updated_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
};
GachaCreditsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
}
Ok(())
}
async fn consume_credit(&self, user_id: Uuid) -> Result<(), AppError> {
let credit = GachaCreditsEntity::find()
.filter(GachaCreditsColumn::UserId.eq(user_id))
.filter(GachaCreditsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("No credit record found".to_string()))?;
if credit.available_rolls <= 0 {
return Err(AppError::BadRequestError("No extra roll credits remaining".to_string()));
}
let mut active_model: GachaCreditsActiveModel = credit.clone().into();
active_model.available_rolls = ActiveValue::Set(credit.available_rolls - 1);
active_model.updated_at = ActiveValue::Set(Some(chrono::Utc::now().naive_utc()));
GachaCreditsEntity::update(active_model)
.exec(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_credit_router;
@@ -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;
@@ -0,0 +1,141 @@
use std::sync::Arc;
use async_trait::async_trait;
use rand::prelude::*;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::gacha_claims::domain::{GachaClaimEntity, GachaClaimRepository};
use crate::gacha_credits::domain::GachaCreditRepository;
use crate::gacha_rolls::domain::{GachaRollEntity, GachaRollRepository, GachaRollService};
pub struct GachaRollServiceImpl {
roll_repo: Arc<dyn GachaRollRepository>,
credit_repo: Arc<dyn GachaCreditRepository>,
claim_repo: Arc<dyn GachaClaimRepository>,
}
impl GachaRollServiceImpl {
pub fn new(
roll_repo: Arc<dyn GachaRollRepository>,
credit_repo: Arc<dyn GachaCreditRepository>,
claim_repo: Arc<dyn GachaClaimRepository>,
) -> Self {
Self {
roll_repo,
credit_repo,
claim_repo,
}
}
fn roll_once(rolls: &[GachaRollEntity]) -> Option<GachaRollEntity> {
let filtered: Vec<&GachaRollEntity> = rolls
.iter()
.filter(|r| !r.is_deleted && r.quantity > 0)
.collect();
if filtered.is_empty() {
return None;
}
let total_weight: f64 = filtered
.iter()
.map(|r| f64::from(r.weight) * f64::from(r.quantity))
.sum();
if total_weight <= 0.0 {
let mut rng = rand::rngs::ThreadRng::default();
let index = rng.random_range(0..filtered.len());
return Some(filtered[index].clone());
}
let mut rng = rand::rngs::ThreadRng::default();
let random_value = rng.random_range(0.0..total_weight);
let mut cumulative_weight = 0.0;
for roll in &filtered {
cumulative_weight += f64::from(roll.weight) * f64::from(roll.quantity);
if random_value <= cumulative_weight {
return Some((*roll).clone());
}
}
Some(filtered[0].clone())
}
}
#[async_trait]
impl GachaRollService for GachaRollServiceImpl {
async fn get_roll(&self, id: Uuid) -> Result<GachaRollEntity, AppError> {
self.roll_repo.find_by_id(id).await
}
async fn create_roll(&self, entity: GachaRollEntity) -> Result<(), AppError> {
self.roll_repo.create(entity).await
}
async fn execute_roll(&self, user_id: Uuid) -> Result<GachaRollEntity, AppError> {
// 1. Check user has credits
let credit = self
.credit_repo
.find_by_user_id(user_id)
.await?
.ok_or_else(|| AppError::BadRequestError("No credit record found".to_string()))?;
if credit.available_rolls <= 0 {
return Err(AppError::BadRequestError(
"Not enough credits to perform this action".to_string(),
));
}
// 2. Consume 1 credit
self.credit_repo.consume_credit(user_id).await?;
// 3. Get all active rolls
let rolls = self.roll_repo.find_all_active().await.map_err(|e| {
AppError::InternalServerError(e.to_string())
})?;
// 4. Weighted random selection
let selected = Self::roll_once(&rolls).ok_or_else(|| {
AppError::NotFoundError("No rollable item available".to_string())
});
let selected = match selected {
Ok(r) => r,
Err(e) => {
// Refund credit on failure
let _ = self.credit_repo.add_credit(user_id, 1).await;
return Err(e);
}
};
// 5. Create claim
let claim_entity = GachaClaimEntity {
id: Uuid::new_v4(),
user_id,
gacha_item_id: selected.item_id,
claim_id: Uuid::new_v4(),
claim_type: "roll".to_string(),
status: "claimed".to_string(),
quantity: 1,
metadata: None,
is_deleted: false,
claimed_at: chrono::Utc::now(),
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
deleted_at: None,
};
if let Err(e) = self.claim_repo.create(claim_entity).await {
// 6. Refund credit on claim creation failure
let _ = self.credit_repo.add_credit(user_id, 1).await;
return Err(e);
}
// 7. Return selected roll entity
Ok(selected)
}
async fn delete_roll(&self, id: Uuid) -> Result<(), AppError> {
self.roll_repo.delete(id).await
}
}
@@ -0,0 +1,3 @@
pub mod gacha_roll_service;
pub use gacha_roll_service::GachaRollServiceImpl;
@@ -0,0 +1,15 @@
use chrono::NaiveDateTime;
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct GachaRollEntity {
pub id: Uuid,
pub user_id: Uuid,
pub gacha_id: String,
pub item_id: Uuid,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<NaiveDateTime>,
pub updated_at: Option<NaiveDateTime>,
}
@@ -0,0 +1,7 @@
pub mod gacha_roll;
pub mod repository;
pub mod service;
pub use gacha_roll::GachaRollEntity;
pub use repository::GachaRollRepository;
pub use service::GachaRollService;
@@ -0,0 +1,12 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_roll::GachaRollEntity;
#[async_trait]
pub trait GachaRollRepository: Send + Sync {
async fn find_by_id(&self, id: Uuid) -> Result<GachaRollEntity, AppError>;
async fn find_all_active(&self) -> Result<Vec<GachaRollEntity>, AppError>;
async fn create(&self, entity: GachaRollEntity) -> Result<(), AppError>;
async fn delete(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,12 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_roll::GachaRollEntity;
#[async_trait]
pub trait GachaRollService: Send + Sync {
async fn get_roll(&self, id: Uuid) -> Result<GachaRollEntity, AppError>;
async fn create_roll(&self, entity: GachaRollEntity) -> Result<(), AppError>;
async fn execute_roll(&self, user_id: Uuid) -> Result<GachaRollEntity, AppError>;
async fn delete_roll(&self, id: Uuid) -> Result<(), AppError>;
}
@@ -0,0 +1,46 @@
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::gacha_rolls::domain::gacha_roll::GachaRollEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaRollCreateRequestDto {
pub item_id: String,
pub weight: f32,
pub quantity: i32,
}
impl ZodValidate for GachaRollCreateRequestDto {
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 GachaRollItemDto {
pub id: String,
pub user_id: String,
pub gacha_id: String,
pub item_id: String,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<&GachaRollEntity> for GachaRollItemDto {
fn from(e: &GachaRollEntity) -> Self {
GachaRollItemDto {
id: e.id.to_string(),
user_id: e.user_id.to_string(),
gacha_id: e.gacha_id.clone(),
item_id: e.item_id.to_string(),
weight: e.weight,
quantity: e.quantity,
is_deleted: e.is_deleted,
created_at: e.created_at.map(|d| d.to_string()),
updated_at: e.updated_at.map(|d| d.to_string()),
}
}
}
@@ -0,0 +1,129 @@
use std::sync::Arc;
use axum::{Extension, extract::Path, http::HeaderMap, response::IntoResponse};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::{ApiSuccess, ApiMessage, extract_email};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_utils::AppError;
use uuid::Uuid;
use super::dto::{GachaRollCreateRequestDto, GachaRollItemDto};
use crate::gacha_rolls::domain::{GachaRollEntity, GachaRollService};
#[utoipa::path(
get,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/detail/{id}",
params(
("id" = String, Path, description = "Gacha Roll ID")
),
responses(
(status = 200, description = "[ADMIN] Get gacha roll by ID", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn get_gacha_roll_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadDetailGachaRolls], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
let roll = service.get_roll(uuid).await?;
Ok(ApiSuccess(GachaRollItemDto::from(&roll)))
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/create",
request_body = GachaRollCreateRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new gacha roll")
),
tag = "Gacha"
)]
pub async fn post_create_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
ValidatedJson(payload): ValidatedJson<GachaRollCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers.clone(), state, [PermissionsEnum::CreateGachaRolls], {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Unauthorized".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user_id = Uuid::parse_str(&user_info.basic_info.id)
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
let item_id = Uuid::parse_str(&payload.item_id)
.map_err(|e| AppError::BadRequestError(format!("Invalid item_id UUID: {e}")))?;
let entity = GachaRollEntity {
id: Uuid::new_v4(),
user_id,
gacha_id: "default".to_string(),
item_id,
weight: payload.weight,
quantity: payload.quantity,
is_deleted: false,
created_at: Some(chrono::Utc::now().naive_utc()),
updated_at: Some(chrono::Utc::now().naive_utc()),
};
service.create_roll(entity).await?;
Ok(ApiMessage::created("Gacha roll created"))
})
}
#[utoipa::path(
post,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/execute",
responses(
(status = 200, description = "[USER] Execute a gacha roll and receive a result", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn post_execute_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers.clone(), state, [PermissionsEnum::ExecuteGachaRolls], {
let email = extract_email(&headers)
.ok_or_else(|| AppError::AuthenticationError("Unauthorized".to_string()))?;
let user_info = state.user_lookup_service.get_user_by_email(&email, &state).await
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
let user_id = Uuid::parse_str(&user_info.basic_info.id)
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
let roll = service.execute_roll(user_id).await?;
Ok(ApiSuccess(GachaRollItemDto::from(&roll)))
})
}
#[utoipa::path(
delete,
security(("Bearer" = [])),
path = "/v1/gacha/rolls/delete/{id}",
params(
("id" = String, Path, description = "Gacha Roll ID")
),
responses(
(status = 200, description = "[ADMIN] Delete gacha roll (soft delete)")
),
tag = "Gacha"
)]
pub async fn delete_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::DeleteGachaRolls], {
let uuid = Uuid::parse_str(&id)
.map_err(|e| AppError::BadRequestError(format!("Invalid UUID: {e}")))?;
service.delete_roll(uuid).await?;
Ok(ApiMessage::ok("Gacha roll deleted"))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::gacha_roll_router;
@@ -0,0 +1,31 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, post}, Extension};
use sea_orm::DatabaseConnection;
use crate::gacha_claims::infrastructure::persistence::PostgresGachaClaimRepository;
use crate::gacha_credits::infrastructure::persistence::PostgresGachaCreditRepository;
use crate::gacha_rolls::application::GachaRollServiceImpl;
use crate::gacha_rolls::domain::GachaRollService;
use crate::gacha_rolls::infrastructure::persistence::PostgresGachaRollRepository;
use super::handlers::{
delete_gacha_roll, get_gacha_roll_by_id, post_create_gacha_roll, post_execute_gacha_roll,
};
fn build_service(
db: DatabaseConnection,
state: Arc<imphnen_libs::AppState>,
) -> Arc<dyn GachaRollService> {
let roll_repo = Arc::new(PostgresGachaRollRepository::new(db.clone()));
let credit_repo = Arc::new(PostgresGachaCreditRepository::new(db.clone()));
let claim_repo = Arc::new(PostgresGachaClaimRepository::new(db, state));
Arc::new(GachaRollServiceImpl::new(roll_repo, credit_repo, claim_repo))
}
pub fn gacha_roll_router(db: DatabaseConnection, state: Arc<imphnen_libs::AppState>) -> Router {
let service = build_service(db, state);
Router::new()
.route("/detail/{id}", get(get_gacha_roll_by_id))
.route("/create", post(post_create_gacha_roll))
.route("/execute", post(post_execute_gacha_roll))
.route("/delete/{id}", delete(delete_gacha_roll))
.layer(Extension(service))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,3 @@
pub mod postgres_gacha_roll_repository;
pub use postgres_gacha_roll_repository::PostgresGachaRollRepository;
@@ -0,0 +1,100 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, QueryFilter};
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::gacha::gacha_rolls::{
Entity as GachaRollsEntity, Column as GachaRollColumn,
ActiveModel as GachaRollActiveModel, Model as GachaRollModel,
};
use crate::gacha_rolls::domain::{gacha_roll::GachaRollEntity, repository::GachaRollRepository};
fn to_entity(model: GachaRollModel) -> GachaRollEntity {
GachaRollEntity {
id: model.id,
user_id: model.user_id,
gacha_id: model.gacha_id,
item_id: model.item_id,
weight: model.weight,
quantity: model.quantity,
is_deleted: model.is_deleted,
created_at: model.created_at,
updated_at: model.updated_at,
}
}
pub struct PostgresGachaRollRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresGachaRollRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl GachaRollRepository for PostgresGachaRollRepository {
async fn find_by_id(&self, id: Uuid) -> Result<GachaRollEntity, AppError> {
let roll = GachaRollsEntity::find_by_id(id)
.filter(GachaRollColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha roll not found".to_string()))?;
Ok(to_entity(roll))
}
async fn find_all_active(&self) -> Result<Vec<GachaRollEntity>, AppError> {
let rolls = GachaRollsEntity::find()
.filter(GachaRollColumn::IsDeleted.eq(false))
.filter(GachaRollColumn::Quantity.gt(0))
.all(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(rolls.into_iter().map(to_entity).collect())
}
async fn create(&self, entity: GachaRollEntity) -> Result<(), AppError> {
let active_model = GachaRollActiveModel {
id: ActiveValue::Set(entity.id),
user_id: ActiveValue::Set(entity.user_id),
gacha_id: ActiveValue::Set(entity.gacha_id),
item_id: ActiveValue::Set(entity.item_id),
weight: ActiveValue::Set(entity.weight),
quantity: ActiveValue::Set(entity.quantity),
is_deleted: ActiveValue::Set(false),
created_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
updated_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
};
GachaRollsEntity::insert(active_model)
.exec(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: GachaRollActiveModel = GachaRollsEntity::find_by_id(id)
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Gacha roll not found".to_string()))?
.into();
active_model.is_deleted = ActiveValue::Set(true);
active_model.updated_at = ActiveValue::Set(Some(chrono::Utc::now().naive_utc()));
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_roll_router;
+30 -31
View File
@@ -1,38 +1,37 @@
pub mod v1;
pub mod gacha_items;
pub mod gacha_credits;
pub mod gacha_claims;
pub mod gacha_rolls;
// Re-export core entity types used across the gacha system
pub use imphnen_libs::AppState;
pub use imphnen_entities::{
CountResult,
Error,
ExperienceDto,
EducationDto,
MessageResponseDto,
MetaRequestDto,
MetaResponseDto,
PermissionsEnum,
PermissionsItemDto,
PermissionsQueryDto,
ResponseListSuccessDto,
ResponseSuccessDto,
UsersDetailQueryDto,
MessageResponseDto,
PermissionsEnum,
};
// Explicitly import only what we need from libs and utils to avoid pollution
pub use imphnen_libs::{
AppState,
MinioService,
};
use std::sync::Arc;
use axum::Router;
use sea_orm::DatabaseConnection;
use gacha_items::gacha_item_router;
use gacha_credits::gacha_credit_router;
use gacha_rolls::gacha_roll_router;
use gacha_claims::gacha_claim_router;
pub use imphnen_utils::{
csrf_token,
extract_email,
generate_date,
generate_otp,
logger,
make_thing,
response_format,
validator,
};
// Re-export public v1 API
pub use v1::gacha_router;
pub fn gacha_router(db: DatabaseConnection, state: Arc<AppState>) -> Router {
let mut router = Router::new();
router = router.nest("/credits", gacha_credit_router(db.clone()));
router = router.nest("/items", gacha_item_router(db.clone()));
router = router.nest("/rolls", gacha_roll_router(db.clone(), state.clone()));
router = router.nest("/claims", gacha_claim_router(db.clone(), state));
router = router.nest("/admin", Router::new().route(
"/",
axum::routing::get(gacha_items::infrastructure::http::handlers::get_gacha_item_list),
).layer(axum::Extension(Arc::new(
gacha_items::application::GachaItemServiceImpl::new(
Arc::new(gacha_items::infrastructure::persistence::PostgresGachaItemRepository::new(db))
)
) as Arc<dyn gacha_items::domain::GachaItemService>)));
router
}
@@ -1,66 +0,0 @@
use axum::Extension;
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use axum::{Json, extract::Path};
use imphnen_iam::{PermissionsEnum, permissions_guard};
use crate::AppState;
use imphnen_entities::{MessageResponseDto, ResponseSuccessDto};
use crate::v1::gacha_claims::{GachaClaimItemDto, GachaClaimRequestDto, GachaClaimService};
#[utoipa::path(
get,
path = "/v1/gacha/claims/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Claim ID")),
responses(
(status = 200, description = "[ADMIN] Get Gacha Claim by ID", body = ResponseSuccessDto<GachaClaimItemDto>)
),
tag = "Gacha"
)]
pub async fn get_detail_gacha_claim(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadDetailGachaClaims],
)
.await
{
Ok((_user, state)) => GachaClaimService::get_gacha_claim_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/gacha/claims/create",
request_body = GachaClaimRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new gacha claim", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_claim(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaClaimRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::CreateGachaClaims],
)
.await
{
Ok((_user, state)) => GachaClaimService::create_gacha_claim(&state, payload).await,
Err(response) => response,
}
}
@@ -1,66 +0,0 @@
use crate::v1::gacha_items::GachaItemDto;
use crate::v1::gacha_items::gacha_items_schema::GachaItemSchema;
use imphnen_iam::{UsersDetailItemDto, UsersDetailQueryDto};
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::{Validate, ValidationError};
// Custom validator for user ID format (UUID-like validation)
pub fn validate_user_id_format(user_id: &str) -> Result<(), ValidationError> {
lazy_static! {
static ref UUID_REGEX: Regex = Regex::new(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$").unwrap();
}
if UUID_REGEX.is_match(user_id) {
Ok(())
} else {
Err(ValidationError::new("invalid_format"))
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct GachaClaimRequestDto {
#[validate(length(min = 1, message = "User ID must not be empty"))]
#[validate(custom(
function = "validate_user_id_format",
message = "User ID must be a valid UUID"
))]
pub user_id: String,
#[validate(length(min = 1, message = "Item ID must not be empty"))]
pub item_id: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaClaimItemDto {
pub id: String,
pub user: UsersDetailItemDto,
pub item: GachaItemDto,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimQueryDto {
pub id: String,
pub user: UsersDetailQueryDto,
pub item: GachaItemSchema,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl GachaClaimItemDto {
pub fn from(dto: &GachaClaimQueryDto) -> Self {
Self {
id: dto.id.clone(),
user: UsersDetailItemDto::from(&dto.user),
item: GachaItemDto::from(dto.item.clone()),
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
@@ -1,122 +0,0 @@
use crate::v1::gacha_claims::gacha_claims_dto::GachaClaimQueryDto;
use crate::v1::gacha_claims::gacha_claims_schema::GachaClaimSchema;
use crate::v1::gacha_items::gacha_items_schema::GachaItemSchema;
use crate::AppState;
use anyhow::{Result, anyhow};
use imphnen_entities::seaorm::gacha::gacha_claims::{Entity as GachaClaimsEntity, ActiveModel as GachaClaimsActiveModel};
use imphnen_entities::seaorm::gacha::gacha_items::Entity as GachaItemsEntity;
use imphnen_iam::{UsersRepository, UsersDetailQueryDto};
use sea_orm::{EntityTrait, ActiveModelTrait, ActiveValue};
use tracing::instrument;
use uuid::Uuid;
pub struct GachaClaimRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaClaimRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
#[instrument(skip(self, id), err)]
pub async fn query_gacha_claim_by_id(
&self,
id: String,
) -> Result<GachaClaimQueryDto> {
let conn = &self.state.postgres_connection.conn;
let claim_uuid = Uuid::parse_str(&id).map_err(|e| anyhow!("Invalid ID format: {}", e))?;
let claim_model = GachaClaimsEntity::find_by_id(claim_uuid)
.one(conn)
.await?
.ok_or_else(|| anyhow!("Gacha claim not found"))?;
// Fetch User
let user_repo = UsersRepository::new(self.state);
let user_dto: UsersDetailQueryDto = user_repo
.query_user_by_id(&claim_model.user_id.to_string())
.await
.map_err(|e| anyhow!("Failed to fetch user: {}", e))?;
// Fetch Item
let item_model = GachaItemsEntity::find_by_id(claim_model.gacha_item_id)
.one(conn)
.await?
.ok_or_else(|| anyhow!("Gacha item not found"))?;
// Convert Item Model to Schema
let item_schema = GachaItemSchema {
id: item_model.id.to_string(),
item_code: item_model.item_code,
name: item_model.name,
description: item_model.description,
rarity: item_model.rarity,
type_: item_model.type_,
category: item_model.category,
value: item_model.value,
weight: item_model.weight,
stock: item_model.stock,
is_limited: item_model.is_limited,
metadata: item_model.metadata,
image_url: "".to_string(), // Field not present in DB model
is_deleted: item_model.deleted_at.is_some(),
created_at: Some(item_model.created_at.to_rfc3339()),
updated_at: Some(item_model.updated_at.to_rfc3339()),
};
Ok(GachaClaimQueryDto {
id: claim_model.id.to_string(),
user: user_dto,
item: item_schema,
is_deleted: claim_model.deleted_at.is_some(),
created_at: Some(claim_model.created_at.to_rfc3339()),
updated_at: Some(claim_model.updated_at.to_rfc3339()),
})
}
#[instrument(skip(self, data), err)]
pub async fn query_create_gacha_claim(
&self,
data: GachaClaimSchema,
) -> Result<String> {
let conn = &self.state.postgres_connection.conn;
// Extract UUIDs from data (which uses Strings)
// GachaClaimSchema uses "thing" format (e.g., "Users:uuid"), we might need to strip prefix if present,
// but looking at schema implementation it seems it might store just UUID string or thing string.
// Let's assume it's a UUID string or clean it.
let user_id_str = data.user.split(':').next_back().unwrap_or(&data.user);
let item_id_str = data.item.split(':').next_back().unwrap_or(&data.item);
let user_uuid = Uuid::parse_str(user_id_str).map_err(|e| anyhow!("Invalid User UUID: {}", e))?;
let item_uuid = Uuid::parse_str(item_id_str).map_err(|e| anyhow!("Invalid Item UUID: {}", e))?;
let claim_id = Uuid::new_v4(); // Generate a new ID for the claim record itself
let id_uuid = if data.id.is_empty() {
Uuid::new_v4()
} else {
let clean_id = data.id.split(':').next_back().unwrap_or(&data.id);
Uuid::parse_str(clean_id).unwrap_or_else(|_| Uuid::new_v4())
};
let active_model = GachaClaimsActiveModel {
id: ActiveValue::Set(id_uuid),
user_id: ActiveValue::Set(user_uuid),
gacha_item_id: ActiveValue::Set(item_uuid),
claim_id: ActiveValue::Set(claim_id), // Using random UUID for claim_id as it's required but not in Schema
claim_type: ActiveValue::Set("standard".to_string()), // Default value
status: ActiveValue::Set("claimed".to_string()), // Default value
quantity: ActiveValue::Set(1),
metadata: ActiveValue::Set(None),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
claimed_at: ActiveValue::Set(chrono::Utc::now()),
};
let result = active_model.insert(conn).await?;
Ok(result.id.to_string())
}
}
@@ -1,71 +0,0 @@
use crate::v1::gacha_rolls::gacha_rolls_dto::GachaRollQueryDto;
use crate::{make_thing};
use imphnen_iam::get_iso_date;
use imphnen_entities::ResourceEnum;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::v1::gacha_claims::gacha_claims_dto::GachaClaimRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimSchema {
pub id: String,
pub user: String,
pub item: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for GachaClaimSchema {
fn default() -> Self {
GachaClaimSchema {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
),
item: make_thing(
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
impl GachaClaimSchema {
pub fn from(dto: GachaClaimRequestDto) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(&ResourceEnum::Users.to_string(), &dto.user_id),
item: make_thing(&ResourceEnum::GachaItems.to_string(), &dto.item_id),
..Default::default()
}
}
pub fn roll(roll: GachaRollQueryDto, user_id: String) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: user_id,
// roll.item is optional at the DTO level; assume caller ensured a valid item exists
item: roll
.item
.as_ref()
.map(|i| i.id.clone())
.unwrap_or_else(|| make_thing(&ResourceEnum::GachaItems.to_string(), &Uuid::new_v4().to_string())),
..Default::default()
}
}
}
@@ -1,37 +0,0 @@
use crate::AppState;
use imphnen_entities::ResponseSuccessDto;
use imphnen_utils::{common_response, success_response, validate_request};
use crate::v1::gacha_claims::gacha_claims_dto::{GachaClaimItemDto, GachaClaimRequestDto};
use crate::v1::gacha_claims::gacha_claims_repository::GachaClaimRepository;
use crate::v1::gacha_claims::gacha_claims_schema::GachaClaimSchema;
use axum::http::StatusCode;
use axum::response::Response;
pub struct GachaClaimService;
impl GachaClaimService {
pub async fn get_gacha_claim_by_id(state: &AppState, id: String) -> Response {
let repo = GachaClaimRepository::new(state);
match repo.query_gacha_claim_by_id(id).await {
Ok(claim) => success_response(ResponseSuccessDto {
data: GachaClaimItemDto::from(&claim),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_claim(
state: &AppState,
payload: GachaClaimRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaClaimRepository::new(state);
let schema = GachaClaimSchema::from(payload);
match repo.query_create_gacha_claim(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
}
-22
View File
@@ -1,22 +0,0 @@
use axum::{
Router,
routing::{get, post},
};
pub mod gacha_claims_controller;
pub mod gacha_claims_dto;
pub mod gacha_claims_repository;
pub mod gacha_claims_schema;
pub mod gacha_claims_service;
// Export only public API functions
pub use gacha_claims_controller::{post_create_gacha_claim, get_detail_gacha_claim};
pub use gacha_claims_dto::{GachaClaimItemDto, GachaClaimRequestDto};
pub use gacha_claims_service::GachaClaimService;
/// Creates router for gacha claims endpoints
pub fn gacha_claim_router() -> Router {
Router::new()
.route("/create", post(post_create_gacha_claim))
.route("/detail/{id}", get(get_detail_gacha_claim))
}
@@ -1,35 +0,0 @@
use axum::{
extract::Json,
http::HeaderMap,
response::Response,
Extension,
};
use crate::AppState;
use crate::v1::gacha_credits::gacha_credits_dto::GachaCreditRequestDto;
use crate::v1::gacha_credits::gacha_credits_service::GachaCreditService;
pub struct GachaCreditController;
impl GachaCreditController {
pub async fn get_user_credits(
headers: HeaderMap,
Extension(state): Extension<AppState>,
) -> Response {
GachaCreditService::get_user_credits(&headers, &state).await
}
pub async fn add_user_credits(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaCreditRequestDto>,
) -> Response {
GachaCreditService::add_user_credits(&headers, &state, payload).await
}
pub async fn consume_user_credit(
headers: HeaderMap,
Extension(state): Extension<AppState>,
) -> Response {
GachaCreditService::consume_user_credit(&headers, &state).await
}
}
@@ -1,38 +0,0 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::Validate;
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, Validate)]
pub struct GachaCreditRequestDto {
#[validate(length(min = 1, message = "User ID must not be empty"))]
pub user_id: String,
#[validate(range(
min = 1,
message = "Amount must be at least 1 credit"
))]
pub amount: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GachaCreditResponseDto {
pub id: String,
pub user_id: String,
pub available_rolls: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<&crate::v1::gacha_credits::gacha_credits_schema::GachaCreditSchema> for GachaCreditResponseDto {
fn from(credit: &crate::v1::gacha_credits::gacha_credits_schema::GachaCreditSchema) -> Self {
Self {
id: credit.id.clone(),
user_id: credit.user.clone(),
available_rolls: credit.available_rolls,
is_deleted: credit.is_deleted,
created_at: credit.created_at.clone(),
updated_at: credit.updated_at.clone(),
}
}
}
@@ -1,117 +0,0 @@
use crate::v1::gacha_credits::gacha_credits_dto::GachaCreditRequestDto;
use crate::AppState;
use imphnen_libs::AppStatePostgresExt;
use imphnen_entities::seaorm::gacha::gacha_credits::{self, Entity as GachaCreditsEntity, Column as GachaCreditsColumn};
use anyhow::{Result, bail};
use sea_orm::{QueryFilter, ActiveValue, EntityTrait, ColumnTrait};
use std::time::Instant;
use tracing::instrument;
use uuid::Uuid;
pub struct GachaCreditRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaCreditRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
#[instrument(skip(self, user_id), err)]
pub async fn query_by_user_id(
&self,
user_id: Uuid,
) -> Result<Option<gacha_credits::Model>> {
let now = Instant::now();
let db = self.state.postgres_db();
let result = GachaCreditsEntity::find()
.filter(GachaCreditsColumn::UserId.eq(user_id))
.filter(GachaCreditsColumn::IsDeleted.eq(false))
.one(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_by_user_id' took: {elapsed:.2?}");
}
Ok(result)
}
#[instrument(skip(self, user_id), err)]
pub async fn query_consume_credit(&self, user_id: Uuid) -> Result<()> {
let now = Instant::now();
let db = self.state.postgres_db();
let credit_opt = self.query_by_user_id(user_id).await?;
let Some(credit) = credit_opt else {
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!(
"Query 'query_consume_credit' took: {elapsed:.2?} (no credit to consume)"
);
}
return Ok(());
};
if credit.available_rolls <= 0 {
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!(
"Query 'query_consume_credit' took: {elapsed:.2?} (no rolls remaining)"
);
}
bail!("No extra roll credits remaining");
}
let mut active_model: gacha_credits::ActiveModel = credit.clone().into();
active_model.available_rolls = ActiveValue::Set(credit.available_rolls - 1);
GachaCreditsEntity::update(active_model).exec(db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_consume_credit' took: {elapsed:.2?}");
}
Ok(())
}
#[instrument(skip(self, payload), err)]
pub async fn query_add_credit(
&self,
payload: GachaCreditRequestDto,
) -> Result<()> {
let now = Instant::now();
let db = self.state.postgres_db();
if let Some(credit) = self.query_by_user_id(Uuid::parse_str(&payload.user_id)?).await? {
let mut active_model: gacha_credits::ActiveModel = credit.clone().into();
active_model.available_rolls = ActiveValue::Set(credit.available_rolls + payload.amount);
GachaCreditsEntity::update(active_model).exec(db).await?;
} else {
let active_model = gacha_credits::ActiveModel {
id: ActiveValue::Set(uuid::Uuid::new_v4()),
user_id: ActiveValue::Set(Uuid::parse_str(&payload.user_id)?),
available_rolls: ActiveValue::Set(payload.amount),
is_deleted: ActiveValue::Set(false),
created_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
updated_at: ActiveValue::Set(Some(chrono::Utc::now().naive_utc())),
};
GachaCreditsEntity::insert(active_model).exec(db).await?;
}
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_add_credit' took: {elapsed:.2?}");
}
Ok(())
}
}
@@ -1,9 +0,0 @@
use axum::{Router, routing::get};
use axum::routing::post;
pub fn gacha_credit_router() -> Router {
Router::new()
.route("/", get(crate::v1::gacha_credits::GachaCreditController::get_user_credits))
.route("/add", post(crate::v1::gacha_credits::GachaCreditController::add_user_credits))
.route("/consume", post(crate::v1::gacha_credits::GachaCreditController::consume_user_credit))
}
@@ -1,39 +0,0 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use imphnen_utils::{get_iso_date};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GachaCreditSchema {
pub id: String,
pub user: String,
pub available_rolls: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for GachaCreditSchema {
fn default() -> Self {
GachaCreditSchema {
id: Uuid::new_v4().to_string(),
user: Uuid::new_v4().to_string(),
available_rolls: 0,
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
impl GachaCreditSchema {
pub fn from(&self) -> Self {
Self {
id: self.id.clone(),
user: self.user.clone(),
available_rolls: self.available_rolls,
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
@@ -1,115 +0,0 @@
use crate::AppState;
use imphnen_entities::ResponseSuccessDto;
use imphnen_utils::{errors::AppError, error_response};
use imphnen_utils::{common_response, success_response, validate_request};
use uuid::Uuid;
use crate::v1::gacha_credits::gacha_credits_dto::{GachaCreditRequestDto, GachaCreditResponseDto};
use crate::v1::gacha_credits::gacha_credits_repository::GachaCreditRepository;
use axum::http::StatusCode;
use axum::response::Response;
use imphnen_iam::UsersRepository;
use imphnen_utils::extract_email;
pub struct GachaCreditService;
impl GachaCreditService {
pub async fn get_user_credits(headers: &axum::http::HeaderMap, state: &AppState) -> Response {
let repo = GachaCreditRepository::new(state);
let repo_user = UsersRepository::new(state);
let Some(email) = extract_email(headers) else {
return error_response(AppError::AuthenticationError("Unauthorized".into()));
};
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
return error_response(AppError::NotFoundError("User not found".into()));
};
let parsed_user_id = match Uuid::parse_str(&user.id) {
Ok(uuid) => uuid,
Err(e) => return error_response(AppError::BadRequestError(format!("Invalid User ID format: {}", e))),
};
match repo.query_by_user_id(parsed_user_id).await {
Ok(Some(credit)) => {
let response_dto = GachaCreditResponseDto {
id: credit.id.to_string(),
user_id: credit.user_id.to_string(),
available_rolls: credit.available_rolls,
is_deleted: credit.is_deleted,
created_at: credit.created_at.map(|d| d.to_string()),
updated_at: credit.updated_at.map(|d| d.to_string()),
};
success_response(ResponseSuccessDto { data: response_dto })
}
Ok(None) => {
// Return empty credits if no record exists
let response_dto = GachaCreditResponseDto {
id: "".to_string(),
user_id: user.id,
available_rolls: 0,
is_deleted: false,
created_at: None,
updated_at: None,
};
success_response(ResponseSuccessDto { data: response_dto })
}
Err(e) => error_response(AppError::InternalServerError(e.to_string())),
}
}
pub async fn add_user_credits(
headers: &axum::http::HeaderMap,
state: &AppState,
payload: GachaCreditRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaCreditRepository::new(state);
let repo_user = UsersRepository::new(state);
let Some(email) = extract_email(headers) else {
return error_response(AppError::AuthenticationError("Unauthorized".into()));
};
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
return error_response(AppError::NotFoundError("User not found".into()));
};
// Ensure the user can only modify their own credits
if payload.user_id != user.id {
return error_response(AppError::AuthorizationError("You can only modify your own credits".into()));
}
let amount = payload.amount; // Extract amount before moving payload
match repo.query_add_credit(payload).await {
Ok(_) => common_response(
StatusCode::OK,
&format!("Added {} credits successfully", amount)
),
Err(e) => error_response(AppError::InternalServerError(e.to_string())),
}
}
pub async fn consume_user_credit(headers: &axum::http::HeaderMap, state: &AppState) -> Response {
let repo = GachaCreditRepository::new(state);
let repo_user = UsersRepository::new(state);
let Some(email) = extract_email(headers) else {
return error_response(AppError::AuthenticationError("Unauthorized".into()));
};
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
return error_response(AppError::NotFoundError("User not found".into()));
};
let parsed_user_id = match Uuid::parse_str(&user.id) {
Ok(uuid) => uuid,
Err(e) => return error_response(AppError::BadRequestError(format!("Invalid User ID format: {}", e))),
};
match repo.query_consume_credit(parsed_user_id).await {
Ok(_) => common_response(StatusCode::OK, "Consumed 1 credit successfully"),
Err(e) => error_response(AppError::BadRequestError(e.to_string())),
}
}
}
-13
View File
@@ -1,13 +0,0 @@
pub mod gacha_credits_controller;
pub mod gacha_credits_dto;
pub mod gacha_credits_repository;
pub mod gacha_credits_schema;
pub mod gacha_credits_service;
pub mod gacha_credits_router;
// Export only public types and functions
pub use gacha_credits_controller::GachaCreditController;
pub use gacha_credits_dto::{GachaCreditRequestDto, GachaCreditResponseDto};
pub use gacha_credits_repository::GachaCreditRepository;
pub use gacha_credits_service::GachaCreditService;
pub use gacha_credits_router::gacha_credit_router;
@@ -1,131 +0,0 @@
use crate::{AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto};
use imphnen_entities::MessageResponseDto;
use crate::v1::gacha_items::GachaItemDto;
use crate::v1::gacha_items::gacha_items_dto::{GachaItemRequestDto, GachaItemUpdateRequestDto};
use crate::v1::gacha_items::gacha_items_service::GachaItemService;
use axum::{
Extension,
extract::{Path, Query},
http::HeaderMap,
response::IntoResponse,
};
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_libs::ValidatedJson;
#[utoipa::path(
get,
path = "/v1/gacha/items",
security(
("Bearer" = [])
),
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"),
("filter" = Option<String>, Query, description = "Filter value"),
("filter_by" = Option<String>, Query, description = "Field to filter by"),
),
responses(
(status = 200, description = "[ADMIN] Get gacha item list", body = ResponseListSuccessDto<Vec<GachaItemDto>>)
),
tag = "Gacha"
)]
pub async fn get_gacha_item_list(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Query(meta): Query<MetaRequestDto>,
) -> impl IntoResponse {
require_permissions!(headers, state, [PermissionsEnum::ReadListGachaItems], {
GachaItemService::get_gacha_item_list(&state, meta).await
})
}
#[utoipa::path(
get,
path = "/v1/gacha/items/detail/{id}",
security(
("Bearer" = [])
),
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>,
Path(id): Path<String>,
) -> impl IntoResponse {
require_permissions!(headers, state, [PermissionsEnum::ReadDetailGachaItems], {
GachaItemService::get_gacha_item_by_id(&state, id).await
})
}
#[utoipa::path(
post,
path = "/v1/gacha/items/create",
security(
("Bearer" = [])
),
request_body = GachaItemRequestDto,
responses(
(status = 201, description = "[ADMIN] Create gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
ValidatedJson(payload): ValidatedJson<GachaItemRequestDto>,
) -> impl IntoResponse {
require_permissions!(headers, state, [PermissionsEnum::CreateGachaItems], {
GachaItemService::create_gacha_item(&state, payload).await
})
}
#[utoipa::path(
put,
path = "/v1/gacha/items/update/{id}",
security(
("Bearer" = [])
),
request_body = GachaItemUpdateRequestDto,
responses(
(status = 200, description = "[ADMIN] Update gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn put_update_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
ValidatedJson(payload): ValidatedJson<GachaItemUpdateRequestDto>,
) -> impl IntoResponse {
require_permissions!(headers, state, [PermissionsEnum::UpdateGachaItems], {
GachaItemService::update_gacha_item(&state, payload, id).await
})
}
#[utoipa::path(
delete,
path = "/v1/gacha/items/delete/{id}",
security(
("Bearer" = [])
),
responses(
(status = 200, description = "[ADMIN] Delete gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn delete_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
require_permissions!(headers, state, [PermissionsEnum::DeleteGachaItems], {
GachaItemService::delete_gacha_item(&state, id).await
})
}
@@ -1,95 +0,0 @@
use crate::v1::gacha_items::gacha_items_schema::GachaItemSchema;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::Value; // Add this import
use std::sync::LazyLock;
use utoipa::ToSchema;
use validator::{Validate, ValidationError};
// Custom validator for image URLs
static IMAGE_URL_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^https?://[^\s]+\.(jpg|jpeg|png|gif|webp)$").unwrap());
pub fn validate_image_url(url: &str) -> Result<(), ValidationError> {
if IMAGE_URL_REGEX.is_match(url) {
Ok(())
} else {
Err(ValidationError::new("invalid_image_url"))
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct GachaItemRequestDto {
#[validate(length(min = 1, max = 100, message = "Item code must be between 1 and 100 characters"))]
pub item_code: String,
#[validate(length(min = 1, max = 100, message = "Item name must be between 1 and 100 characters"))]
pub name: String,
#[validate(length(min = 1, max = 500, message = "Description must be between 1 and 500 characters"))]
pub description: String,
#[validate(length(min = 1, max = 50, message = "Rarity must be between 1 and 50 characters"))]
pub rarity: String,
#[validate(length(min = 1, max = 50, message = "Type must be between 1 and 50 characters"))]
pub type_: String,
#[validate(length(min = 1, max = 50, message = "Category must be between 1 and 50 characters"))]
pub category: String,
#[validate(range(min = 0, message = "Value must be non-negative"))]
pub value: i32,
#[validate(range(min = 0.0, message = "Weight must be non-negative"))]
pub weight: f64,
#[validate(range(min = 0, message = "Stock must be non-negative"))]
pub stock: i32,
pub is_limited: bool,
pub metadata: Option<Value>,
#[validate(length(min = 1, message = "Image URL must not be empty"))]
#[validate(custom(
function = "validate_image_url",
message = "Image URL must be a valid URL pointing to JPG, JPEG, PNG, GIF, or WebP image"
))]
pub image_url: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct GachaItemUpdateRequestDto {
#[validate(length(min = 1, max = 100, message = "Item name must be between 1 and 100 characters"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[validate(length(min = 1, message = "Image URL must not be empty"))]
#[validate(custom(
function = "validate_image_url",
message = "Image URL must be a valid URL pointing to JPG, JPEG, PNG, GIF, or WebP image"
))]
#[serde(skip_serializing_if = "Option::is_none")]
pub image_url: Option<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 GachaItemDto {
pub fn from(dto: GachaItemSchema) -> Self {
Self {
id: dto.id.to_string(),
name: dto.name,
is_deleted: dto.is_deleted,
created_at: dto.created_at,
updated_at: dto.updated_at,
}
}
}
@@ -1,258 +0,0 @@
use crate::v1::gacha_items::gacha_items_schema::GachaItemSchema;
use crate::v1::gacha_items::GachaItemDto;
use crate::{AppState, MetaRequestDto, ResponseListSuccessDto};
use anyhow::{Result, bail};
// QueryListBuilder is not available in imphnen-iam, need to implement locally or use alternative
use std::time::Instant;
use tracing::instrument;
use sea_orm::{EntityTrait, ColumnTrait, QueryFilter, QueryOrder, PaginatorTrait, ActiveModelTrait, ActiveValue, QuerySelect};
use imphnen_entities::seaorm::gacha::gacha_items::{Entity as GachaItemEntity, Column as GachaItemColumn, ActiveModel as GachaItemActiveModel};
use uuid::Uuid;
pub struct GachaItemRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaItemRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
#[instrument(skip(self, meta), err)]
pub async fn query_gacha_item_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<GachaItemDto>>> {
let now = Instant::now();
let db = &self.state.postgres_connection.conn;
let query = GachaItemEntity::find()
.filter(GachaItemColumn::DeletedAt.is_null());
// Apply search if provided
let query = if let Some(search) = &meta.search {
query.filter(GachaItemColumn::Name.contains(search))
} else {
query
};
// Apply sorting
let query = if let Some(sort_by) = &meta.sort_by {
match sort_by.as_str() {
"name" => {
if meta.order.as_deref() == Some("desc") {
query.order_by_desc(GachaItemColumn::Name)
} else {
query.order_by_asc(GachaItemColumn::Name)
}
}
"created_at" => {
if meta.order.as_deref() == Some("desc") {
query.order_by_desc(GachaItemColumn::CreatedAt)
} else {
query.order_by_asc(GachaItemColumn::CreatedAt)
}
}
_ => query.order_by_desc(GachaItemColumn::CreatedAt),
}
} else {
query.order_by_desc(GachaItemColumn::CreatedAt)
};
// Get total count
let total_count = query.clone().count(db).await?;
// Apply pagination
let page = meta.page.unwrap_or(1);
let limit = meta.per_page.unwrap_or(10);
let offset = (page - 1) * limit;
let items = query
.offset(offset)
.limit(limit)
.all(db)
.await?;
let data: Vec<GachaItemDto> = items
.into_iter()
.map(|item| GachaItemDto {
id: item.id.to_string(),
name: item.name,
is_deleted: item.deleted_at.is_some(),
created_at: Some(item.created_at.to_string()),
updated_at: Some(item.updated_at.to_string()),
})
.collect();
let _total_pages = (total_count as f64 / limit as f64).ceil() as u32;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_gacha_item_list' took: {elapsed:.2?}");
}
Ok(ResponseListSuccessDto {
data,
meta: Some(imphnen_libs::MetaResponseDto {
page: Some(page),
per_page: Some(limit),
total: Some(total_count),
}),
})
}
#[instrument(skip(self, id), err)]
pub async fn query_gacha_item_by_id(&self, id: String) -> Result<GachaItemSchema> {
let now = Instant::now();
let db = &self.state.postgres_connection.conn;
let uuid_id = Uuid::parse_str(&id)?;
let item = GachaItemEntity::find_by_id(uuid_id)
.filter(GachaItemColumn::DeletedAt.is_null())
.one(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_gacha_item_by_id' took: {elapsed:.2?}");
}
match item {
Some(item) => Ok(GachaItemSchema {
id: item.id.to_string(),
item_code: item.item_code,
name: item.name,
description: item.description,
rarity: item.rarity,
type_: item.type_,
category: item.category,
value: item.value,
weight: item.weight,
stock: item.stock,
is_limited: item.is_limited,
metadata: item.metadata,
image_url: "".to_string(), // Not present in DB model
is_deleted: item.deleted_at.is_some(),
created_at: Some(item.created_at.to_string()),
updated_at: Some(item.updated_at.to_string()),
}),
None => bail!("Gacha Item not found"),
}
}
#[instrument(skip(self, data), err)]
pub async fn query_create_gacha_item(
&self,
data: GachaItemSchema,
) -> Result<String> {
let now = Instant::now();
let db = &self.state.postgres_connection.conn;
let active_model = GachaItemActiveModel {
id: ActiveValue::Set(Uuid::new_v4()),
item_code: ActiveValue::Set(data.item_code),
name: ActiveValue::Set(data.name),
description: ActiveValue::Set(data.description),
rarity: ActiveValue::Set(data.rarity),
type_: ActiveValue::Set(data.type_),
category: ActiveValue::Set(data.category),
value: ActiveValue::Set(data.value),
weight: ActiveValue::Set(data.weight),
stock: ActiveValue::Set(data.stock),
is_limited: ActiveValue::Set(data.is_limited),
metadata: ActiveValue::Set(data.metadata),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
};
let result = active_model.insert(db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_create_gacha_item' took: {elapsed:.2?}");
}
Ok(result.id.to_string())
}
#[instrument(skip(self, data), err)]
pub async fn query_update_gacha_item(
&self,
data: GachaItemSchema,
) -> Result<String> {
let now = Instant::now();
let db = &self.state.postgres_connection.conn;
let uuid_id = Uuid::parse_str(&data.id)?;
let mut active_model: GachaItemActiveModel = GachaItemEntity::find_by_id(uuid_id)
.one(db)
.await?
.ok_or_else(|| anyhow::anyhow!("Gacha Item not found"))?
.into();
active_model.item_code = ActiveValue::Set(data.item_code);
active_model.name = ActiveValue::Set(data.name);
active_model.description = ActiveValue::Set(data.description);
active_model.rarity = ActiveValue::Set(data.rarity);
active_model.type_ = ActiveValue::Set(data.type_);
active_model.category = ActiveValue::Set(data.category);
active_model.value = ActiveValue::Set(data.value);
active_model.weight = ActiveValue::Set(data.weight);
active_model.stock = ActiveValue::Set(data.stock);
active_model.is_limited = ActiveValue::Set(data.is_limited);
active_model.metadata = ActiveValue::Set(data.metadata);
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
let _result = active_model.update(db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_update_gacha_item' took: {elapsed:.2?}");
}
Ok("Success update Gacha Item".into())
}
#[instrument(skip(self, id), err)]
pub async fn query_delete_gacha_item(&self, id: String) -> Result<String> {
let now = Instant::now();
let db = &self.state.postgres_connection.conn;
let uuid_id = Uuid::parse_str(&id)?;
let mut active_model: GachaItemActiveModel = GachaItemEntity::find_by_id(uuid_id)
.one(db)
.await?
.ok_or_else(|| anyhow::anyhow!("Gacha Item not found"))?
.into();
if active_model.deleted_at.is_set() {
bail!("Gacha Item already deleted");
}
active_model.deleted_at = ActiveValue::Set(Some(chrono::Utc::now()));
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model.update(db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_delete_gacha_item' took: {elapsed:.2?}");
}
Ok("Success soft delete Gacha Item".into())
}
}
@@ -1,75 +0,0 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use serde_json::Value;
use crate::v1::gacha_items::gacha_items_dto::GachaItemRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaItemSchema {
pub id: String,
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 image_url: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for GachaItemSchema {
fn default() -> Self {
GachaItemSchema {
id: Uuid::new_v4().to_string(),
item_code: String::new(),
name: String::new(),
description: String::new(),
rarity: String::new(),
type_: String::new(),
category: String::new(),
value: 0,
weight: 0.0,
stock: 0,
is_limited: false,
metadata: None,
image_url: String::new(),
is_deleted: false,
created_at: None,
updated_at: None,
}
}
}
impl GachaItemSchema {
pub fn from(dto: GachaItemRequestDto) -> Self {
Self {
id: Uuid::new_v4().to_string(),
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,
image_url: dto.image_url,
is_deleted: false,
created_at: None,
updated_at: None,
}
}
pub fn from_existing(existing: GachaItemSchema) -> Self {
existing
}
}
@@ -1,112 +0,0 @@
use crate::AppState;
use imphnen_entities::{MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto};
use imphnen_utils::{common_response, make_thing, success_list_response, success_response};
use crate::v1::gacha_items::GachaItemDto;
use crate::v1::gacha_items::gacha_items_dto::{GachaItemRequestDto, GachaItemUpdateRequestDto};
use crate::v1::gacha_items::gacha_items_repository::GachaItemRepository;
use crate::v1::gacha_items::gacha_items_schema::GachaItemSchema;
use imphnen_entities::ResourceEnum;
use axum::http::StatusCode;
use axum::response::Response;
use imphnen_utils::get_iso_date;
pub struct GachaItemService;
impl GachaItemService {
pub async fn get_gacha_item_list(
state: &AppState,
meta: MetaRequestDto,
) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_gacha_item_list(meta).await {
Ok(data) => {
let response = ResponseListSuccessDto {
data: data.data,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn get_gacha_item_by_id(state: &AppState, id: String) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_gacha_item_by_id(id).await {
Ok(item) => success_response(ResponseSuccessDto {
data: GachaItemDto::from(item),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_item(
state: &AppState,
payload: GachaItemRequestDto,
) -> Response {
// Validation is now automatic via ValidatedJson extractor
let repo = GachaItemRepository::new(state);
let schema = GachaItemSchema {
id: make_thing(&ResourceEnum::GachaItems.to_string(), &payload.name), // Fixed: Use payload.name or some other identifier
name: payload.name,
image_url: payload.image_url,
..Default::default()
};
match repo.query_create_gacha_item(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn update_gacha_item(
state: &AppState,
payload: GachaItemUpdateRequestDto,
id: String,
) -> Response {
// Validation is now automatic via ValidatedJson extractor
let repo = GachaItemRepository::new(state);
// Get current gacha item data first
let _thing_id = make_thing(&ResourceEnum::GachaItems.to_string(), &id);
let current_item = match repo.query_gacha_item_by_id(id.clone()).await {
Ok(item) => item,
Err(_) => return common_response(StatusCode::NOT_FOUND, "Gacha Item not found"),
};
let mut updated_item = current_item;
updated_item.updated_at = Some(get_iso_date());
// Only update fields that are provided
if let Some(name) = payload.name {
updated_item.name = name;
}
if let Some(image_url) = payload.image_url {
updated_item.image_url = image_url;
}
match repo.query_update_gacha_item(updated_item).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Gacha Item not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
pub async fn delete_gacha_item(state: &AppState, id: String) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_delete_gacha_item(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Gacha Item not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
}
-30
View File
@@ -1,30 +0,0 @@
use axum::{
Router,
routing::{delete, get, post, put},
};
pub mod gacha_items_controller;
pub mod gacha_items_dto;
pub mod gacha_items_repository;
pub mod gacha_items_schema;
pub mod gacha_items_service;
// Export only public API functions and types
pub use gacha_items_controller::{
get_gacha_item_list,
post_create_gacha_item,
get_gacha_item_by_id,
put_update_gacha_item,
delete_gacha_item,
};
pub use gacha_items_dto::GachaItemDto;
/// Creates router for gacha items endpoints
pub fn gacha_item_router() -> Router {
Router::new()
.route("/", get(get_gacha_item_list))
.route("/create", post(post_create_gacha_item))
.route("/detail/{id}", get(get_gacha_item_by_id))
.route("/update/{id}", put(put_update_gacha_item))
.route("/delete/{id}", delete(delete_gacha_item))
}
@@ -1,136 +0,0 @@
use crate::AppState;
use imphnen_entities::{MessageResponseDto, ResponseSuccessDto};
use crate::v1::gacha_rolls::gacha_rolls_dto::{GachaRollItemDto, GachaRollRequestDto};
use crate::v1::gacha_rolls::gacha_rolls_service::GachaRollService;
use axum::{
Extension, Json, extract::Path, http::{HeaderMap, StatusCode}, response::IntoResponse,
};
use imphnen_iam::{PermissionsEnum, permissions_guard};
use imphnen_utils::common_response;
use uuid::Uuid;
#[utoipa::path(
get,
path = "/v1/gacha/rolls/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Roll ID")),
responses(
(status = 200, description = "[ADMIN] Get Gacha Roll by ID", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn get_detail_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadDetailGachaRolls],
)
.await
{
Ok((_user, state)) => {
let parsed_id = match Uuid::parse_str(&id) {
Ok(uuid) => uuid,
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
};
GachaRollService::get_gacha_roll_by_id(&state, parsed_id).await
},
Err(response) => response,
}
}
#[utoipa::path(
post,
path = "/v1/gacha/rolls/create",
security(
("Bearer" = [])
),
request_body = GachaRollRequestDto,
responses(
(status = 201, description = "[ADMIN] Create new gacha roll", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaRollRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers.clone(),
Extension(state.clone()),
vec![PermissionsEnum::CreateGachaRolls],
)
.await
{
Ok((_user, _)) => GachaRollService::create_gacha_roll(headers, &state, payload, "default".to_string()).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
path = "/v1/gacha/rolls/execute",
security(
("Bearer" = [])
),
responses(
(status = 200, description = "[ADMIN] Execute and get 1 gacha result", body = ResponseSuccessDto<GachaRollItemDto>)
),
tag = "Gacha"
)]
pub async fn post_execute_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
) -> impl IntoResponse {
match permissions_guard(
headers.clone(),
Extension(state),
vec![PermissionsEnum::ExecuteGachaRolls],
)
.await
{
Ok((_user, state)) => GachaRollService::execute_roll_once(headers, &state).await,
Err(response) => response,
}
}
#[utoipa::path(
delete,
path = "/v1/gacha/rolls/delete/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Roll ID")),
responses(
(status = 200, description = "[ADMIN] Delete Gacha Roll (soft delete)", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn delete_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::DeleteGachaRolls],
)
.await
{
Ok((_user, state)) => {
let parsed_id = match Uuid::parse_str(&id) {
Ok(uuid) => uuid,
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid UUID format: {}", e)),
};
GachaRollService::soft_delete_gacha_roll(&state, parsed_id).await
},
Err(response) => response,
}
}
@@ -1,64 +0,0 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::Validate;
use crate::v1::gacha_items::GachaItemDto;
use crate::v1::gacha_items::gacha_items_schema::GachaItemSchema;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct GachaRollRequestDto {
#[validate(length(min = 1, max = 100, message = "Item ID must be between 1 and 100 characters"))]
pub item_id: String,
#[validate(range(min = 0.0, max = 1.0, message = "Weight must be between 0.0 and 1.0"))]
pub weight: f32,
#[validate(range(min = 1, max = 100, message = "Quantity must be between 1 and 100"))]
pub quantity: i32,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaRollItemDto {
pub id: String,
pub item: GachaItemDto,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl GachaRollItemDto {
pub fn from(dto: &GachaRollQueryDto) -> Self {
Self {
id: dto.id.clone(),
// Handle case where item might be missing
item: match &dto.item {
Some(item) => GachaItemDto::from(item.clone()),
None => GachaItemDto {
id: "".to_string(),
name: "Unknown".to_string(),
is_deleted: false,
created_at: None,
updated_at: None,
}
},
weight: dto.weight,
quantity: dto.quantity,
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaRollQueryDto {
pub id: String,
// item can be missing in the DB (during partial queries); make optional to allow graceful handling
pub item: Option<GachaItemSchema>,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
@@ -1,190 +0,0 @@
use crate::v1::gacha_rolls::gacha_rolls_dto::GachaRollQueryDto;
use crate::v1::gacha_rolls::gacha_rolls_schema::GachaRollSchema;
use crate::AppState;
use imphnen_entities::seaorm::gacha::gacha_rolls::{Entity as GachaRollsEntity, ActiveModel as GachaRollActiveModel, Column as GachaRollColumn};
use anyhow::{Result, bail};
use chrono::Utc;
use rand::prelude::*;
use sea_orm::{EntityTrait, QueryFilter, Set, ColumnTrait, ActiveModelTrait};
use imphnen_libs::postgres::AppStatePostgresExt;
use std::time::Instant;
use tracing::instrument;
use uuid::Uuid;
pub struct GachaRollRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaRollRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
#[instrument(skip(self, id), err)]
pub async fn query_gacha_roll_by_id(
&self,
id: Uuid,
) -> Result<GachaRollQueryDto> {
let now = Instant::now();
let db = self.state.postgres_db();
let result = GachaRollsEntity::find()
.filter(GachaRollColumn::Id.eq(id))
.filter(GachaRollColumn::IsDeleted.eq(false))
.one(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_gacha_roll_by_id' took: {elapsed:.2?}");
}
match result {
Some(r) => Ok(GachaRollQueryDto {
id: r.id.to_string(),
item: None,
weight: r.weight,
quantity: r.quantity,
is_deleted: r.is_deleted,
created_at: r.created_at.map(|d| d.to_string()),
updated_at: r.updated_at.map(|d| d.to_string()),
}),
None => bail!("Gacha Roll not found"),
}
}
#[instrument(skip(self, data), err)]
pub async fn query_create_gacha_roll(
&self,
data: GachaRollSchema,
) -> Result<String> {
let now = Instant::now();
let db = self.state.postgres_db();
let active_model = GachaRollActiveModel {
id: Set(Uuid::parse_str(&data.id)?),
user_id: Set(Uuid::parse_str(&data.user_id)?),
gacha_id: Set(data.gacha_id), // gacha_id is String
item_id: Set(Uuid::parse_str(&data.item_id)?),
quantity: Set(data.quantity),
weight: Set(data.weight),
is_deleted: Set(false),
created_at: Set(Some(Utc::now().naive_utc())),
updated_at: Set(Some(Utc::now().naive_utc())),
};
let _ = GachaRollsEntity::insert(active_model)
.exec(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_create_gacha_roll' took: {elapsed:.2?}");
}
Ok("Success create Gacha Roll".into())
}
#[instrument(skip(self), err)]
pub async fn query_all_active_rolls(&self) -> Result<Vec<GachaRollQueryDto>> {
let now = Instant::now();
let db = self.state.postgres_db();
let results = GachaRollsEntity::find()
.filter(GachaRollColumn::IsDeleted.eq(false))
.filter(GachaRollColumn::Quantity.gt(0))
.all(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_all_active_rolls' took: {elapsed:.2?}");
}
Ok(results.into_iter().map(|r| GachaRollQueryDto {
id: r.id.to_string(),
item: None,
weight: r.weight,
quantity: r.quantity,
is_deleted: r.is_deleted,
created_at: r.created_at.map(|d| d.to_string()),
updated_at: r.updated_at.map(|d| d.to_string()),
}).collect())
}
#[instrument]
pub fn roll_once(rolls: &[GachaRollQueryDto]) -> Option<GachaRollQueryDto> {
let filtered: Vec<GachaRollQueryDto> = rolls
.iter()
.filter(|r| !r.is_deleted && r.quantity > 0)
.cloned()
.collect();
if filtered.is_empty() {
return None;
}
// Simple random selection based on quantity weights
let total_weight: f64 = filtered.iter()
.map(|r| f64::from(r.weight) * f64::from(r.quantity))
.sum();
if total_weight <= 0.0 {
// Fallback to equal probability if weights are invalid
let mut rng = rand::rngs::ThreadRng::default();
let index = rng.random_range(0..filtered.len());
return Some(filtered[index].clone());
}
// Weighted random selection
let mut rng = rand::rngs::ThreadRng::default();
let random_value = rng.random_range(0.0..total_weight);
let mut cumulative_weight = 0.0;
for roll in &filtered {
cumulative_weight += f64::from(roll.weight) * f64::from(roll.quantity);
if random_value <= cumulative_weight {
return Some(roll.clone());
}
}
// This should rarely happen but provides a fallback
Some(filtered[0].clone())
}
#[instrument(skip(self, id), err)]
pub async fn query_soft_delete_gacha_roll(&self, id: Uuid) -> Result<String> {
let now = Instant::now();
let db = self.state.postgres_db();
let roll = self.query_gacha_roll_by_id(id).await?;
if roll.is_deleted {
bail!("Gacha Roll already deleted");
}
let mut active_model: GachaRollActiveModel = GachaRollsEntity::find_by_id(id)
.one(db)
.await?
.ok_or_else(|| anyhow::anyhow!("Gacha Roll not found"))?
.into();
active_model.is_deleted = Set(true);
active_model.updated_at = Set(Some(Utc::now().naive_utc()));
let _result = GachaRollActiveModel::update(active_model, db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_soft_delete_gacha_roll' took: {elapsed:.2?}");
}
Ok("Success soft delete Gacha Roll".into())
}
}
@@ -1,48 +0,0 @@
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use uuid::Uuid;
use crate::v1::gacha_rolls::gacha_rolls_dto::GachaRollRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaRollSchema {
pub id: String,
pub user_id: String,
pub gacha_id: String,
pub item_id: String,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<DateTime<Utc>>,
pub updated_at: Option<DateTime<Utc>>,
}
impl Default for GachaRollSchema {
fn default() -> Self {
GachaRollSchema {
id: Uuid::new_v4().to_string(),
user_id: "".to_string(),
gacha_id: "".to_string(),
item_id: "".to_string(),
weight: 0.0,
quantity: 0,
is_deleted: false,
created_at: Some(Utc::now()),
updated_at: Some(Utc::now()),
}
}
}
impl GachaRollSchema {
pub fn create(dto: GachaRollRequestDto, user_id: String, gacha_id: String) -> Self {
Self {
id: Uuid::new_v4().to_string(),
user_id,
gacha_id,
item_id: dto.item_id,
weight: dto.weight,
quantity: dto.quantity,
..Default::default()
}
}
}
@@ -1,122 +0,0 @@
use crate::AppState;
use imphnen_entities::ResponseSuccessDto;
use imphnen_utils::{common_response, success_response, validate_request};
use crate::v1::gacha_claims::gacha_claims_repository::GachaClaimRepository;
use crate::v1::gacha_claims::gacha_claims_schema::GachaClaimSchema;
use crate::v1::gacha_rolls::gacha_rolls_dto::{GachaRollItemDto, GachaRollRequestDto};
use crate::v1::gacha_rolls::gacha_rolls_repository::GachaRollRepository;
use crate::v1::gacha_rolls::gacha_rolls_schema::GachaRollSchema;
use crate::v1::gacha_credits::gacha_credits_repository::GachaCreditRepository;
use axum::http::{HeaderMap, StatusCode};
use axum::response::Response;
use imphnen_iam::UsersRepository;
use imphnen_utils::extract_email;
use uuid::Uuid;
pub struct GachaRollService;
impl GachaRollService {
pub async fn get_gacha_roll_by_id(state: &AppState, id: Uuid) -> Response {
let repo = GachaRollRepository::new(state);
match repo.query_gacha_roll_by_id(id).await {
Ok(roll) => success_response(ResponseSuccessDto {
data: GachaRollItemDto::from(&roll),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_roll(
headers: HeaderMap, // Add headers
state: &AppState,
payload: GachaRollRequestDto,
gacha_id: String, // Add gacha_id
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo_user = UsersRepository::new(state); // Need UsersRepository here
let Some(email) = extract_email(&headers) else {
return common_response(StatusCode::UNAUTHORIZED, "Unauthorized");
};
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
return common_response(StatusCode::NOT_FOUND, "User not found");
};
let schema = GachaRollSchema::create(payload, user.id.clone(), gacha_id); // Pass user.id and gacha_id
let repo = GachaRollRepository::new(state);
match repo.query_create_gacha_roll(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn execute_roll_once(headers: HeaderMap, state: &AppState) -> Response {
let repo = GachaRollRepository::new(state);
let repo_claim = GachaClaimRepository::new(state);
let repo_user = UsersRepository::new(state);
let repo_credits = GachaCreditRepository::new(state);
let Some(email) = extract_email(&headers) else {
return common_response(StatusCode::UNAUTHORIZED, "Unauthorized");
};
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
return common_response(StatusCode::NOT_FOUND, "User not found");
};
let parsed_user_id = match Uuid::parse_str(&user.id) {
Ok(uuid) => uuid,
Err(e) => return common_response(StatusCode::BAD_REQUEST, &format!("Invalid User ID format: {}", e)),
};
// Check if user has enough credits
let credit_opt = repo_credits.query_by_user_id(parsed_user_id).await;
let has_enough_credits = match credit_opt {
Ok(Some(credit)) => credit.available_rolls > 0,
Ok(None) => false, // No credit record means no credits
Err(e) => {
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
}
};
if !has_enough_credits {
return common_response(StatusCode::PAYMENT_REQUIRED, "Not enough credits to perform this action");
}
// Consume one credit
if let Err(e) = repo_credits.query_consume_credit(parsed_user_id).await { return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()) }
// Proceed with the roll
match repo.query_all_active_rolls().await {
Ok(rolls) => match GachaRollRepository::roll_once(&rolls) {
Some(roll) => {
let user_id_clone = user.id.clone();
let claim = GachaClaimSchema::roll(roll.clone(), user_id_clone);
match repo_claim.query_create_gacha_claim(claim).await {
Ok(_) => success_response(ResponseSuccessDto {
data: GachaRollItemDto::from(&roll),
}),
Err(e) => {
// Refund the credit if claim creation fails
let user_id = user.id.clone(); // Extract value before potential move
let _ = repo_credits.query_add_credit(crate::v1::gacha_credits::gacha_credits_dto::GachaCreditRequestDto {
user_id,
amount: 1,
}).await;
common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
}
}
}
None => common_response(StatusCode::NOT_FOUND, "No rollable item available"),
},
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn soft_delete_gacha_roll(state: &AppState, id: Uuid) -> Response {
let repo = GachaRollRepository::new(state);
match repo.query_soft_delete_gacha_roll(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
}
-26
View File
@@ -1,26 +0,0 @@
use axum::{
Router,
routing::{get, post},
};
pub mod gacha_rolls_controller;
pub mod gacha_rolls_dto;
pub mod gacha_rolls_repository;
pub mod gacha_rolls_schema;
pub mod gacha_rolls_service;
// Export only public API functions and types
pub use gacha_rolls_controller::{
post_create_gacha_roll,
post_execute_gacha_roll,
get_detail_gacha_roll,
};
pub use gacha_rolls_dto::GachaRollItemDto;
/// Creates router for gacha rolls endpoints
pub fn gacha_roll_router() -> Router {
Router::new()
.route("/create", post(post_create_gacha_roll))
.route("/execute", post(post_execute_gacha_roll))
.route("/detail/{id}", get(get_detail_gacha_roll))
}
-26
View File
@@ -1,26 +0,0 @@
use axum::Router;
pub mod gacha_claims;
pub mod gacha_credits;
pub mod gacha_items;
pub mod gacha_rolls;
use crate::v1::gacha_items::gacha_items_controller;
// Export only public router functions to avoid namespace pollution
pub use gacha_credits::gacha_credit_router;
pub use gacha_items::gacha_item_router;
pub use gacha_rolls::gacha_roll_router;
pub use gacha_claims::gacha_claim_router;
/// Creates the main gacha router with all version 1 endpoints
pub fn gacha_router() -> Router {
let mut router = Router::new();
router = router.nest("/credits", gacha_credit_router());
router = router.nest("/items", gacha_item_router());
router = router.nest("/rolls", gacha_roll_router());
router = router.nest("/claims", gacha_claim_router());
// Minimal admin router mounted at /admin to satisfy test.sh expectations
// This will expose GET /v1/gacha/admin -> list items (admin view)
router = router.nest("/admin", Router::new().route("/", axum::routing::get(gacha_items_controller::get_gacha_item_list)));
router
}