Skip to main content

web/pages/account/
edit.rs

1use askama::Template;
2use axum::{
3    Extension, Json,
4    extract::{Path, State},
5    http::StatusCode,
6    response::IntoResponse,
7};
8use finance::account::Account;
9use serde::Deserialize;
10use server::command::{CmdResult, FinanceEntity, account::GetAccount};
11use sqlx::types::Uuid;
12use std::sync::Arc;
13
14use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate};
15
16struct ScriptView {
17    id: Uuid,
18    name: Option<String>,
19}
20
21#[derive(Template)]
22#[template(path = "pages/account/edit.html")]
23struct AccountEditPage {
24    account_id: Uuid,
25    account_name: String,
26    tags: Vec<finance::tag::Tag>,
27    scripting_enabled: bool,
28    scripts: Vec<ScriptView>,
29}
30
31pub async fn account_edit_page(
32    Path(id): Path<Uuid>,
33    State(_data): State<Arc<AppState>>,
34    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
35) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
36    let user = &jwt_auth.user;
37
38    let account_result = GetAccount::new()
39        .user_id(user.id)
40        .account_id(id)
41        .run()
42        .await
43        .map_err(|e| {
44            let error_response = serde_json::json!({
45                "status": "fail",
46                "message": format!("Failed to get account: {e:?}"),
47            });
48            (StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
49        })?;
50
51    let (account, name) = if let Some(CmdResult::TaggedEntities { entities, .. }) = account_result
52        && let Some((FinanceEntity::Account(account), tags)) = entities.into_iter().next()
53    {
54        let name = if let Some(FinanceEntity::Tag(name_tag)) = tags.get("name") {
55            name_tag.tag_value.clone()
56        } else {
57            String::new()
58        };
59        (account, name)
60    } else {
61        let error_response = serde_json::json!({
62            "status": "fail",
63            "message": "Account not found",
64        });
65        return Err((StatusCode::NOT_FOUND, Json(error_response)));
66    };
67
68    let server_user = server::user::User { id: user.id };
69    let tags: Vec<finance::tag::Tag> = server_user
70        .get_account_tags(&account)
71        .await
72        .unwrap_or_default()
73        .into_iter()
74        .filter(|t| t.tag_name != "name")
75        .collect();
76
77    #[cfg(feature = "scripting")]
78    let scripts: Vec<ScriptView> = server_user
79        .list_scripts()
80        .await
81        .unwrap_or_default()
82        .into_iter()
83        .map(|s| ScriptView {
84            id: s.id,
85            name: s.name,
86        })
87        .collect();
88
89    #[cfg(not(feature = "scripting"))]
90    let scripts: Vec<ScriptView> = Vec::new();
91
92    let template = AccountEditPage {
93        account_id: account.id,
94        account_name: name,
95        tags,
96        scripting_enabled: cfg!(feature = "scripting"),
97        scripts,
98    };
99
100    Ok(HtmlTemplate(template))
101}
102
103#[derive(Deserialize)]
104pub struct RenameForm {
105    account_id: Uuid,
106    name: String,
107}
108
109#[derive(Deserialize)]
110struct AccountTagData {
111    name: String,
112    value: String,
113    description: Option<String>,
114}
115
116#[derive(Deserialize)]
117pub struct AccountTagsForm {
118    tags: Vec<AccountTagData>,
119}
120
121pub async fn rename_account(
122    State(_data): State<Arc<AppState>>,
123    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
124    Json(form): Json<RenameForm>,
125) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
126    let user = &jwt_auth.user;
127    let server_user = server::user::User { id: user.id };
128
129    let account = Account {
130        id: form.account_id,
131        parent: None,
132    };
133
134    let name_tag = finance::tag::Tag {
135        id: Uuid::new_v4(),
136        tag_name: "name".to_string(),
137        tag_value: form.name,
138        description: None,
139    };
140
141    server_user
142        .set_account_tag(&account, &name_tag)
143        .await
144        .map_err(|e| {
145            let error_response = serde_json::json!({
146                "status": "fail",
147                "message": t!("Failed to rename account"),
148            });
149            log::error!("Failed to rename account: {e:?}");
150            (StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
151        })?;
152
153    Ok(t!("Account renamed").to_string())
154}
155
156pub async fn account_tags_submit(
157    Path(id): Path<Uuid>,
158    State(_data): State<Arc<AppState>>,
159    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
160    Json(form): Json<AccountTagsForm>,
161) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
162    let user = &jwt_auth.user;
163    let server_user = server::user::User { id: user.id };
164
165    let account = Account { id, parent: None };
166
167    let existing_tags = server_user
168        .get_account_tags(&account)
169        .await
170        .unwrap_or_default();
171
172    for tag in &existing_tags {
173        if tag.tag_name == "name" {
174            continue;
175        }
176        let _ = server_user.detach_account_tag(id, tag.id).await;
177        let _ = server_user.cleanup_orphan_tag(tag.id).await;
178    }
179
180    for tag_data in form.tags {
181        if tag_data.name == "name" {
182            continue;
183        }
184        server_user
185            .create_account_tag(id, tag_data.name, tag_data.value, tag_data.description)
186            .await
187            .map_err(|e| {
188                let error_response = serde_json::json!({
189                    "status": "fail",
190                    "message": format!("Failed to create account tag: {:?}", e),
191                });
192                log::error!("Failed to create account tag: {e:?}");
193                (StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
194            })?;
195    }
196
197    Ok(t!("Account tags saved").to_string())
198}
199
200#[cfg(feature = "scripting")]
201pub async fn run_account_script(
202    Path((account_id, script_id)): Path<(Uuid, Uuid)>,
203    State(_data): State<Arc<AppState>>,
204    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
205) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
206    use scripting::ScriptExecutor;
207
208    let user = &jwt_auth.user;
209    let server_user = server::user::User { id: user.id };
210
211    let script = server_user.get_script(script_id).await.map_err(|e| {
212        let error_response = serde_json::json!({
213            "status": "fail",
214            "message": format!("Failed to get script: {e:?}"),
215        });
216        (StatusCode::NOT_FOUND, Json(error_response))
217    })?;
218
219    let transaction_ids = server_user
220        .list_transaction_ids_by_account(account_id)
221        .await
222        .map_err(|e| {
223            let error_response = serde_json::json!({
224                "status": "fail",
225                "message": format!("Failed to fetch transactions: {e:?}"),
226            });
227            (StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
228        })?;
229
230    let executor = ScriptExecutor::new();
231    let mut processed = 0u64;
232
233    // Per-tx I/O moved into `server::script::load_transaction_state`;
234    // this loop is thin glue around the typestate read path + the
235    // script-output write path. Lets CLI/TUI use the same helper
236    // when their migration lands.
237    for tx_id in &transaction_ids {
238        let state = match server::script::load_transaction_state(user.id, *tx_id).await {
239            Ok(Some(s)) => s,
240            Ok(None) => continue,
241            Err(e) => {
242                let error_response = serde_json::json!({
243                    "status": "fail",
244                    "message": format!("Failed to load transaction {tx_id}: {e:?}"),
245                });
246                return Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)));
247            }
248        };
249
250        let report = state
251            .run_scripts(&executor, &[(script.id, script.bytecode.clone())])
252            .map_err(|e| {
253                let error_response = serde_json::json!({
254                    "status": "fail",
255                    "message": format!("Script execution failed on {tx_id}: {e:?}"),
256                });
257                (StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
258            })?;
259        for failure in &report.failures {
260            log::error!(
261                "Script {sid} failed on tx {tx_id}: {code}: {message}",
262                sid = failure.script_id,
263                code = failure.code,
264                message = failure.message
265            );
266        }
267        let state = report.state;
268
269        for tag in &state.transaction_tags {
270            let _ = server_user
271                .create_transaction_tag(*tx_id, tag.tag_name.clone(), tag.tag_value.clone(), None)
272                .await;
273        }
274
275        for (split_id, tag) in &state.split_tags {
276            let _ = server_user
277                .create_split_tag(*split_id, tag.tag_name.clone(), tag.tag_value.clone(), None)
278                .await;
279        }
280
281        processed += 1;
282    }
283
284    Ok(format!("{}: {processed}", t!("Processed transactions")))
285}