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,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(())
}
}