Skip to main content

web/pages/transaction/
new.rs

1//! The create page over the shared forms: `TRANSACTION_CREATE` rendered by
2//! `form_render` and submitted through `rpc::forms::submit`.
3
4use std::collections::BTreeMap;
5
6use askama::Template;
7use axum::{
8    Extension, Form,
9    extract::Query,
10    response::{IntoResponse, Response},
11};
12use forms::{FieldError, FormValues, Row, Source, TRANSACTION_CREATE};
13use rpc::forms::{Failure, FormAction, FormOption, count_result};
14use serde::Deserialize;
15use uuid::Uuid;
16
17use crate::form_invalid::form_invalid;
18use crate::form_render::{References, render_form};
19use crate::pages::{
20    HtmlTemplate,
21    forms::{failure_error, message, references, request::Request},
22};
23use crate::{jwt_auth::JWTAuthMiddleware, response::WebError};
24
25pub const SUBMIT_PATH: &str = "/api/transaction/new/submit";
26
27#[derive(Deserialize)]
28pub struct NewParams {
29    template: Option<String>,
30    from_account: Option<String>,
31}
32
33#[derive(Template)]
34#[template(path = "pages/transaction/new.html")]
35struct NewPage {
36    form: String,
37}
38
39/// The message of a successful create, shown in the form's result box.
40#[must_use]
41pub fn created_message(id: Uuid) -> String {
42    format!("{}: {id}", t!("New transaction created with ID"))
43}
44
45fn render(
46    values: &FormValues,
47    errors: &[FieldError],
48    references: &References,
49) -> Result<String, WebError> {
50    render_form(&TRANSACTION_CREATE, values, errors, SUBMIT_PATH, references)
51        .map_err(|e| WebError::internal("Create form render failed", e))
52}
53
54fn template_error(failure: Failure) -> WebError {
55    match failure {
56        Failure::Refused(reason) => {
57            WebError::unprocessable(format!("The template cannot be shown as a form: {reason}"))
58        }
59        other => failure_error("Template load failed", other),
60    }
61}
62
63/// The plain create page: one empty split row.
64#[must_use]
65pub fn blank_values() -> FormValues {
66    first_row(Row::new())
67}
68
69fn first_row(row: Row) -> FormValues {
70    let mut values = FormValues::default();
71    values.push_row("splits", row);
72    values
73}
74
75/// The values of a create page and the cells a fill wrote into them.
76struct Seed {
77    values: FormValues,
78    filled: BTreeMap<String, bool>,
79}
80
81impl From<FormValues> for Seed {
82    fn from(values: FormValues) -> Self {
83        Self {
84            values,
85            filled: BTreeMap::new(),
86        }
87    }
88}
89
90/// The first row of a pick of `option`: its only commodity fills the
91/// from-commodity, which fills the to-commodity in turn, each marked filled.
92fn picked_row(option: &FormOption) -> (Row, BTreeMap<String, bool>) {
93    let mut row = Row::from([("from".to_string(), option.id.to_string())]);
94    let mut filled = BTreeMap::new();
95    for cell in ["from-commodity", "to-commodity"] {
96        if let Some(commodity) = option.commodity {
97            row.insert(cell.to_string(), commodity.to_string());
98            filled.insert(format!("splits.0.{cell}"), false);
99        }
100    }
101    (row, filled)
102}
103
104/// The first row starts as a pick of the account `id` when it is one of the
105/// user's own; anything else seeds the blank page.
106async fn from_account(user_id: Uuid, id: Option<&str>) -> Result<Seed, WebError> {
107    let Some(wanted) = id.and_then(|id| Uuid::parse_str(id.trim()).ok()) else {
108        return Ok(blank_values().into());
109    };
110    let options = rpc::forms::options(user_id, Source::Accounts)
111        .await
112        .map_err(|f| failure_error("Account options failed", f))?;
113    Ok(match options.iter().find(|option| option.id == wanted) {
114        Some(option) => {
115            let (row, filled) = picked_row(option);
116            Seed {
117                values: first_row(row),
118                filled,
119            }
120        }
121        None => blank_values().into(),
122    })
123}
124
125/// A template wins over `from_account`; a create without a date starts now.
126async fn seed(user_id: Uuid, params: NewParams) -> Result<Seed, WebError> {
127    let mut seed = match params {
128        NewParams {
129            template: Some(template),
130            ..
131        } => count_result(
132            TRANSACTION_CREATE.name,
133            FormAction::Load,
134            rpc::forms::load(user_id, &TRANSACTION_CREATE, &template).await,
135        )
136        .map(Seed::from)
137        .map_err(template_error)?,
138        NewParams {
139            from_account: id, ..
140        } => from_account(user_id, id.as_deref()).await?,
141    };
142    if seed.values.text("date").is_none_or(str::is_empty) {
143        seed.values.set("date", &forms::now_instant());
144    }
145    Ok(seed)
146}
147
148pub async fn transaction_new_page(
149    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
150    Query(params): Query<NewParams>,
151) -> Result<impl IntoResponse, WebError> {
152    let Seed { values, filled } = seed(jwt_auth.user.id, params).await?;
153    let mut references = references(&TRANSACTION_CREATE, jwt_auth.user.id, BTreeMap::new()).await?;
154    references.filled = filled;
155    let form = render(&values, &[], &references)?;
156    Ok(HtmlTemplate(NewPage { form }))
157}
158
159pub async fn transaction_new_submit(
160    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
161    Form(pairs): Form<Vec<(String, String)>>,
162) -> Result<Response, WebError> {
163    let request = Request::read(
164        &TRANSACTION_CREATE,
165        FormAction::Submit,
166        jwt_auth.user.id,
167        pairs,
168    )
169    .await?;
170    let submitted = request
171        .settle(async |values| {
172            rpc::forms::submit(jwt_auth.user.id, &TRANSACTION_CREATE, values).await
173        })
174        .await;
175    match submitted {
176        Ok(submitted) => message::reply(&created_message(submitted.id)),
177        Err(Failure::Invalid(errors)) => Ok(form_invalid(
178            &TRANSACTION_CREATE,
179            render(&request.values, &errors, &request.references)?,
180        )),
181        Err(failure) => Err(failure_error("Transaction create failed", failure)),
182    }
183}