1
//! The edit page over the shared forms, served on its production paths.
2

            
3
use axum::{
4
    Router,
5
    body::Body,
6
    http::Request,
7
    routing::{get, post},
8
};
9
use forms::{FormValues, TRANSACTION_CREATE};
10
use sqlx::types::Uuid;
11
use web::model::User;
12
use web::pages::transaction::update::{
13
    SUBMIT_PATH, transaction_update_page, transaction_update_submit,
14
};
15

            
16
use crate::common::controls;
17
use crate::common::create_mock_user;
18
use crate::common::new_page::{Reply, send_to};
19
use crate::common::seed::{commodity_id, named_account, named_commodity};
20
use crate::common::tenant::{provision_tenant, tenant_connection};
21

            
22
pub const POST_DATE: &str = "2026-10-27T09:15:42.123456Z";
23

            
24
/// A tenant with the accounts `Cash`, `Food` and the commodities `USD`, `EUR`.
25
pub struct Ledger {
26
    pub user: User,
27
    pub cash: Uuid,
28
    pub food: Uuid,
29
    pub usd: Uuid,
30
}
31

            
32
20
pub async fn ledger() -> Ledger {
33
20
    let user = create_mock_user();
34
20
    provision_tenant(user.id).await;
35
20
    let cash = named_account(user.id, "Cash").await;
36
20
    let food = named_account(user.id, "Food").await;
37
20
    let usd = named_commodity(user.id, "USD").await;
38
20
    named_commodity(user.id, "EUR").await;
39
20
    Ledger {
40
20
        user,
41
20
        cash,
42
20
        food,
43
20
        usd,
44
20
    }
45
20
}
46

            
47
41
async fn send(user: &User, request: Request<Body>) -> Reply {
48
41
    let router = Router::new()
49
41
        .route("/transaction/{id}/edit", get(transaction_update_page))
50
41
        .route_layer(axum::middleware::from_fn(web::error_render::full_page))
51
41
        .route(SUBMIT_PATH, post(transaction_update_submit));
52
41
    send_to(router, user, request).await
53
41
}
54

            
55
26
pub async fn get_edit(user: &User, id: &str) -> Reply {
56
26
    let request = Request::builder()
57
26
        .uri(format!("/transaction/{id}/edit"))
58
26
        .body(Body::empty())
59
26
        .expect("request");
60
26
    send(user, request).await
61
26
}
62

            
63
15
pub async fn post_edit(user: &User, pairs: &[(String, String)]) -> Reply {
64
15
    let body = serde_urlencoded::to_string(pairs).expect("urlencoded");
65
15
    let request = Request::builder()
66
15
        .method("POST")
67
15
        .uri(SUBMIT_PATH)
68
15
        .header("content-type", "application/x-www-form-urlencoded")
69
15
        .header("hx-request", "true")
70
15
        .body(Body::from(body))
71
15
        .expect("request");
72
15
    send(user, request).await
73
15
}
74

            
75
/// The rendered edit form, from its id to its end.
76
18
pub fn edit_form(html: &str) -> &str {
77
18
    let start = html
78
18
        .find("id=\"nf-transaction-edit\"")
79
        .unwrap_or_else(|| panic!("no edit form in {html}"));
80
18
    let form = &html[start..];
81
18
    &form[..form.find("</form>").expect("form end")]
82
18
}
83

            
84
/// What a browser posts from the rendered edit form: every named, enabled
85
/// control outside `<template>`, line breaks normalised to CRLF.
86
15
pub fn browser_pairs(html: &str) -> Vec<(String, String)> {
87
15
    controls::pairs(edit_form(html))
88
15
        .into_iter()
89
456
        .map(|(name, value)| (name, value.replace('\n', "\r\n")))
90
        .collect()
91
15
}
92

            
93
/// `pairs` with the value of `name` replaced.
94
45
pub fn with_value(pairs: &[(String, String)], name: &str, value: &str) -> Vec<(String, String)> {
95
45
    assert!(
96
224
        pairs.iter().any(|(n, _)| n == name),
97
        "no {name} in {pairs:?}"
98
    );
99
45
    pairs
100
45
        .iter()
101
626
        .map(|(n, v)| match n == name {
102
45
            true => (n.clone(), value.to_string()),
103
581
            false => (n.clone(), v.clone()),
104
626
        })
105
        .collect()
106
45
}
107

            
108
/// The value posted under `name`.
109
67
pub fn posted<'a>(pairs: &'a [(String, String)], name: &str) -> &'a str {
110
67
    pairs
111
67
        .iter()
112
605
        .find(|(n, _)| n == name)
113
67
        .map(|(_, v)| v.as_str())
114
        .unwrap_or_else(|| panic!("no {name} in {pairs:?}"))
115
67
}
116

            
117
/// An FX transaction `Cash` → `Food`, 10 USD for 9 EUR, with a transaction
118
/// tag and a split tag.
119
18
pub async fn fx_transaction(ledger: &Ledger, note: &str) -> Uuid {
120
54
    let [cash, food, usd] = [ledger.cash, ledger.food, ledger.usd].map(|id| id.to_string());
121
18
    let eur = commodity_id(ledger.user.id, "EUR").await;
122
18
    let pairs = [
123
18
        ("date", POST_DATE),
124
18
        ("note", note),
125
18
        ("tags", ""),
126
18
        ("tags.0.name", "trip"),
127
18
        ("tags.0.value", "japan"),
128
18
        ("tags.0.description", "spring"),
129
18
        ("splits", ""),
130
18
        ("splits.0.key", "n1"),
131
18
        ("splits.0.from", cash.as_str()),
132
18
        ("splits.0.to", food.as_str()),
133
18
        ("splits.0.from-commodity", usd.as_str()),
134
18
        ("splits.0.to-commodity", eur.as_str()),
135
18
        ("splits.0.value", "10"),
136
18
        ("splits.0.to-amount", "9"),
137
18
        ("splits.0.hidden", ""),
138
18
        ("split-tags", ""),
139
18
        ("split-tags.0.row", "n1"),
140
18
        ("split-tags.0.name", "memo"),
141
18
        ("split-tags.0.value", "m"),
142
18
        ("split-tags.0.description", "split memo"),
143
18
    ]
144
360
    .map(|(n, v)| (n.to_string(), v.to_string()));
145
18
    let values = FormValues::from_pairs(&TRANSACTION_CREATE, pairs).expect("pairs");
146
18
    rpc::forms::submit(ledger.user.id, &TRANSACTION_CREATE, &values)
147
18
        .await
148
18
        .expect("create")
149
        .id
150
18
}
151

            
152
/// Run `sql` with `$1` bound to `transaction` in the tenant of `user`.
153
7
pub async fn alter(user: &User, sql: &str, transaction: Uuid) {
154
7
    let mut conn = tenant_connection(user.id).await;
155
7
    sqlx::query(sqlx::AssertSqlSafe(sql.to_string()))
156
7
        .bind(transaction)
157
7
        .execute(&mut *conn)
158
7
        .await
159
7
        .expect("alter");
160
7
}