feat: add gacha credits
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
use crate::{
|
||||
AppState, GachaItemDto, GachaItemRequestDto, GachaItemService, MessageResponseDto,
|
||||
MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use super::GachaItemSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct GachaItemRequestDto {
|
||||
#[validate(length(min = 1, message = "Item name must not be empty"))]
|
||||
pub name: String,
|
||||
#[validate(length(min = 1, message = "Image URL must not be empty"))]
|
||||
pub image_url: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GachaItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl GachaItemDto {
|
||||
pub fn from(dto: GachaItemSchema) -> Self {
|
||||
Self {
|
||||
id: dto.id.id.to_raw(),
|
||||
name: dto.name.clone(),
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
use super::GachaItemSchema;
|
||||
use crate::{
|
||||
AppState, GachaItemDto, MetaRequestDto, ResourceEnum, ResponseListSuccessDto,
|
||||
get_id, make_thing,
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_iam::QueryListBuilder;
|
||||
|
||||
pub struct GachaItemRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> GachaItemRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_gacha_item_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<GachaItemDto>>> {
|
||||
let raw_result: ResponseListSuccessDto<Vec<GachaItemSchema>> =
|
||||
QueryListBuilder::new(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::GachaItems.to_string(),
|
||||
&meta,
|
||||
)
|
||||
.with_condition("is_deleted = false")
|
||||
.search_field("name")
|
||||
.select_fields(vec!["*"])
|
||||
.build()
|
||||
.await?;
|
||||
let data = raw_result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(GachaItemDto::from)
|
||||
.collect();
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: raw_result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_gacha_item_by_id(&self, id: String) -> Result<GachaItemSchema> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let result: Option<GachaItemSchema> = db
|
||||
.select((ResourceEnum::GachaItems.to_string(), id.clone()))
|
||||
.await?;
|
||||
match result {
|
||||
Some(item) if !item.is_deleted => Ok(item),
|
||||
_ => bail!("Gacha Item not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_create_gacha_item(
|
||||
&self,
|
||||
data: GachaItemSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<GachaItemSchema> = db
|
||||
.create(ResourceEnum::GachaItems.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success create Gacha Item".into()),
|
||||
None => bail!("Failed to create Gacha Item"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_update_gacha_item(
|
||||
&self,
|
||||
data: GachaItemSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(&data.id)?;
|
||||
let existing = self.query_gacha_item_by_id(data.id.id.to_raw()).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Gacha Item already deleted");
|
||||
}
|
||||
let merged = GachaItemSchema {
|
||||
created_at: existing.created_at,
|
||||
..data.clone()
|
||||
};
|
||||
let record: Option<GachaItemSchema> =
|
||||
db.update(record_key).merge(merged).await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update Gacha Item".into()),
|
||||
None => bail!("Failed to update Gacha Item"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_gacha_item(&self, id: String) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let item_id = make_thing(&ResourceEnum::GachaItems.to_string(), &id);
|
||||
let item = self.query_gacha_item_by_id(item_id.id.to_raw()).await?;
|
||||
if item.is_deleted {
|
||||
bail!("Gacha Item already deleted");
|
||||
}
|
||||
let record_key = get_id(&item.id)?;
|
||||
let record: Option<GachaItemSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete Gacha Item".into()),
|
||||
None => bail!("Failed to delete Gacha Item"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
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,
|
||||
pub name: String,
|
||||
pub image_url: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for GachaItemSchema {
|
||||
fn default() -> Self {
|
||||
GachaItemSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::GachaItems.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
name: String::new(),
|
||||
image_url: String::new(),
|
||||
is_deleted: false,
|
||||
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,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
|
||||
pub mod gacha_items_controller;
|
||||
pub mod gacha_items_dto;
|
||||
pub mod gacha_items_repository;
|
||||
pub mod gacha_items_schema;
|
||||
pub mod gacha_items_service;
|
||||
|
||||
pub use gacha_items_controller::*;
|
||||
pub use gacha_items_dto::*;
|
||||
pub use gacha_items_repository::*;
|
||||
pub use gacha_items_schema::*;
|
||||
pub use gacha_items_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))
|
||||
}
|
||||
Reference in New Issue
Block a user