From 11ba5c3d7e039c3c092e45fdd55c0c6a9e144842 Mon Sep 17 00:00:00 2001 From: Curly Bryce Date: Wed, 3 Jul 2024 19:50:40 -0600 Subject: transfers --- src/db.rs | 44 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) (limited to 'src/db.rs') diff --git a/src/db.rs b/src/db.rs index a6ca7b0..85e259b 100644 --- a/src/db.rs +++ b/src/db.rs @@ -17,7 +17,7 @@ impl Config { } } -#[derive(Debug, Serialize, Deserialize, Clone, Copy)] +#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)] pub enum Color { White, Red, @@ -186,7 +186,7 @@ impl DB { } } - Err("Not Found".into()) + Err("User Not Found".into()) } pub async fn get_user_authenticated(&self, id: UID, session: &String) -> Result<&User, String> { @@ -208,7 +208,7 @@ impl DB { } } - Err("Not Found".into()) + Err("User Not Found".into()) } pub async fn get_user_by_name(&self, name: &str) -> Result, String> { @@ -220,7 +220,7 @@ impl DB { } if vec.len() == 0 { - Err("Not Found".into()) + Err("User(s) Not Found".into()) } else { return Ok(vec) } @@ -303,4 +303,40 @@ impl DB { let _ = self.save().await; r } + + pub async fn transfer(&mut self, from: UID, to: UID, session: &String, color: Color, amount: usize) -> Result<(), String> { + let mut subtracted = false; + + let from = self.get_mut_user(from).await?; + // If authenticated + if from.authenticate(session) { + for v in from.tokovec.iter_mut() { + // Get the token of the right color + if v.color == color { + // If amount is greater or equal to amount being sent + // and if the amount does not overflow past 0 + if v.amount >= amount && v.amount.checked_sub(amount) != None { + // Remove from account + v.amount -= amount; + subtracted = true; + } + } + } + } + + let to = self.get_mut_user(to).await?; + if subtracted { + for v in to.tokovec.iter_mut() { + if v.color == color { + v.amount += amount + } + } + + let _ = self.save().await; + Ok(()) + } else { + Err("Could not complete transaction".into()) + } + + } } -- cgit v1.2.3