Get accounts and balances

This commit is contained in:
2025-04-21 12:08:12 +02:00
parent f5b0ae49ca
commit 6ee250d872
5 changed files with 72 additions and 5 deletions

View File

@ -7,8 +7,9 @@ use crate::models::users::UserID;
use crate::schema::movements;
use crate::services::{accounts_service, files_service};
use crate::utils::time_utils::time;
use diesel::RunQueryDsl;
use diesel::prelude::*;
use diesel::{RunQueryDsl, sql_query};
use std::collections::HashMap;
#[derive(serde::Deserialize)]
pub struct UpdateMovementQuery {
@ -136,6 +137,31 @@ pub async fn get_list_account(account_id: AccountID) -> anyhow::Result<Vec<Movem
.get_results(&mut db()?)?)
}
table! {
accounts_balances (account_id) {
account_id -> Int4,
balance -> Float4,
}
}
#[derive(QueryableByName)]
#[diesel(table_name = accounts_balances)]
struct AccountBalance {
account_id: i32,
balance: f32,
}
/// Get the balances of all the accounts of the user
pub async fn get_balances(user_id: UserID) -> anyhow::Result<HashMap<AccountID, f32>> {
let result = sql_query(format!("select a.id as account_id, sum(m.amount) as balance from accounts a right join movements m on a.id = m.account_id where a.user_id = {} group by a.id", user_id.0))
.get_results::<AccountBalance>(&mut db()?)?;
Ok(result
.into_iter()
.map(|r| (AccountID(r.account_id), r.balance))
.collect())
}
/// Delete a movement
pub async fn delete(id: MovementID) -> anyhow::Result<()> {
diesel::delete(movements::dsl::movements.filter(movements::dsl::id.eq(id.0)))