Files
imphnen-backend-service/imphnen-gacha/src/v1/gacha_rolls/gacha_rolls_repository.rs
T

80 lines
2.2 KiB
Rust
Raw Normal View History

2025-05-20 10:45:01 +07:00
use super::GachaRollQueryDto;
2025-04-07 00:50:57 +07:00
use super::GachaRollSchema;
2025-05-20 10:45:01 +07:00
use crate::{AppState, DetailQueryBuilder, ResourceEnum};
2025-04-07 00:50:57 +07:00
use anyhow::{Result, bail};
2025-05-21 19:37:30 +07:00
use imphnen_iam::ListQueryBuilder;
2025-05-20 10:45:01 +07:00
use rand::prelude::*;
use rand::rng;
use rand_distr::weighted::WeightedIndex;
2025-04-07 00:50:57 +07:00
pub struct GachaRollRepository<'a> {
state: &'a AppState,
}
impl<'a> GachaRollRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
2025-05-20 10:45:01 +07:00
pub async fn query_gacha_roll_by_id(
&self,
id: String,
) -> Result<GachaRollQueryDto> {
2025-04-07 00:50:57 +07:00
let db = &self.state.surrealdb_ws;
2025-05-20 10:45:01 +07:00
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)?;
2025-04-07 00:50:57 +07:00
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"),
}
}
2025-05-20 10:45:01 +07:00
pub async fn query_all_active_rolls(&self) -> Result<Vec<GachaRollQueryDto>> {
let db = &self.state.surrealdb_ws;
2025-05-21 19:37:30 +07:00
let builder = ListQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
2025-05-20 10:45:01 +07:00
.with_select_fields(vec!["*"])
2025-05-21 19:37:30 +07:00
.with_fetch(Some(vec!["item"]));
let sql = builder.build();
2025-05-20 10:45:01 +07:00
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())
}
2025-04-07 00:50:57 +07:00
}