From 0c088e6fc83e09deabb2dae4c865c8fb50be17e7 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Tue, 11 Mar 2025 21:04:36 -0500 Subject: [PATCH] receipts: Attach receipt to Firefly transaction If a specific transaction is selected on the Add Receipt form, the uploaded receipt image will now be attached to that transaction in Firefly. --- src/receipts.rs | 1 + src/routes/receipts.rs | 44 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/receipts.rs b/src/receipts.rs index d39e21b..102f20c 100644 --- a/src/receipts.rs +++ b/src/receipts.rs @@ -31,6 +31,7 @@ pub struct ReceiptJson { #[derive(rocket::FromForm)] pub struct ReceiptPostForm<'r> { + pub transaction: Option, pub date: String, pub vendor: String, pub amount: String, diff --git a/src/routes/receipts.rs b/src/routes/receipts.rs index 226a91c..3350013 100644 --- a/src/routes/receipts.rs +++ b/src/routes/receipts.rs @@ -1,13 +1,13 @@ use rocket::form::Form; use rocket::http::{ContentType, MediaType, Status}; use rocket::serde::json::Json; -use rocket::Route; +use rocket::{Route, State}; use rocket_db_pools::Connection as DatabaseConnection; use rocket_dyn_templates::{context, Template}; use tracing::{error, info}; use crate::receipts::*; -use crate::Database; +use crate::{Context, Database}; #[rocket::get("/")] pub async fn list_receipts( @@ -45,6 +45,7 @@ pub async fn receipt_form() -> Template { pub async fn add_receipt( form: Form>, db: DatabaseConnection, + ctx: &State, ) -> (Status, Json) { let data = match ReceiptPostData::from_form(&form).await { Ok(d) => d, @@ -56,19 +57,50 @@ pub async fn add_receipt( }, }; let mut repo = ReceiptsRepository::new(db); - match repo.add_receipt(&data).await { + let receipt = match repo.add_receipt(&data).await { Ok(r) => { info!("Created new receipt {}", r.id); - (Status::Ok, Json(AddReceiptResponse::Success(r))) + r }, Err(e) => { error!("Failed to insert new receipt record: {}", e); - ( + return ( Status::InternalServerError, Json(AddReceiptResponse::Error(e.to_string())), - ) + ); }, + }; + if let Some(id) = &form.transaction { + match ctx.firefly.get_transaction(id).await { + Ok(t) => { + if let Some(j) = t.data.attributes.transactions.first() { + if let Err(e) = ctx + .firefly + .attach_receipt( + &j.transaction_journal_id, + data.photo, + data.filename, + ) + .await + { + error!( + "Failed to attach receipt to Firefly transaction {}: {}", + id, e + ); + } + } else { + error!( + "Could not attach receipt to Firefly transaction {}: no splits", + id + ); + } + }, + Err(e) => { + error!("Could not load Firefly transaction {}: {}", id, e); + }, + } } + (Status::Ok, Json(AddReceiptResponse::Success(receipt))) } #[rocket::get("/")]