From 90bb4db806043e9e25bc5812f1066e7e762ae629 Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Mon, 7 Apr 2025 21:42:35 +0200 Subject: [PATCH] Can change default account --- .../src/controllers/accounts_controller.rs | 7 +++++++ moneymgr_backend/src/main.rs | 5 ++++- .../src/services/accounts_service.rs | 19 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/moneymgr_backend/src/controllers/accounts_controller.rs b/moneymgr_backend/src/controllers/accounts_controller.rs index b23db52..96c5e14 100644 --- a/moneymgr_backend/src/controllers/accounts_controller.rs +++ b/moneymgr_backend/src/controllers/accounts_controller.rs @@ -37,6 +37,13 @@ pub async fn update(account: AccountInPath, req: web::Json) Ok(HttpResponse::Accepted().finish()) } +/// Set an account as the default one +pub async fn set_default(account: AccountInPath) -> HttpResult { + accounts_service::set_default(account.as_ref().user_id(), account.as_ref().id()).await?; + + Ok(HttpResponse::Accepted().finish()) +} + /// Delete an account pub async fn delete(account: AccountInPath) -> HttpResult { accounts_service::delete(account.as_ref().id()).await?; diff --git a/moneymgr_backend/src/main.rs b/moneymgr_backend/src/main.rs index e2af597..e6ff9ea 100644 --- a/moneymgr_backend/src/main.rs +++ b/moneymgr_backend/src/main.rs @@ -111,11 +111,14 @@ async fn main() -> std::io::Result<()> { "/api/account/{account_id}", web::put().to(accounts_controller::update), ) + .route( + "/api/account/{account_id}/default", + web::put().to(accounts_controller::set_default), + ) .route( "/api/account/{account_id}", web::delete().to(accounts_controller::delete), ) - // TODO : set as default // Static assets .route("/", web::get().to(static_controller::root_index)) .route( diff --git a/moneymgr_backend/src/services/accounts_service.rs b/moneymgr_backend/src/services/accounts_service.rs index e53e6cf..2a94599 100644 --- a/moneymgr_backend/src/services/accounts_service.rs +++ b/moneymgr_backend/src/services/accounts_service.rs @@ -68,6 +68,25 @@ pub async fn get_list_user(id: UserID) -> anyhow::Result> { .get_results(&mut db()?)?) } +/// Change the default account of a user +pub async fn set_default(user_id: UserID, account_id: AccountID) -> anyhow::Result<()> { + diesel::update(accounts::dsl::accounts.filter(accounts::dsl::user_id.eq(user_id.0))) + .set((accounts::dsl::default_account.eq(false),)) + .execute(&mut db()?)?; + + diesel::update( + accounts::dsl::accounts.filter( + accounts::dsl::user_id + .eq(user_id.0) + .and(accounts::dsl::id.eq(account_id.0)), + ), + ) + .set((accounts::dsl::default_account.eq(true),)) + .execute(&mut db()?)?; + + Ok(()) +} + /// Delete an account pub async fn delete(id: AccountID) -> anyhow::Result<()> { diesel::delete(accounts::dsl::accounts.filter(accounts::dsl::id.eq(id.0)))