use rusqlite::Connection; use crate::db::accounts::{Account, AccountType, get_checking_accounts_for_sec_id, list_user_accounts}; use crate::db::external_id::{AccountId, Id, SecurityId, UserId}; use crate::util::{CustomResult, Error}; use serde::Deserialize; use serde::Serialize; use crate::db::{account_history, accounts}; use crate::db::securities::Security; use crate::services::_securities::SecurityDTO; pub struct AccountService<'a> { conn: &'a Connection, } #[derive(Deserialize, Serialize, Debug)] pub struct AccountNumbers { checking: i64, security_emitter: i64, } #[derive(Deserialize, Serialize, Debug)] pub struct AccountDTO { pub id: String, pub amount: i64, pub account_type: String, pub last_update: i64, pub security: SecurityDTO, pub label: String, } #[derive(Serialize, Debug)] pub struct AccountHistoryDTO { amounts: Vec, timestamps: Vec, } impl AccountDTO { fn from_entity(account: & Account) -> AccountDTO { AccountDTO{ id: account.id().to_string(), amount: account.amount(), account_type: account.account_type().to_string(), last_update: account.timestamp(), security: SecurityDTO::from_entity(account.security()), label: account.label().to_string(), } } } impl AccountService<'_> { pub fn new(conn: & Connection) -> AccountService{ AccountService{conn} } pub fn get_user_accounts(& self, user_id: &UserId) -> CustomResult>{ let ret = list_user_accounts(&self.conn, user_id)?; Ok(ret.iter().map(AccountDTO::from_entity).collect()) } pub fn get_user_emitter_accounts(& self, user_id: &UserId) -> CustomResult> { let accounts = self.get_user_accounts(user_id)?; let ret = accounts.into_iter() .filter(|acc| acc.account_type == AccountType::SecurityEmitter.to_string()) .collect(); Ok(ret) } pub fn get_checking_accounts_for_security(& self, sec_id: & SecurityId) -> CustomResult>{ let ret = get_checking_accounts_for_sec_id(self.conn, sec_id)?; Ok(ret.iter().map(AccountDTO::from_entity).collect()) } pub fn get_account_by_id(&self, account_id: &AccountId, user_id: &UserId) -> CustomResult { let ret = &accounts::get_account_by_id(self.conn, account_id)?; Ok(AccountDTO::from_entity(ret)) } pub fn get_account_history_by_id(&self, account_id: &AccountId, user_id: &UserId) -> CustomResult { let ac = account_history::get_account_history(self.conn, account_id)?; // ret.account() let ret = AccountHistoryDTO{ amounts: ac.amount().clone(), timestamps: ac.timestamps().clone(), }; Ok(ret) } pub fn get_number_of_accounts(&self, sec_id: &SecurityId) -> CustomResult{ let checking = accounts::get_number_of_accounts(self.conn, sec_id, AccountType::Checking)?; let security_emitter = accounts::get_number_of_accounts(self.conn, sec_id, AccountType::SecurityEmitter)?; Ok(AccountNumbers{checking, security_emitter}) } }