feat: v0.3.0 — standardize codebase, centralize infra, merge QR into CMS

- Enforce axum best practices across all 13 workspace crates
  (max 200 LOC/file, no comments, no unwrap, clean architecture)
- Fix domain→infrastructure dependency inversions in imphnen-iam and imphnen-dimentorin
- Extract imphnen-storage (MinIO) and imphnen-email (Lettre) as standalone crates
- Centralize all config in ENV struct: CDN_URL, CORS_ALLOWED_ORIGINS
- Centralize SMTP through imphnen-email; remove dead HackathonConfig
- Centralize database: QR crate now shares main DB pool (single DATABASE_URL)
- Rename QR users table to qr_users to avoid collision with main users table
- Merge imphnen-qr into imphnen-cms/src/qr (13 crates, down from 14)
- Restructure imphnen-hackathon flat modules into clean architecture
- Remove all stale env vars from .env.example (SurrealDB, QR_JWT, Hackathon infra)
- Fix Dockerfile to include all current workspace crates
- Bump all crate versions 0.2.0 → 0.3.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
maulanasdqn
2026-04-02 22:29:08 +07:00
co-authored by Claude Sonnet 4.6
parent 2ae43b3bcc
commit 331a4a4e88
442 changed files with 22226 additions and 18700 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "imphnen-gacha"
version = "0.2.0"
version = "0.3.0"
edition = "2024"
[dependencies]
@@ -1,28 +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,
GachaClaimDetail, GachaClaimEntity, GachaClaimRepository, GachaClaimService,
};
use async_trait::async_trait;
use imphnen_utils::AppError;
use std::sync::Arc;
use uuid::Uuid;
pub struct GachaClaimServiceImpl {
repo: Arc<dyn GachaClaimRepository>,
repo: Arc<dyn GachaClaimRepository>,
}
impl GachaClaimServiceImpl {
pub fn new(repo: Arc<dyn GachaClaimRepository>) -> Self {
Self { repo }
}
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 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
}
async fn create_claim(&self, entity: GachaClaimEntity) -> Result<(), AppError> {
self.repo.create(entity).await
}
}
@@ -1,33 +1,32 @@
use crate::gacha_items::domain::gacha_item::GachaItemEntity;
use chrono::{DateTime, Utc};
use imphnen_entities::UsersDetailQueryDto;
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>>,
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>,
pub id: Uuid,
pub user: UsersDetailQueryDto,
pub item: GachaItemEntity,
pub is_deleted: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -1,10 +1,10 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_claim::{GachaClaimDetail, GachaClaimEntity};
use async_trait::async_trait;
use imphnen_utils::AppError;
use uuid::Uuid;
#[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>;
async fn find_by_id(&self, id: Uuid) -> Result<GachaClaimDetail, AppError>;
async fn create(&self, entity: GachaClaimEntity) -> Result<(), AppError>;
}
@@ -1,10 +1,10 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_claim::{GachaClaimDetail, GachaClaimEntity};
use async_trait::async_trait;
use imphnen_utils::AppError;
use uuid::Uuid;
#[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>;
async fn get_claim(&self, id: Uuid) -> Result<GachaClaimDetail, AppError>;
async fn create_claim(&self, entity: GachaClaimEntity) -> Result<(), AppError>;
}
@@ -1,41 +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;
use imphnen_iam::users::infrastructure::http::dto::UsersDetailItemDto;
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaClaimCreateRequestDto {
pub user_id: String,
pub item_id: String,
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())
}
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,
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(),
}
}
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(),
}
}
}
@@ -1,13 +1,13 @@
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};
use axum::{Extension, extract::Path, http::HeaderMap, response::IntoResponse};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::AppError;
use imphnen_utils::{ApiMessage, ApiSuccess};
use std::sync::Arc;
use uuid::Uuid;
#[utoipa::path(
get,
@@ -22,17 +22,17 @@ use crate::gacha_claims::domain::{GachaClaimEntity, GachaClaimService};
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>,
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)))
})
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(
@@ -46,32 +46,34 @@ pub async fn get_gacha_claim_by_id(
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>,
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"))
})
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"))
})
}
@@ -1,20 +1,29 @@
use std::sync::Arc;
use axum::{Router, routing::{get, post}, Extension};
use sea_orm::DatabaseConnection;
use super::handlers::{get_gacha_claim_by_id, post_create_gacha_claim};
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};
use axum::{
Extension, Router,
routing::{get, post},
};
use sea_orm::DatabaseConnection;
use std::sync::Arc;
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))
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))
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))
}
@@ -1,105 +1,109 @@
use std::sync::Arc;
use crate::gacha_claims::domain::{
gacha_claim::{GachaClaimDetail, GachaClaimEntity},
repository::GachaClaimRepository,
};
use crate::gacha_items::domain::gacha_item::GachaItemEntity;
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,
ActiveModel as GachaClaimsActiveModel, Entity as GachaClaimsEntity,
};
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;
use imphnen_utils::AppError;
use sea_orm::ActiveValue;
use sea_orm::prelude::*;
use std::sync::Arc;
use uuid::Uuid;
pub struct PostgresGachaClaimRepository {
db: Arc<DatabaseConnection>,
state: Arc<AppState>,
db: Arc<DatabaseConnection>,
state: Arc<AppState>,
}
impl PostgresGachaClaimRepository {
pub fn new(db: DatabaseConnection, state: Arc<AppState>) -> Self {
Self {
db: Arc::new(db),
state,
}
}
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()))?;
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 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_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,
};
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,
})
}
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),
};
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()))?;
GachaClaimsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
Ok(())
}
}
@@ -1,30 +1,35 @@
use std::sync::Arc;
use crate::gacha_credits::domain::{
GachaCreditEntity, GachaCreditRepository, GachaCreditService,
};
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::gacha_credits::domain::{GachaCreditEntity, GachaCreditRepository, GachaCreditService};
use std::sync::Arc;
use uuid::Uuid;
pub struct GachaCreditServiceImpl {
repo: Arc<dyn GachaCreditRepository>,
repo: Arc<dyn GachaCreditRepository>,
}
impl GachaCreditServiceImpl {
pub fn new(repo: Arc<dyn GachaCreditRepository>) -> Self {
Self { repo }
}
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 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 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
}
async fn consume_credit(&self, user_id: Uuid) -> Result<(), AppError> {
self.repo.consume_credit(user_id).await
}
}
@@ -3,10 +3,10 @@ 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>,
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>,
}
@@ -1,11 +1,14 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_credit::GachaCreditEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use uuid::Uuid;
#[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>;
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>;
}
@@ -1,11 +1,14 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_credit::GachaCreditEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use uuid::Uuid;
#[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>;
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>;
}
@@ -1,38 +1,38 @@
use crate::gacha_credits::domain::gacha_credit::GachaCreditEntity;
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,
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())
}
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>,
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()),
}
}
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()),
}
}
}
@@ -1,13 +1,13 @@
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;
use axum::{Extension, http::HeaderMap, response::IntoResponse};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::AppError;
use imphnen_utils::{ApiMessage, ApiSuccess, extract_email};
use std::sync::Arc;
use uuid::Uuid;
#[utoipa::path(
get,
@@ -19,30 +19,38 @@ use crate::gacha_credits::domain::GachaCreditService;
tag = "Gacha"
)]
pub async fn get_user_credits(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaCreditService>>,
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,
})),
}
})
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(
@@ -56,21 +64,32 @@ pub async fn get_user_credits(
tag = "Gacha"
)]
pub async fn post_add_credits(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaCreditService>>,
ValidatedJson(payload): ValidatedJson<GachaCreditAddRequestDto>,
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)))
})
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(
@@ -83,18 +102,26 @@ pub async fn post_add_credits(
tag = "Gacha"
)]
pub async fn post_consume_credit(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaCreditService>>,
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"))
})
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"))
}
)
}
@@ -1,21 +1,24 @@
use std::sync::Arc;
use axum::{Router, routing::{get, post}, Extension};
use sea_orm::DatabaseConnection;
use super::handlers::{get_user_credits, post_add_credits, post_consume_credit};
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};
use axum::{
Extension, Router,
routing::{get, post},
};
use sea_orm::DatabaseConnection;
use std::sync::Arc;
fn build_service(db: DatabaseConnection) -> Arc<dyn GachaCreditService> {
let repo = Arc::new(PostgresGachaCreditRepository::new(db));
Arc::new(GachaCreditServiceImpl::new(repo))
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))
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))
}
@@ -1,105 +1,116 @@
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,
};
use crate::gacha_credits::domain::{gacha_credit::GachaCreditEntity, repository::GachaCreditRepository};
use async_trait::async_trait;
use imphnen_entities::seaorm::gacha::gacha_credits::{
self, ActiveModel as GachaCreditsActiveModel, Column as GachaCreditsColumn,
Entity as GachaCreditsEntity,
};
use imphnen_utils::AppError;
use sea_orm::ActiveValue;
use sea_orm::prelude::*;
use std::sync::Arc;
use uuid::Uuid;
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,
}
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>,
db: Arc<DatabaseConnection>,
}
impl PostgresGachaCreditRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
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()))?;
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))
}
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()))?;
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()))?;
}
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(())
}
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()))?;
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()));
}
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()));
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()))?;
GachaCreditsEntity::update(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
Ok(())
}
}
@@ -1,40 +1,45 @@
use std::sync::Arc;
use crate::gacha_items::domain::{
GachaItemEntity, GachaItemRepository, GachaItemService,
};
use async_trait::async_trait;
use imphnen_utils::AppError;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use std::sync::Arc;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::gacha_items::domain::{GachaItemEntity, GachaItemRepository, GachaItemService};
pub struct GachaItemServiceImpl {
repo: Arc<dyn GachaItemRepository>,
repo: Arc<dyn GachaItemRepository>,
}
impl GachaItemServiceImpl {
pub fn new(repo: Arc<dyn GachaItemRepository>) -> Self {
Self { repo }
}
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 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 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 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 update(&self, entity: GachaItemEntity) -> Result<(), AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
async fn delete(&self, id: Uuid) -> Result<(), AppError> {
self.repo.delete(id).await
}
}
@@ -4,20 +4,20 @@ 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>>,
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>>,
}
@@ -1,15 +1,18 @@
use super::gacha_item::GachaItemEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
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>;
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>;
}
@@ -1,15 +1,18 @@
use super::gacha_item::GachaItemEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
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>;
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>;
}
@@ -1,92 +1,92 @@
use crate::gacha_items::domain::gacha_item::GachaItemEntity;
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>,
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())
}
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,
}
}
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>,
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())
}
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>,
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()),
}
}
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()),
}
}
}
@@ -1,15 +1,17 @@
use std::sync::Arc;
use super::dto::{
GachaItemCreateRequestDto, GachaItemDto, GachaItemUpdateRequestDto,
};
use crate::gacha_items::domain::{GachaItemEntity, GachaItemService};
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_libs::{AppState, ValidatedJson};
use imphnen_utils::AppError;
use super::dto::{GachaItemCreateRequestDto, GachaItemDto, GachaItemUpdateRequestDto};
use crate::gacha_items::domain::{GachaItemEntity, GachaItemService};
use imphnen_utils::{ApiMessage, ApiPaginated, ApiSuccess};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use std::sync::Arc;
use uuid::Uuid;
#[utoipa::path(
get,
@@ -28,19 +30,23 @@ use crate::gacha_items::domain::{GachaItemEntity, GachaItemService};
tag = "Gacha"
)]
pub async fn get_gacha_item_list(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaItemService>>,
PaginationQuery(params): PaginationQuery,
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))
})
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(
@@ -56,17 +62,17 @@ pub async fn get_gacha_item_list(
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>,
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)))
})
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(
@@ -80,16 +86,16 @@ pub async fn get_gacha_item_by_id(
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>,
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"))
})
require_permissions!(headers, state, [PermissionsEnum::CreateGachaItems], {
let entity: GachaItemEntity = payload.into();
service.create(entity).await?;
Ok(ApiMessage::created("Gacha item created"))
})
}
#[utoipa::path(
@@ -106,37 +112,37 @@ pub async fn post_create_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>,
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"))
})
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(
@@ -152,15 +158,15 @@ pub async fn put_update_gacha_item(
tag = "Gacha"
)]
pub async fn delete_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaItemService>>,
Path(id): Path<String>,
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"))
})
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"))
})
}
@@ -1,26 +1,29 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, post, put}, Extension};
use sea_orm::DatabaseConnection;
use super::handlers::{
delete_gacha_item, get_gacha_item_by_id, get_gacha_item_list,
post_create_gacha_item, put_update_gacha_item,
};
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,
use axum::{
Extension, Router,
routing::{delete, get, post, put},
};
use sea_orm::DatabaseConnection;
use std::sync::Arc;
fn build_service(db: DatabaseConnection) -> Arc<dyn GachaItemService> {
let repo = Arc::new(PostgresGachaItemRepository::new(db));
Arc::new(GachaItemServiceImpl::new(repo))
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))
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))
}
@@ -1,170 +1,180 @@
use std::sync::Arc;
use crate::gacha_items::domain::{
gacha_item::GachaItemEntity, repository::GachaItemRepository,
};
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, QueryOrder, PaginatorTrait};
use imphnen_entities::seaorm::gacha::gacha_items::{
ActiveModel as GachaItemsActiveModel, Column as GachaItemsColumn,
Entity as GachaItemsEntity, Model as GachaItemsModel,
};
use imphnen_utils::AppError;
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, PaginatorTrait, QueryOrder};
use std::sync::Arc;
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,
}
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>,
db: Arc<DatabaseConnection>,
}
impl PostgresGachaItemRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
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);
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());
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));
}
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),
},
};
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 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 })
}
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()))?;
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))
}
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),
};
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()))?;
GachaItemsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
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();
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.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()))?;
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
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();
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.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()))?;
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
Ok(())
}
}
@@ -1,141 +1,139 @@
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};
use crate::gacha_rolls::domain::{
GachaRollEntity, GachaRollRepository, GachaRollService,
};
use async_trait::async_trait;
use imphnen_utils::AppError;
use rand::prelude::*;
use std::sync::Arc;
use uuid::Uuid;
pub struct GachaRollServiceImpl {
roll_repo: Arc<dyn GachaRollRepository>,
credit_repo: Arc<dyn GachaCreditRepository>,
claim_repo: Arc<dyn GachaClaimRepository>,
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,
}
}
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();
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;
}
if filtered.is_empty() {
return None;
}
let total_weight: f64 = filtered
.iter()
.map(|r| f64::from(r.weight) * f64::from(r.quantity))
.sum();
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());
}
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 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());
}
}
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())
}
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 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 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()))?;
async fn execute_roll(&self, user_id: Uuid) -> Result<GachaRollEntity, AppError> {
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(),
));
}
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?;
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())
})?;
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 = 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);
}
};
let selected = match selected {
Ok(r) => r,
Err(e) => {
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,
};
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);
}
if let Err(e) = self.claim_repo.create(claim_entity).await {
let _ = self.credit_repo.add_credit(user_id, 1).await;
return Err(e);
}
// 7. Return selected roll entity
Ok(selected)
}
Ok(selected)
}
async fn delete_roll(&self, id: Uuid) -> Result<(), AppError> {
self.roll_repo.delete(id).await
}
async fn delete_roll(&self, id: Uuid) -> Result<(), AppError> {
self.roll_repo.delete(id).await
}
}
@@ -3,13 +3,13 @@ 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>,
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>,
}
@@ -1,12 +1,12 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_roll::GachaRollEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use uuid::Uuid;
#[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>;
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>;
}
@@ -1,12 +1,12 @@
use async_trait::async_trait;
use uuid::Uuid;
use imphnen_utils::AppError;
use super::gacha_roll::GachaRollEntity;
use async_trait::async_trait;
use imphnen_utils::AppError;
use uuid::Uuid;
#[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>;
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>;
}
@@ -1,46 +1,46 @@
use crate::gacha_rolls::domain::gacha_roll::GachaRollEntity;
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,
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())
}
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>,
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()),
}
}
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()),
}
}
}
@@ -1,13 +1,13 @@
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};
use axum::{Extension, extract::Path, http::HeaderMap, response::IntoResponse};
use imphnen_entities::ResponseSuccessDto;
use imphnen_iam::{PermissionsEnum, require_permissions};
use imphnen_libs::{AppState, ValidatedJson};
use imphnen_utils::AppError;
use imphnen_utils::{ApiMessage, ApiSuccess, extract_email};
use std::sync::Arc;
use uuid::Uuid;
#[utoipa::path(
get,
@@ -22,17 +22,17 @@ use crate::gacha_rolls::domain::{GachaRollEntity, GachaRollService};
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>,
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)))
})
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(
@@ -46,34 +46,43 @@ pub async fn get_gacha_roll_by_id(
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>,
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"))
})
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(
@@ -86,20 +95,28 @@ pub async fn post_create_gacha_roll(
tag = "Gacha"
)]
pub async fn post_execute_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
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)))
})
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(
@@ -115,15 +132,15 @@ pub async fn post_execute_gacha_roll(
tag = "Gacha"
)]
pub async fn delete_gacha_roll(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn GachaRollService>>,
Path(id): Path<String>,
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"))
})
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"))
})
}
@@ -1,31 +1,42 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, post}, Extension};
use sea_orm::DatabaseConnection;
use super::handlers::{
delete_gacha_roll, get_gacha_roll_by_id, post_create_gacha_roll,
post_execute_gacha_roll,
};
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,
use axum::{
Extension, Router,
routing::{delete, get, post},
};
use sea_orm::DatabaseConnection;
use std::sync::Arc;
fn build_service(
db: DatabaseConnection,
state: Arc<imphnen_libs::AppState>,
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))
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))
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))
}
@@ -1,100 +1,102 @@
use std::sync::Arc;
use crate::gacha_rolls::domain::{
gacha_roll::GachaRollEntity, repository::GachaRollRepository,
};
use async_trait::async_trait;
use imphnen_entities::seaorm::gacha::gacha_rolls::{
ActiveModel as GachaRollActiveModel, Column as GachaRollColumn,
Entity as GachaRollsEntity, Model as GachaRollModel,
};
use imphnen_utils::AppError;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, QueryFilter};
use std::sync::Arc;
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,
}
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>,
db: Arc<DatabaseConnection>,
}
impl PostgresGachaRollRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
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()))?;
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))
}
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()))?;
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())
}
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())),
};
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()))?;
GachaRollsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
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();
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.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()))?;
active_model
.update(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(())
}
Ok(())
}
}
+33 -26
View File
@@ -1,37 +1,44 @@
pub mod gacha_items;
pub mod gacha_credits;
pub mod gacha_claims;
pub mod gacha_credits;
pub mod gacha_items;
pub mod gacha_rolls;
pub use imphnen_libs::AppState;
pub use imphnen_entities::{
ResponseListSuccessDto,
ResponseSuccessDto,
MessageResponseDto,
PermissionsEnum,
MessageResponseDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
};
pub use imphnen_libs::AppState;
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;
use gacha_credits::gacha_credit_router;
use gacha_items::gacha_item_router;
use gacha_rolls::gacha_roll_router;
use sea_orm::DatabaseConnection;
use std::sync::Arc;
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
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
}