1
//! The create page over the shared forms: `TRANSACTION_CREATE` rendered by
2
//! `form_render` and submitted through `rpc::forms::submit`.
3

            
4
use std::collections::BTreeMap;
5

            
6
use askama::Template;
7
use axum::{
8
    Extension, Form,
9
    extract::Query,
10
    response::{IntoResponse, Response},
11
};
12
use forms::{FieldError, FormValues, Row, Source, TRANSACTION_CREATE};
13
use rpc::forms::{Failure, FormAction, FormOption, count_result};
14
use serde::Deserialize;
15
use uuid::Uuid;
16

            
17
use crate::form_invalid::form_invalid;
18
use crate::form_render::{References, render_form};
19
use crate::pages::{
20
    HtmlTemplate,
21
    forms::{failure_error, message, references, request::Request},
22
};
23
use crate::{jwt_auth::JWTAuthMiddleware, response::WebError};
24

            
25
pub const SUBMIT_PATH: &str = "/api/transaction/new/submit";
26

            
27
#[derive(Deserialize)]
28
pub struct NewParams {
29
    template: Option<String>,
30
    from_account: Option<String>,
31
}
32

            
33
#[derive(Template)]
34
#[template(path = "pages/transaction/new.html")]
35
struct NewPage {
36
    form: String,
37
}
38

            
39
/// The message of a successful create, shown in the form's result box.
40
#[must_use]
41
101
pub fn created_message(id: Uuid) -> String {
42
101
    format!("{}: {id}", t!("New transaction created with ID"))
43
101
}
44

            
45
20
fn render(
46
20
    values: &FormValues,
47
20
    errors: &[FieldError],
48
20
    references: &References,
49
20
) -> Result<String, WebError> {
50
20
    render_form(&TRANSACTION_CREATE, values, errors, SUBMIT_PATH, references)
51
        .map_err(|e| WebError::internal("Create form render failed", e))
52
20
}
53

            
54
5
fn template_error(failure: Failure) -> WebError {
55
5
    match failure {
56
        Failure::Refused(reason) => {
57
4
            WebError::unprocessable(format!("The template cannot be shown as a form: {reason}"))
58
        }
59
1
        other => failure_error("Template load failed", other),
60
    }
61
5
}
62

            
63
/// The plain create page: one empty split row.
64
#[must_use]
65
6
pub fn blank_values() -> FormValues {
66
6
    first_row(Row::new())
67
6
}
68

            
69
9
fn first_row(row: Row) -> FormValues {
70
9
    let mut values = FormValues::default();
71
9
    values.push_row("splits", row);
72
9
    values
73
9
}
74

            
75
/// The values of a create page and the cells a fill wrote into them.
76
struct Seed {
77
    values: FormValues,
78
    filled: BTreeMap<String, bool>,
79
}
80

            
81
impl From<FormValues> for Seed {
82
11
    fn from(values: FormValues) -> Self {
83
11
        Self {
84
11
            values,
85
11
            filled: BTreeMap::new(),
86
11
        }
87
11
    }
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.
92
3
fn picked_row(option: &FormOption) -> (Row, BTreeMap<String, bool>) {
93
3
    let mut row = Row::from([("from".to_string(), option.id.to_string())]);
94
3
    let mut filled = BTreeMap::new();
95
3
    for cell in ["from-commodity", "to-commodity"] {
96
6
        if let Some(commodity) = option.commodity {
97
2
            row.insert(cell.to_string(), commodity.to_string());
98
2
            filled.insert(format!("splits.0.{cell}"), false);
99
4
        }
100
    }
101
3
    (row, filled)
102
3
}
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.
106
7
async fn from_account(user_id: Uuid, id: Option<&str>) -> Result<Seed, WebError> {
107
7
    let Some(wanted) = id.and_then(|id| Uuid::parse_str(id.trim()).ok()) else {
108
3
        return Ok(blank_values().into());
109
    };
110
4
    let options = rpc::forms::options(user_id, Source::Accounts)
111
4
        .await
112
        .map_err(|f| failure_error("Account options failed", f))?;
113
8
    Ok(match options.iter().find(|option| option.id == wanted) {
114
        Some(option) => {
115
3
            let (row, filled) = picked_row(option);
116
3
            Seed {
117
3
                values: first_row(row),
118
3
                filled,
119
3
            }
120
        }
121
1
        None => blank_values().into(),
122
    })
123
7
}
124

            
125
/// A template wins over `from_account`; a create without a date starts now.
126
19
async fn seed(user_id: Uuid, params: NewParams) -> Result<Seed, WebError> {
127
19
    let mut seed = match params {
128
        NewParams {
129
            template: Some(template),
130
            ..
131
12
        } => count_result(
132
12
            TRANSACTION_CREATE.name,
133
12
            FormAction::Load,
134
12
            rpc::forms::load(user_id, &TRANSACTION_CREATE, &template).await,
135
        )
136
12
        .map(Seed::from)
137
12
        .map_err(template_error)?,
138
        NewParams {
139
            from_account: id, ..
140
7
        } => from_account(user_id, id.as_deref()).await?,
141
    };
142
14
    if seed.values.text("date").is_none_or(str::is_empty) {
143
9
        seed.values.set("date", &forms::now_instant());
144
5
    }
145
14
    Ok(seed)
146
19
}
147

            
148
19
pub async fn transaction_new_page(
149
19
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
150
19
    Query(params): Query<NewParams>,
151
19
) -> Result<impl IntoResponse, WebError> {
152
19
    let Seed { values, filled } = seed(jwt_auth.user.id, params).await?;
153
14
    let mut references = references(&TRANSACTION_CREATE, jwt_auth.user.id, BTreeMap::new()).await?;
154
14
    references.filled = filled;
155
14
    let form = render(&values, &[], &references)?;
156
14
    Ok(HtmlTemplate(NewPage { form }))
157
19
}
158

            
159
110
pub async fn transaction_new_submit(
160
110
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
161
110
    Form(pairs): Form<Vec<(String, String)>>,
162
110
) -> Result<Response, WebError> {
163
110
    let request = Request::read(
164
110
        &TRANSACTION_CREATE,
165
110
        FormAction::Submit,
166
110
        jwt_auth.user.id,
167
110
        pairs,
168
110
    )
169
110
    .await?;
170
107
    let submitted = request
171
208
        .settle(async |values| {
172
104
            rpc::forms::submit(jwt_auth.user.id, &TRANSACTION_CREATE, values).await
173
208
        })
174
107
        .await;
175
107
    match submitted {
176
101
        Ok(submitted) => message::reply(&created_message(submitted.id)),
177
6
        Err(Failure::Invalid(errors)) => Ok(form_invalid(
178
6
            &TRANSACTION_CREATE,
179
6
            render(&request.values, &errors, &request.references)?,
180
        )),
181
        Err(failure) => Err(failure_error("Transaction create failed", failure)),
182
    }
183
110
}