feat: add gacha and init cms

This commit is contained in:
Maulana Sodiqin
2025-05-20 10:45:01 +07:00
parent f4b0ed0a4a
commit e63658c082
35 changed files with 976 additions and 171 deletions
Generated
+84 -74
View File
@@ -173,9 +173,9 @@ checksum = "ea50b14b7a4b9343f8c627a7a53c52076482bd4bdad0a24fd3ec533ed616cc2c"
[[package]]
name = "anyhow"
version = "1.0.97"
version = "1.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"
checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
[[package]]
name = "approx"
@@ -407,9 +407,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "axum"
version = "0.8.3"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de45108900e1f9b9242f7f2e254aa3e2c029c921c258fe9e6b4217eeebd54288"
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
dependencies = [
"axum-core",
"bytes",
@@ -786,9 +786,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chrono"
version = "0.4.40"
version = "0.4.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c"
checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d"
dependencies = [
"android-tzdata",
"iana-time-zone",
@@ -1092,10 +1092,10 @@ dependencies = [
]
[[package]]
name = "doc-comment"
version = "0.3.3"
name = "double-ended-peekable"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
checksum = "c0d05e1c0dbad51b52c38bda7adceef61b9efc2baf04acfe8726a8c4630a6f57"
[[package]]
name = "earcutr"
@@ -1464,7 +1464,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62ddb1950450d67efee2bbc5e429c68d052a822de3aad010d28b351fbb705224"
dependencies = [
"approx 0.5.1",
"arbitrary",
"num-traits",
"rstar",
"serde",
@@ -1571,12 +1570,6 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "heck"
version = "0.5.0"
@@ -1940,7 +1933,31 @@ dependencies = [
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
"surrealdb",
"tokio",
"tower-http",
"utoipa",
"utoipa-swagger-ui",
"validator",
]
[[package]]
name = "imphnen-cms"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"axum-test",
"chrono",
"imphnen-entities",
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -1964,7 +1981,7 @@ dependencies = [
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -1996,10 +2013,12 @@ dependencies = [
"axum-test",
"chrono",
"imphnen-entities",
"imphnen-iam",
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"rand_distr",
"regex",
"serde",
"serde_json",
@@ -2020,12 +2039,13 @@ dependencies = [
"axum-test",
"chrono",
"imphnen-entities",
"imphnen-gacha",
"imphnen-iam",
"imphnen-libs",
"imphnen-middleware",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -2049,7 +2069,7 @@ dependencies = [
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -2071,6 +2091,7 @@ dependencies = [
"imphnen-entities",
"jsonwebtoken",
"lettre",
"log",
"serde",
"surrealdb",
"tokio",
@@ -2090,7 +2111,7 @@ dependencies = [
"imphnen-libs",
"imphnen-utils",
"lazy_static",
"rand 0.9.0",
"rand 0.9.1",
"regex",
"serde",
"serde_json",
@@ -2113,7 +2134,7 @@ dependencies = [
"chrono",
"imphnen-entities",
"imphnen-libs",
"rand 0.9.0",
"rand 0.9.1",
"serde",
"serde_json",
"surrealdb",
@@ -2183,9 +2204,9 @@ dependencies = [
[[package]]
name = "itertools"
version = "0.13.0"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
@@ -2284,9 +2305,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "lettre"
version = "0.11.15"
version = "0.11.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "759bc2b8eabb6a30b235d6f716f7f36479f4b38cbe65b8747aefee51f89e8437"
checksum = "87ffd14fa289730e3ad68edefdc31f603d56fe716ec38f2076bb7410e09147c2"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -2698,23 +2719,26 @@ dependencies = [
[[package]]
name = "object_store"
version = "0.10.2"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6da452820c715ce78221e8202ccc599b4a52f3e1eb3eedb487b680c81a8e3f3"
checksum = "d94ac16b433c0ccf75326388c893d2835ab7457ea35ab8ba5d745c053ef5fa16"
dependencies = [
"async-trait",
"bytes",
"chrono",
"futures",
"http",
"humantime",
"itertools 0.13.0",
"itertools 0.14.0",
"parking_lot",
"percent-encoding",
"snafu",
"thiserror 2.0.12",
"tokio",
"tracing",
"url",
"walkdir",
"wasm-bindgen-futures",
"web-time",
]
[[package]]
@@ -3131,7 +3155,7 @@ checksum = "b820744eb4dc9b57a3398183639c511b5a26d2ed702cedd3febaa1393caa22cc"
dependencies = [
"bytes",
"getrandom 0.3.2",
"rand 0.9.0",
"rand 0.9.1",
"ring",
"rustc-hash",
"rustls",
@@ -3208,13 +3232,12 @@ dependencies = [
[[package]]
name = "rand"
version = "0.9.0"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94"
checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.3",
"zerocopy 0.8.24",
]
[[package]]
@@ -3255,6 +3278,16 @@ dependencies = [
"getrandom 0.3.2",
]
[[package]]
name = "rand_distr"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"
dependencies = [
"num-traits",
"rand 0.9.1",
]
[[package]]
name = "rawpointer"
version = "0.2.1"
@@ -3614,7 +3647,7 @@ dependencies = [
"futures-util",
"http",
"mime",
"rand 0.9.0",
"rand 0.9.1",
"thiserror 2.0.12",
]
@@ -4008,28 +4041,6 @@ dependencies = [
"serde",
]
[[package]]
name = "snafu"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4de37ad025c587a29e8f3f5605c00f70b98715ef90b9061a815b9e59e9042d6"
dependencies = [
"doc-comment",
"snafu-derive",
]
[[package]]
name = "snafu-derive"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990079665f075b699031e9c08fd3ab99be5029b96f3b78dc0709e8f77e4efebf"
dependencies = [
"heck 0.4.1",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "snap"
version = "1.1.1"
@@ -4147,7 +4158,7 @@ version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [
"heck 0.5.0",
"heck",
"proc-macro2",
"quote",
"rustversion",
@@ -4162,9 +4173,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "surrealdb"
version = "2.2.1"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa1aa87197bad9dd12c93350533a8da09bae064a411f445c97ca0e64faabc304"
checksum = "12a5a2d3f0d40d8b0bc2e3a327663c0cdffe7d35508ccabc810dab8281cf251d"
dependencies = [
"arrayvec",
"async-channel",
@@ -4173,6 +4184,7 @@ dependencies = [
"dmp",
"futures",
"geo",
"getrandom 0.3.2",
"indexmap 2.9.0",
"path-clean",
"pharos",
@@ -4203,9 +4215,9 @@ dependencies = [
[[package]]
name = "surrealdb-core"
version = "2.2.1"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ceb9f421e07af67b06c57ea7a8b08c3b4e4677de483435ca6d69bd00600a571"
checksum = "032f20c01cf3a5569f47c857da280abb7b6ff1e443bf58b993c3c28d2d802859"
dependencies = [
"addr",
"affinitypool",
@@ -4234,6 +4246,7 @@ dependencies = [
"fuzzy-matcher",
"geo",
"geo-types",
"getrandom 0.3.2",
"hex",
"http",
"ipnet",
@@ -4294,24 +4307,21 @@ dependencies = [
[[package]]
name = "surrealkv"
version = "0.8.1"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e28eec56aca077c245bf5f9e08876fdcce58b5361e77a0b94a92fd47e1990ad4"
checksum = "6d43d55edab1e65c7704486016f98e9eac61c97474921dbac094af2cd16e16c3"
dependencies = [
"ahash 0.8.11",
"async-channel",
"bytes",
"chrono",
"crc32fast",
"futures",
"double-ended-peekable",
"getrandom 0.2.15",
"lru",
"parking_lot",
"quick_cache 0.6.12",
"revision 0.10.0",
"tokio",
"vart 0.9.2",
"wasm-bindgen-futures",
]
[[package]]
@@ -4544,9 +4554,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.44.2"
version = "1.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165"
dependencies = [
"backtrace",
"bytes",
@@ -4654,9 +4664,9 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.2"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697"
checksum = "0fdb0c213ca27a9f57ab69ddb290fd80d970922355b83ae380b395d3986b8a2e"
dependencies = [
"bitflags",
"bytes",
@@ -4766,7 +4776,7 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "470dbf6591da1b39d43c14523b2b469c86879a53e8b758c8e090a470fe7b1fbe"
dependencies = [
"rand 0.9.0",
"rand 0.9.1",
"serde",
"web-time",
]
+11 -9
View File
@@ -3,6 +3,7 @@ resolver = "2"
members = [
"tests",
"imphnen-iam",
"imphnen-cms",
"imphnen-libs",
"imphnen-utils",
"imphnen-gacha",
@@ -15,22 +16,23 @@ members = [
[workspace.dependencies]
axum = { version = "0.8.1", features = ["multipart"] }
axum = { version = "0.8.4", features = ["multipart"] }
log = "0.4.25"
serde = { version = "1.0.217", features = ["derive"] }
serde_json = "1.0.138"
tokio = { version = "1.43.0" }
tokio = { version = "1.45.0" }
argon2 = { version = "0.5.3", features = ["password-hash"] }
jsonwebtoken = "9.3.1"
chrono = "0.4.39"
chrono = "0.4.41"
utoipa = { version = "5.3.1", features = ["axum_extras"] }
utoipa-swagger-ui = { version = "9.0.0", features = ["axum"] }
lettre = { version = "0.11.12", features = ["tokio1-native-tls"] }
surrealdb = { version = "2.2.1", features = ["kv-mem"] }
thiserror = "2.0.11"
anyhow = "1.0.97"
rand = "0.9.0"
tower-http = { version = "0.6.2", features = ["cors"] }
lettre = { version = "0.11.16", features = ["tokio1-native-tls"] }
surrealdb = { version = "2.3.2", features = ["kv-mem"] }
thiserror = "2.0.12"
anyhow = "1.0.98"
rand = { version = "0.9.1", features = ["std", "alloc"] }
rand_distr = "0.5.1"
tower-http = { version = "0.6.4", features = ["cors"] }
validator = { version = "0.12", features = ["derive"] }
lazy_static = "1.4.0"
regex = "1.11.1"
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "imphnen-cms"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
axum.workspace = true
serde.workspace = true
serde_json.workspace = true
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
validator.workspace = true
axum-test.workspace = true
surrealdb.workspace = true
rand.workspace = true
tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
+14
View File
@@ -0,0 +1,14 @@
pub fn add(left: u64, right: u64) -> u64 {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
View File
View File
+2
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-iam ={ version = "0.1.0", path = "../imphnen-iam" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
@@ -22,3 +23,4 @@ chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
rand_distr.workspace = true
+1
View File
@@ -3,6 +3,7 @@ use imphnen_libs::*;
use imphnen_utils::*;
pub mod v1;
pub use imphnen_entities::*;
pub use imphnen_libs::*;
pub use imphnen_utils::*;
@@ -0,0 +1,66 @@
use axum::Extension;
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use axum::{Json, extract::Path};
use imphnen_iam::{PermissionsEnum, permissions_guard};
use imphnen_libs::{AppState, MessageResponseDto, ResponseSuccessDto};
use super::{GachaClaimItemDto, GachaClaimRequestDto, GachaClaimService};
#[utoipa::path(
get,
path = "/v1/gacha/claims/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Claim ID")),
responses(
(status = 200, description = "Get Gacha Claim by ID", body = ResponseSuccessDto<GachaClaimItemDto>)
),
tag = "Gacha"
)]
pub async fn get_detail_gacha_claim(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::CreateGachaClaims],
)
.await
{
Ok(_) => GachaClaimService::get_gacha_claim_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/gacha/claims/create",
request_body = GachaClaimRequestDto,
responses(
(status = 201, description = "Create new gacha claim", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_claim(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaClaimRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::CreateGachaClaims],
)
.await
{
Ok(_) => GachaClaimService::create_gacha_claim(&state, payload).await,
Err(response) => response,
}
}
@@ -1,3 +1,5 @@
use crate::{GachaItemDto, GachaItemSchema};
use imphnen_iam::{UsersDetailItemDto, UsersDetailQueryDto};
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
@@ -7,27 +9,39 @@ use validator::Validate;
pub struct GachaClaimRequestDto {
#[validate(length(min = 1, message = "User ID must not be empty"))]
pub user_id: String,
#[validate(length(min = 1, message = "Item ID must not be empty"))]
pub item_id: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct GachaClaimDto {
pub struct GachaClaimItemDto {
pub id: String,
pub user: String,
pub item: String,
pub user: UsersDetailItemDto,
pub item: GachaItemDto,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimDtoRaw {
pub struct GachaClaimQueryDto {
pub id: Thing,
pub user: Thing,
pub item: Thing,
pub user: UsersDetailQueryDto,
pub item: GachaItemSchema,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl GachaClaimItemDto {
pub fn from(dto: &GachaClaimQueryDto) -> Self {
Self {
id: dto.id.id.to_raw(),
user: UsersDetailItemDto::from(&dto.user),
item: GachaItemDto::from(&dto.item),
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
@@ -1,6 +1,7 @@
use super::GachaClaimSchema;
use super::{GachaClaimQueryDto, GachaClaimSchema};
use crate::{AppState, ResourceEnum};
use anyhow::{Result, bail};
use imphnen_iam::DetailQueryBuilder;
pub struct GachaClaimRepository<'a> {
state: &'a AppState,
@@ -14,11 +15,16 @@ impl<'a> GachaClaimRepository<'a> {
pub async fn query_gacha_claim_by_id(
&self,
id: String,
) -> Result<GachaClaimSchema> {
) -> Result<GachaClaimQueryDto> {
let db = &self.state.surrealdb_ws;
let result: Option<GachaClaimSchema> = db
.select((ResourceEnum::GachaClaims.to_string(), id.clone()))
.await?;
let builder = DetailQueryBuilder::new(ResourceEnum::GachaClaims.to_string())
.with_id(id.clone())
.with_select_fields(vec!["*"])
.with_fetch("item")
.with_fetch("user");
let sql = builder.build();
let result: Option<GachaClaimQueryDto> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
match result {
Some(claim) if !claim.is_deleted => Ok(claim),
_ => bail!("Gacha Claim not found"),
@@ -2,6 +2,8 @@ use crate::{ResourceEnum, make_thing};
use serde::{Deserialize, Serialize};
use surrealdb::{Uuid, sql::Thing};
use super::GachaClaimRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaClaimSchema {
pub id: Thing,
@@ -33,3 +35,19 @@ impl Default for GachaClaimSchema {
}
}
}
impl GachaClaimSchema {
pub fn from(dto: GachaClaimRequestDto) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaClaims.to_string(),
&Uuid::new_v4().to_string(),
),
user: make_thing(&ResourceEnum::Users.to_string(), &dto.user_id),
item: make_thing(&ResourceEnum::GachaItems.to_string(), &dto.item_id),
is_deleted: false,
created_at: None,
updated_at: None,
}
}
}
@@ -0,0 +1,36 @@
use crate::{
AppState, GachaClaimItemDto, GachaClaimRepository, GachaClaimRequestDto,
GachaClaimSchema, ResponseSuccessDto, common_response, success_response,
validate_request,
};
use axum::http::StatusCode;
use axum::response::Response;
pub struct GachaClaimService;
impl GachaClaimService {
pub async fn get_gacha_claim_by_id(state: &AppState, id: String) -> Response {
let repo = GachaClaimRepository::new(state);
match repo.query_gacha_claim_by_id(id).await {
Ok(claim) => success_response(ResponseSuccessDto {
data: GachaClaimItemDto::from(&claim),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_claim(
state: &AppState,
payload: GachaClaimRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaClaimRepository::new(state);
let schema = GachaClaimSchema::from(payload);
match repo.query_create_gacha_claim(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
}
+15
View File
@@ -1,7 +1,22 @@
use axum::{
Router,
routing::{get, post},
};
pub mod gacha_claim_controller;
pub mod gacha_claim_dto;
pub mod gacha_claim_repository;
pub mod gacha_claim_schema;
pub mod gacha_claim_service;
pub use gacha_claim_controller::*;
pub use gacha_claim_dto::*;
pub use gacha_claim_repository::*;
pub use gacha_claim_schema::*;
pub use gacha_claim_service::*;
pub fn gacha_claim_router() -> Router {
Router::new()
.route("/create", post(post_create_gacha_claim))
.route("/detail/{id}", get(get_detail_gacha_claim))
}
@@ -0,0 +1,166 @@
use crate::{
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
ResponseSuccessDto,
gacha_item_dto::{GachaItemDto, GachaItemRequestDto},
gacha_item_service::GachaItemService,
};
use axum::{
Extension, Json,
extract::{Path, Query},
http::HeaderMap,
response::IntoResponse,
};
use imphnen_iam::{PermissionsEnum, permissions_guard};
#[utoipa::path(
get,
path = "/v1/gacha/items",
security(
("Bearer" = [])
),
params(
("page" = Option<i64>, Query, description = "Page number"),
("per_page" = Option<i64>, Query, description = "Items per page"),
("search" = Option<String>, Query, description = "Search keyword"),
("sort_by" = Option<String>, Query, description = "Sort by field"),
("order" = Option<String>, Query, description = "Order ASC or DESC"),
("filter" = Option<String>, Query, description = "Filter value"),
("filter_by" = Option<String>, Query, description = "Field to filter by"),
),
responses(
(status = 200, description = "Get gacha item list", body = ResponseListSuccessDto<Vec<GachaItemDto>>)
),
tag = "Gacha"
)]
pub async fn get_gacha_item_list(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Query(meta): Query<MetaRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::ReadListGachaItems],
)
.await
{
Ok(_) => GachaItemService::get_gacha_item_list(&state, meta).await,
Err(response) => response,
}
}
#[utoipa::path(
get,
path = "/v1/gacha/items/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Gacha Item ID")),
responses(
(status = 200, description = "Get gacha item by ID", body = ResponseSuccessDto<GachaItemDto>)
),
tag = "Gacha"
)]
pub async fn get_gacha_item_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::ReadDetailGachaItems],
)
.await
{
Ok(_) => GachaItemService::get_gacha_item_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
path = "/v1/gacha/items/create",
security(
("Bearer" = [])
),
request_body = GachaItemRequestDto,
responses(
(status = 201, description = "Create gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn post_create_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<GachaItemRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::CreateGachaItems],
)
.await
{
Ok(_) => GachaItemService::create_gacha_item(&state, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
put,
path = "/v1/gacha/items/update/{id}",
security(
("Bearer" = [])
),
request_body = GachaItemRequestDto,
responses(
(status = 200, description = "Update gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn put_update_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
Json(payload): Json<GachaItemRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::UpdateGachaItems],
)
.await
{
Ok(_) => GachaItemService::update_gacha_item(&state, payload, id).await,
Err(response) => response,
}
}
#[utoipa::path(
delete,
path = "/v1/gacha/items/delete/{id}",
security(
("Bearer" = [])
),
responses(
(status = 200, description = "Delete gacha item", body = MessageResponseDto)
),
tag = "Gacha"
)]
pub async fn delete_gacha_item(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
&headers,
state.clone(),
vec![PermissionsEnum::DeleteGachaItems],
)
.await
{
Ok(_) => GachaItemService::delete_gacha_item(&state, id).await,
Err(response) => response,
}
}
@@ -1,5 +1,5 @@
use super::GachaItemSchema;
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
use validator::Validate;
@@ -20,11 +20,14 @@ pub struct GachaItemDto {
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaItemDtoRaw {
pub id: Thing,
pub name: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
impl GachaItemDto {
pub fn from(dto: &GachaItemSchema) -> Self {
Self {
id: dto.id.id.to_raw(),
name: dto.name.clone(),
is_deleted: dto.is_deleted,
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
}
}
}
@@ -1,7 +1,7 @@
use super::GachaItemSchema;
use crate::{
AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto, get_id,
make_thing, query_list_with_meta,
AppState, GachaItemDto, MetaRequestDto, ResourceEnum, ResponseListSuccessDto,
get_id, make_thing, query_list_with_meta,
};
use anyhow::{Result, bail};
@@ -17,22 +17,28 @@ impl<'a> GachaItemRepository<'a> {
pub async fn query_gacha_item_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<GachaItemSchema>>> {
let mut conditions = vec!["is_deleted = false".into()];
if meta.search.is_some() {
conditions.push("string::contains(name, $search)".into());
}
query_list_with_meta(
&self.state.surrealdb_ws,
&ResourceEnum::GachaItems.to_string(),
&meta,
conditions,
None,
"name",
None,
None,
)
.await
) -> Result<ResponseListSuccessDto<Vec<GachaItemDto>>> {
let raw_result: ResponseListSuccessDto<Vec<GachaItemSchema>> =
query_list_with_meta(
&self.state.surrealdb_ws,
&ResourceEnum::GachaItems.to_string(),
&meta,
vec!["is_deleted = false".into()],
None,
"name",
Some(vec!["*"]),
None,
)
.await?;
let transformed_data = raw_result
.data
.into_iter()
.map(|gacha_item| GachaItemDto::from(&gacha_item))
.collect();
Ok(ResponseListSuccessDto {
data: transformed_data,
meta: raw_result.meta,
})
}
pub async fn query_gacha_item_by_id(&self, id: String) -> Result<GachaItemSchema> {
@@ -1,7 +1,10 @@
use crate::{ResourceEnum, make_thing};
use imphnen_iam::get_iso_date;
use serde::{Deserialize, Serialize};
use surrealdb::{Uuid, sql::Thing};
use super::GachaItemRequestDto;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GachaItemSchema {
pub id: Thing,
@@ -22,8 +25,24 @@ impl Default for GachaItemSchema {
name: String::new(),
image_url: String::new(),
is_deleted: false,
created_at: None,
updated_at: None,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
impl GachaItemSchema {
pub fn from(dto: GachaItemRequestDto) -> Self {
Self {
id: make_thing(
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
name: dto.name,
image_url: dto.image_url,
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
@@ -0,0 +1,95 @@
use crate::{
AppState, GachaItemDto, GachaItemRepository, GachaItemRequestDto, GachaItemSchema,
MetaRequestDto, ResourceEnum, ResponseListSuccessDto, ResponseSuccessDto,
common_response, make_thing, success_list_response, success_response,
validate_request,
};
use axum::http::StatusCode;
use axum::response::Response;
pub struct GachaItemService;
impl GachaItemService {
pub async fn get_gacha_item_list(
state: &AppState,
meta: MetaRequestDto,
) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_gacha_item_list(meta).await {
Ok(data) => {
let response = ResponseListSuccessDto {
data: data.data,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn get_gacha_item_by_id(state: &AppState, id: String) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_gacha_item_by_id(id).await {
Ok(item) => success_response(ResponseSuccessDto {
data: GachaItemDto::from(&item),
}),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_gacha_item(
state: &AppState,
payload: GachaItemRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaItemRepository::new(state);
let schema = GachaItemSchema::from(payload);
match repo.query_create_gacha_item(schema).await {
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn update_gacha_item(
state: &AppState,
payload: GachaItemRequestDto,
id: String,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = GachaItemRepository::new(state);
let schema = GachaItemSchema {
id: make_thing(&ResourceEnum::GachaItems.to_string(), &id),
name: payload.name,
image_url: payload.image_url,
..Default::default()
};
match repo.query_update_gacha_item(schema).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Gacha Item not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
pub async fn delete_gacha_item(state: &AppState, id: String) -> Response {
let repo = GachaItemRepository::new(state);
match repo.query_delete_gacha_item(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Gacha Item not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
}
+18
View File
@@ -1,7 +1,25 @@
use axum::{
Router,
routing::{delete, get, post, put},
};
pub mod gacha_item_controller;
pub mod gacha_item_dto;
pub mod gacha_item_repository;
pub mod gacha_item_schema;
pub mod gacha_item_service;
pub use gacha_item_controller::*;
pub use gacha_item_dto::*;
pub use gacha_item_repository::*;
pub use gacha_item_schema::*;
pub use gacha_item_service::*;
pub fn gacha_item_router() -> Router {
Router::new()
.route("/", get(get_gacha_item_list))
.route("/create", post(post_create_gacha_item))
.route("/detail/{id}", get(get_gacha_item_by_id))
.route("/update/{id}", put(put_update_gacha_item))
.route("/delete/{id}", delete(delete_gacha_item))
}
@@ -0,0 +1,94 @@
use crate::{
AppState, MessageResponseDto, ResponseSuccessDto,
gacha_roll_dto::{GachaRollItemDto, GachaRollRequestDto},
gacha_roll_service::GachaRollService,
};
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(&state).await,
Err(response) => response,
}
}
@@ -1,3 +1,4 @@
use crate::{GachaItemDto, GachaItemSchema};
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
@@ -7,18 +8,16 @@ use validator::Validate;
pub struct GachaRollRequestDto {
#[validate(length(min = 1, message = "Item ID must not be empty"))]
pub item_id: String,
#[validate(range(min = 1, message = "Weight must be greater than zero"))]
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 GachaRollDto {
pub struct GachaRollItemDto {
pub id: String,
pub item: String,
pub item: GachaItemDto,
pub weight: String,
pub quantity: i32,
pub is_deleted: bool,
@@ -26,11 +25,25 @@ pub struct GachaRollDto {
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),
weight: dto.weight.to_string(),
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 GachaRollDtoRaw {
pub struct GachaRollQueryDto {
pub id: Thing,
pub item: Thing,
pub weight: String,
pub item: GachaItemSchema,
pub weight: f32,
pub quantity: i32,
pub is_deleted: bool,
pub created_at: Option<String>,
@@ -1,6 +1,10 @@
use super::GachaRollQueryDto;
use super::GachaRollSchema;
use crate::{AppState, ResourceEnum};
use crate::{AppState, DetailQueryBuilder, ResourceEnum};
use anyhow::{Result, bail};
use rand::prelude::*;
use rand::rng;
use rand_distr::weighted::WeightedIndex;
pub struct GachaRollRepository<'a> {
state: &'a AppState,
@@ -11,11 +15,18 @@ impl<'a> GachaRollRepository<'a> {
Self { state }
}
pub async fn query_gacha_roll_by_id(&self, id: String) -> Result<GachaRollSchema> {
pub async fn query_gacha_roll_by_id(
&self,
id: String,
) -> Result<GachaRollQueryDto> {
let db = &self.state.surrealdb_ws;
let result: Option<GachaRollSchema> = db
.select((ResourceEnum::GachaRolls.to_string(), id.clone()))
.await?;
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"),
@@ -36,4 +47,34 @@ impl<'a> GachaRollRepository<'a> {
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 sql = DetailQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
.with_where("is_deleted")
.where_value("false")
.with_select_fields(vec!["*"])
.with_fetch("item")
.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())
}
}
@@ -1,7 +1,10 @@
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,
@@ -24,11 +27,28 @@ impl Default for GachaRollSchema {
&ResourceEnum::GachaItems.to_string(),
&Uuid::new_v4().to_string(),
),
weight: 0.2,
quantity: 2,
weight: 0.0,
quantity: 0,
is_deleted: false,
created_at: None,
updated_at: None,
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,
is_deleted: false,
created_at: Some(get_iso_date()),
updated_at: Some(get_iso_date()),
}
}
}
@@ -0,0 +1,49 @@
use crate::{
AppState, GachaRollItemDto, GachaRollRepository, GachaRollRequestDto,
GachaRollSchema, ResponseSuccessDto, common_response, success_response,
validate_request,
};
use axum::http::StatusCode;
use axum::response::Response;
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(state: &AppState) -> Response {
let repo = GachaRollRepository::new(state);
match repo.query_all_active_rolls().await {
Ok(rolls) => match GachaRollRepository::roll_once(&rolls) {
Some(roll) => success_response(ResponseSuccessDto {
data: GachaRollItemDto::from(&roll),
}),
None => common_response(StatusCode::NOT_FOUND, "No rollable item available"),
},
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
}
+15
View File
@@ -1,7 +1,22 @@
pub mod gacha_roll_controller;
pub mod gacha_roll_dto;
pub mod gacha_roll_repository;
pub mod gacha_roll_schema;
pub mod gacha_roll_service;
use axum::{
Router,
routing::{get, post},
};
pub use gacha_roll_controller::*;
pub use gacha_roll_dto::*;
pub use gacha_roll_repository::*;
pub use gacha_roll_schema::*;
pub use gacha_roll_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))
}
+9
View File
@@ -1,3 +1,5 @@
use axum::Router;
pub mod gacha_claim;
pub mod gacha_item;
pub mod gacha_roll;
@@ -5,3 +7,10 @@ pub mod gacha_roll;
pub use gacha_claim::*;
pub use gacha_item::*;
pub use gacha_roll::*;
pub fn gacha_router() -> Router {
Router::new()
.nest("/gacha/claims", gacha_claim_router())
.nest("/gacha/items", gacha_item_router())
.nest("/gacha/rolls", gacha_roll_router())
}
+1
View File
@@ -7,6 +7,7 @@ edition = "2024"
imphnen-iam = { version = "0.1.0", path = "../imphnen-iam" }
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
imphnen-gacha = { version = "0.1.0", path = "../imphnen-gacha" }
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
imphnen-middleware = { version = "0.1.0", path = "../imphnen-middleware" }
axum.workspace = true
+22 -1
View File
@@ -5,6 +5,7 @@ use utoipa::{
openapi::security::{Http, HttpAuthScheme, SecurityScheme},
Modify, OpenApi,
};
use imphnen_gacha::{gacha_claim, gacha_item, gacha_roll, GachaClaimItemDto, GachaClaimRequestDto, GachaItemDto, GachaItemRequestDto, GachaRollItemDto, GachaRollRequestDto};
#[derive(OpenApi)]
#[openapi(
@@ -33,7 +34,17 @@ use utoipa::{
permissions::permissions_controller::get_permission_by_id,
permissions::permissions_controller::post_create_permission,
permissions::permissions_controller::put_update_permission,
permissions::permissions_controller::delete_permission
permissions::permissions_controller::delete_permission,
gacha_claim::get_detail_gacha_claim,
gacha_claim::post_create_gacha_claim,
gacha_item::get_gacha_item_list,
gacha_item::get_gacha_item_by_id,
gacha_item::post_create_gacha_item,
gacha_item::put_update_gacha_item,
gacha_item::delete_gacha_item,
gacha_roll::get_detail_gacha_roll,
gacha_roll::post_create_gacha_roll,
gacha_roll::post_execute_gacha_roll,
),
components(
schemas(
@@ -56,6 +67,16 @@ use utoipa::{
UsersListItemDto,
UsersUpdateRequestDto,
UsersCreateRequestDto,
GachaClaimItemDto,
GachaClaimRequestDto,
GachaItemDto,
GachaItemRequestDto,
GachaRollItemDto,
GachaRollRequestDto,
ResponseListSuccessDto<Vec<GachaItemDto>>,
ResponseSuccessDto<GachaRollItemDto>,
ResponseSuccessDto<GachaItemDto>,
ResponseSuccessDto<GachaClaimItemDto>,
ResponseSuccessDto<AuthLoginResponsetDto>,
ResponseListSuccessDto<Vec<RolesListItemDto>>,
ResponseSuccessDto<RolesDetailItemDto>,
+7 -2
View File
@@ -2,6 +2,7 @@ use axum::{
Extension, Router, middleware::from_fn, response::Redirect, routing::get,
};
use imphnen_entities::{AppState, SurrealMemClient, SurrealWsClient};
use imphnen_gacha::gacha_router;
use imphnen_iam::{iam_protected_routes, iam_public_routes};
use imphnen_middleware::{auth_middleware, cors_middleware};
use utoipa_swagger_ui::SwaggerUi;
@@ -19,12 +20,16 @@ pub async fn gateway_service(
};
let public_routes = iam_public_routes();
let protected_routes = iam_protected_routes().layer(from_fn(auth_middleware));
let protected_routes = Router::new()
.merge(iam_protected_routes())
.merge(gacha_router())
.layer(from_fn(auth_middleware));
Router::new()
.route("/", get(Redirect::to("/docs")))
.nest("/v1", public_routes.merge(protected_routes))
.merge(SwaggerUi::new("/docs").url("/openapi.json", docs_router()))
.layer(cors_middleware())
.layer(Extension(state.clone()))
.layer(Extension(state))
}
@@ -18,6 +18,16 @@ pub enum PermissionsEnum {
CreatePermissions,
DeletePermissions,
UpdatePermissions,
CreateGachaClaims,
ReadDetailGachaClaims,
ReadListGachaItems,
ReadDetailGachaItems,
CreateGachaItems,
DeleteGachaItems,
UpdateGachaItems,
ReadDetailGachaRolls,
CreateGachaRolls,
ExecuteGachaRolls,
}
impl fmt::Display for PermissionsEnum {
@@ -39,6 +49,16 @@ impl fmt::Display for PermissionsEnum {
PermissionsEnum::CreatePermissions => "Create Permissions",
PermissionsEnum::DeletePermissions => "Delete Permissions",
PermissionsEnum::UpdatePermissions => "Update Permissions",
PermissionsEnum::CreateGachaClaims => "Create Gacha Claims",
PermissionsEnum::ReadDetailGachaClaims => "Read Detail Gacha Claims",
PermissionsEnum::ReadListGachaItems => "Read List Gacha Items",
PermissionsEnum::ReadDetailGachaItems => "Read Detail Gacha Items",
PermissionsEnum::CreateGachaItems => "Create Gacha Items",
PermissionsEnum::DeleteGachaItems => "Delete Gacha Items",
PermissionsEnum::UpdateGachaItems => "Update Gacha Items",
PermissionsEnum::ReadDetailGachaRolls => "Read Detail Gacha Rolls",
PermissionsEnum::CreateGachaRolls => "Create Gacha Rolls",
PermissionsEnum::ExecuteGachaRolls => "Execute Gacha Rolls",
};
write!(f, "{}", permission_str)
}
@@ -4,7 +4,7 @@ use crate::{
make_thing, query_list_with_meta,
};
use anyhow::{Result, bail};
use imphnen_utils::extract_id;
use imphnen_utils::{DetailQueryBuilder, extract_id};
pub struct PermissionsRepository<'a> {
state: &'a AppState,
@@ -19,23 +19,15 @@ impl<'a> PermissionsRepository<'a> {
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<PermissionsItemDto>>> {
let mut conditions = vec!["is_deleted = false".into()];
if meta.search.is_some() {
conditions.push("string::contains(name, $search)".into());
}
if meta.filter_by.is_some() && meta.filter.is_some() {
let filter_by = meta.filter_by.as_ref().unwrap();
conditions.push(format!("{} = $filter", filter_by));
}
let raw_result: ResponseListSuccessDto<Vec<PermissionsSchema>> =
query_list_with_meta(
&self.state.surrealdb_ws,
&ResourceEnum::Permissions.to_string(),
&meta,
conditions,
vec!["is_deleted = false".into()],
None,
"name",
None,
Some(vec!["*"]),
None,
)
.await?;
@@ -83,16 +75,16 @@ impl<'a> PermissionsRepository<'a> {
name: String,
) -> Result<PermissionsSchema> {
let db = &self.state.surrealdb_ws;
let sql = format!(
"SELECT * FROM {} WHERE name = $name AND is_deleted = false",
ResourceEnum::Permissions.to_string()
);
let result: Vec<PermissionsSchema> =
db.query(sql).bind(("name", name.clone())).await?.take(0)?;
if let Some(permission) = result.into_iter().next() {
Ok(permission.into())
} else {
bail!("Permission not found")
let builder = DetailQueryBuilder::new(ResourceEnum::Permissions.to_string())
.with_where("name")
.where_value(name.clone())
.with_select_fields(vec!["*"]);
let sql = builder.build();
let result: Option<PermissionsSchema> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
match result {
Some(permission) => Ok(permission),
None => bail!("Permission not found"),
}
}
+1
View File
@@ -5,6 +5,7 @@ edition = "2024"
[dependencies]
imphnen-entities = { path = "../imphnen-entities" }
log.workspace = true
axum.workspace = true
tokio.workspace = true
serde.workspace = true
+16 -7
View File
@@ -1,7 +1,7 @@
use crate::{
surrealdb_init_mem, surrealdb_init_ws, Env, SurrealMemClient, SurrealWsClient,
};
use axum::{serve, Router};
use crate::{Env, surrealdb_init_mem, surrealdb_init_ws};
use axum::{Router, serve};
use imphnen_entities::{SurrealMemClient, SurrealWsClient};
use log::{debug, error, info};
use std::{future::Future, net::SocketAddr};
use tokio::net::TcpListener;
@@ -11,15 +11,24 @@ where
Fut: Future<Output = Router>,
{
let env = Env::new();
info!("Environment loaded with port: {}", env.port);
let surrealdb_ws = surrealdb_init_ws().await.expect("Failed surrealdb ws");
info!("SurrealDB WS client initialized");
let surrealdb_mem = surrealdb_init_mem().await.expect("Failed surrealdb mem");
info!("SurrealDB MEM client initialized");
let router = router_fn(surrealdb_ws, surrealdb_mem).await;
debug!("Router created successfully");
let port = env.port;
let addr = SocketAddr::from(([0, 0, 0, 0], port));
let listener = TcpListener::bind(&addr).await.unwrap();
println!("Listening on http://{}", addr);
info!("Listening on http://{}", addr);
match serve(listener, router).await {
Ok(_) => println!("Server stopped gracefully."),
Err(err) => println!("Server encountered an error: {}", err),
Ok(_) => info!("Server stopped gracefully."),
Err(err) => error!("Server encountered an error: {}", err),
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use surrealdb::sql::Thing;
pub fn get_id(thing: &Thing) -> Result<(&str, &str)> {