feat: add gacha credits
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
use crate::{
|
||||
AppState, GachaRollItemDto, GachaRollRequestDto, GachaRollService,
|
||||
MessageResponseDto, ResponseSuccessDto,
|
||||
};
|
||||
use axum::{
|
||||
Extension, Json, extract::Path, http::HeaderMap, response::IntoResponse,
|
||||
};
|
||||
use imphnen_iam::{PermissionsEnum, permissions_guard};
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/gacha/rolls/detail/{id}",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
params(("id" = String, Path, description = "Gacha Roll ID")),
|
||||
responses(
|
||||
(status = 200, description = "Get Gacha Roll by ID", body = ResponseSuccessDto<GachaRollItemDto>)
|
||||
),
|
||||
tag = "Gacha"
|
||||
)]
|
||||
pub async fn get_detail_gacha_roll(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadDetailGachaRolls],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => GachaRollService::get_gacha_roll_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/gacha/rolls/create",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
request_body = GachaRollRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "Create new gacha roll", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Gacha"
|
||||
)]
|
||||
pub async fn post_create_gacha_roll(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<GachaRollRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::CreateGachaRolls],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => GachaRollService::create_gacha_roll(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/gacha/rolls/execute",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Execute and get 1 gacha result", body = ResponseSuccessDto<GachaRollItemDto>)
|
||||
),
|
||||
tag = "Gacha"
|
||||
)]
|
||||
pub async fn post_execute_gacha_roll(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ExecuteGachaRolls],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => GachaRollService::execute_roll_once(headers, &state).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use crate::{GachaItemDto, GachaItemSchema};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct GachaRollRequestDto {
|
||||
#[validate(length(min = 1, message = "Item ID must not be empty"))]
|
||||
pub item_id: String,
|
||||
pub weight: f32,
|
||||
#[validate(range(min = 1, message = "Quantity must be at least 1"))]
|
||||
pub quantity: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GachaRollItemDto {
|
||||
pub id: String,
|
||||
pub item: GachaItemDto,
|
||||
pub weight: f32,
|
||||
pub quantity: i32,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl GachaRollItemDto {
|
||||
pub fn from(dto: &GachaRollQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.id.to_raw(),
|
||||
item: GachaItemDto::from(dto.item.clone()),
|
||||
weight: dto.weight.clone(),
|
||||
quantity: dto.quantity,
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaRollQueryDto {
|
||||
pub id: Thing,
|
||||
pub item: GachaItemSchema,
|
||||
pub weight: f32,
|
||||
pub quantity: i32,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use super::GachaRollQueryDto;
|
||||
use super::GachaRollSchema;
|
||||
use crate::{AppState, DetailQueryBuilder, ResourceEnum};
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_iam::ListQueryBuilder;
|
||||
use rand::prelude::*;
|
||||
use rand::rng;
|
||||
use rand_distr::weighted::WeightedIndex;
|
||||
|
||||
pub struct GachaRollRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> GachaRollRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_gacha_roll_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<GachaRollQueryDto> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
|
||||
.with_id(id.clone())
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch("item");
|
||||
let sql = builder.build();
|
||||
let result: Option<GachaRollQueryDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
match result {
|
||||
Some(roll) if !roll.is_deleted => Ok(roll),
|
||||
_ => bail!("Gacha Roll not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_create_gacha_roll(
|
||||
&self,
|
||||
data: GachaRollSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<GachaRollSchema> = db
|
||||
.create(ResourceEnum::GachaRolls.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success create Gacha Roll".into()),
|
||||
None => bail!("Failed to create Gacha Roll"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_all_active_rolls(&self) -> Result<Vec<GachaRollQueryDto>> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = ListQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch(Some(vec!["item"]));
|
||||
let sql = builder.build();
|
||||
let result: Vec<GachaRollQueryDto> = db.query(sql).await?.take(0)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn roll_once(rolls: &[GachaRollQueryDto]) -> Option<GachaRollQueryDto> {
|
||||
let filtered: Vec<_> = rolls
|
||||
.iter()
|
||||
.filter(|r| !r.is_deleted && r.quantity > 0)
|
||||
.collect();
|
||||
let weights: Vec<f32> = filtered
|
||||
.iter()
|
||||
.map(|r| r.weight * r.quantity as f32)
|
||||
.collect();
|
||||
if weights.iter().all(|&w| w <= 0.0) {
|
||||
return None;
|
||||
}
|
||||
let dist = WeightedIndex::new(&weights).ok()?;
|
||||
let mut rng = rng();
|
||||
let index = dist.sample(&mut rng);
|
||||
Some(filtered[index].clone())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use crate::{ResourceEnum, make_thing};
|
||||
use imphnen_iam::get_iso_date;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
|
||||
use super::GachaRollRequestDto;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct GachaRollSchema {
|
||||
pub id: Thing,
|
||||
pub item: Thing,
|
||||
pub weight: f32,
|
||||
pub quantity: i32,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for GachaRollSchema {
|
||||
fn default() -> Self {
|
||||
GachaRollSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaRolls.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
item: make_thing(
|
||||
&ResourceEnum::GachaItems.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
weight: 0.0,
|
||||
quantity: 0,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GachaRollSchema {
|
||||
pub fn create(dto: GachaRollRequestDto) -> Self {
|
||||
Self {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaRolls.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
item: make_thing(&ResourceEnum::GachaItems.to_string(), &dto.item_id),
|
||||
weight: dto.weight,
|
||||
quantity: dto.quantity,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use crate::{
|
||||
AppState, GachaClaimRepository, GachaClaimSchema, GachaRollItemDto,
|
||||
GachaRollRepository, GachaRollRequestDto, GachaRollSchema, ResponseSuccessDto,
|
||||
common_response, success_response, validate_request,
|
||||
};
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::Response;
|
||||
use imphnen_iam::{UsersRepository, extract_email};
|
||||
|
||||
pub struct GachaRollService;
|
||||
|
||||
impl GachaRollService {
|
||||
pub async fn get_gacha_roll_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = GachaRollRepository::new(state);
|
||||
match repo.query_gacha_roll_by_id(id).await {
|
||||
Ok(roll) => success_response(ResponseSuccessDto {
|
||||
data: GachaRollItemDto::from(&roll),
|
||||
}),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_gacha_roll(
|
||||
state: &AppState,
|
||||
payload: GachaRollRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let schema = GachaRollSchema::create(payload);
|
||||
let repo = GachaRollRepository::new(state);
|
||||
match repo.query_create_gacha_roll(schema).await {
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn execute_roll_once(headers: HeaderMap, state: &AppState) -> Response {
|
||||
let repo = GachaRollRepository::new(state);
|
||||
let repo_claim = GachaClaimRepository::new(state);
|
||||
let repo_user = UsersRepository::new(state);
|
||||
let Some(email) = extract_email(&headers) else {
|
||||
return common_response(StatusCode::UNAUTHORIZED, "Unauthorized");
|
||||
};
|
||||
let Ok(user) = repo_user.query_user_by_email(email.to_string()).await else {
|
||||
return common_response(StatusCode::NOT_FOUND, "User not found");
|
||||
};
|
||||
match repo.query_all_active_rolls().await {
|
||||
Ok(rolls) => match GachaRollRepository::roll_once(&rolls) {
|
||||
Some(roll) => {
|
||||
let claim = GachaClaimSchema::roll(roll.clone(), user.id);
|
||||
match repo_claim.query_create_gacha_claim(claim).await {
|
||||
Ok(_) => success_response(ResponseSuccessDto {
|
||||
data: GachaRollItemDto::from(&roll),
|
||||
}),
|
||||
Err(e) => {
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
None => common_response(StatusCode::NOT_FOUND, "No rollable item available"),
|
||||
},
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
pub mod gacha_rolls_controller;
|
||||
pub mod gacha_rolls_dto;
|
||||
pub mod gacha_rolls_repository;
|
||||
pub mod gacha_rolls_schema;
|
||||
pub mod gacha_rolls_service;
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{get, post},
|
||||
};
|
||||
pub use gacha_rolls_controller::*;
|
||||
pub use gacha_rolls_dto::*;
|
||||
pub use gacha_rolls_repository::*;
|
||||
pub use gacha_rolls_schema::*;
|
||||
pub use gacha_rolls_service::*;
|
||||
|
||||
pub fn gacha_roll_router() -> Router {
|
||||
Router::new()
|
||||
.route("/create", post(post_create_gacha_roll))
|
||||
.route("/execute", post(post_execute_gacha_roll))
|
||||
.route("/detail/{id}", get(get_detail_gacha_roll))
|
||||
}
|
||||
Reference in New Issue
Block a user