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

            
3
use axum::{
4
    Router,
5
    body::Body,
6
    http::{HeaderMap, Request, StatusCode},
7
    routing::{get, post},
8
};
9
use sqlx::types::Uuid;
10
use std::sync::Arc;
11
use tower::ServiceExt;
12
use web::AppState;
13
use web::model::User;
14
use web::pages::transaction::new::{SUBMIT_PATH, transaction_new_page, transaction_new_submit};
15

            
16
use crate::common::seed::{account_id, commodity_id, named_account, named_commodity};
17
use crate::common::tenant::{provision_tenant, tenant_connection};
18
use crate::common::{authenticated, create_mock_user, create_test_app_state};
19

            
20
pub struct Reply {
21
    pub status: StatusCode,
22
    pub headers: HeaderMap,
23
    pub body: String,
24
}
25

            
26
129
async fn send(user: &User, request: Request<Body>) -> Reply {
27
129
    let router = Router::new()
28
129
        .route("/transaction/new", get(transaction_new_page))
29
129
        .route_layer(axum::middleware::from_fn(web::error_render::full_page))
30
129
        .route(SUBMIT_PATH, post(transaction_new_submit));
31
129
    send_to(router, user, request).await
32
129
}
33

            
34
/// The reply of `router`, behind the test authentication, to `request`.
35
412
pub async fn send_to(router: Router<Arc<AppState>>, user: &User, request: Request<Body>) -> Reply {
36
412
    let response = authenticated(router, create_test_app_state().await, user.clone())
37
412
        .oneshot(request)
38
412
        .await
39
412
        .expect("response");
40
412
    let status = response.status();
41
412
    let headers = response.headers().clone();
42
412
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
43
412
        .await
44
412
        .expect("body");
45
412
    Reply {
46
412
        status,
47
412
        headers,
48
412
        body: String::from_utf8_lossy(&bytes).into_owned(),
49
412
    }
50
412
}
51

            
52
19
pub async fn get_page(user: &User, query: &str) -> Reply {
53
19
    let request = Request::builder()
54
19
        .uri(format!("/transaction/new?{query}"))
55
19
        .body(Body::empty())
56
19
        .expect("request");
57
19
    send(user, request).await
58
19
}
59

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

            
72
/// The id a successful create names in its message.
73
93
pub fn created_id(reply: &Reply) -> Uuid {
74
93
    let id = reply.body.rsplit(' ').next().unwrap_or_default();
75
93
    Uuid::parse_str(id).unwrap_or_else(|_| panic!("{} {}", reply.status, reply.body))
76
93
}
77

            
78
/// A tenant with `USD`, `EUR`, `Assets:Checking` and `Expenses:Food`.
79
84
pub async fn seeded_user() -> User {
80
84
    let user = create_mock_user();
81
84
    provision_tenant(user.id).await;
82
84
    named_commodity(user.id, "USD").await;
83
84
    named_commodity(user.id, "EUR").await;
84
84
    named_account(user.id, "Assets:Checking").await;
85
84
    named_account(user.id, "Expenses:Food").await;
86
84
    user
87
84
}
88

            
89
/// The ids of the entities `seeded_user` creates.
90
pub struct Ids {
91
    pub checking: String,
92
    pub food: String,
93
    pub usd: String,
94
    pub eur: String,
95
}
96

            
97
87
pub async fn seeded_ids(user: &User) -> Ids {
98
    Ids {
99
87
        checking: account_id(user.id, "Assets:Checking").await,
100
87
        food: account_id(user.id, "Expenses:Food").await,
101
87
        usd: commodity_id(user.id, "USD").await,
102
87
        eur: commodity_id(user.id, "EUR").await,
103
    }
104
87
}
105

            
106
20
pub async fn snapshot(user: &User, transaction: Uuid) -> Vec<String> {
107
20
    let mut conn = tenant_connection(user.id).await;
108
20
    server::lossless::snapshot(&mut *conn, transaction)
109
20
        .await
110
20
        .expect("snapshot")
111
20
}
112

            
113
/// Two creates differ only in when they were entered.
114
4
pub fn without_entered(facts: Vec<String>) -> Vec<String> {
115
4
    facts
116
4
        .into_iter()
117
36
        .map(|fact| match fact.split_once(" entered ") {
118
4
            Some((date, _)) if fact.starts_with("date ") => date.to_string(),
119
32
            _ => fact,
120
36
        })
121
        .collect()
122
4
}
123

            
124
/// The rendered create form, from its id to its end.
125
4
pub fn create_form(html: &str) -> &str {
126
4
    let start = html
127
4
        .find("id=\"nf-transaction-create\"")
128
4
        .expect("the create form");
129
4
    let form = &html[start..];
130
4
    &form[..form.find("</form>").expect("form end")]
131
4
}
132

            
133
/// The `name` attributes of the rendered create form, without those of its
134
/// `<template>` rows.
135
1
pub fn form_names(html: &str) -> Vec<String> {
136
1
    create_form(html)
137
1
        .split(" name=\"")
138
1
        .skip(1)
139
40
        .filter_map(|tail| tail.split('"').next())
140
40
        .filter(|name| !name.contains("__INDEX__"))
141
1
        .map(str::to_string)
142
        .collect()
143
1
}
144

            
145
/// The `value` attribute of the input named `name`.
146
64
pub fn input_value<'a>(html: &'a str, name: &str) -> Option<&'a str> {
147
64
    let (_, tail) = html.split_once(&format!("name=\"{name}\""))?;
148
63
    let tag = tail.split('>').next()?;
149
63
    let (_, value) = tag.split_once("value=\"")?;
150
63
    value.split('"').next()
151
64
}
152

            
153
/// The text of the textarea named `name`, without the newline the renderer
154
/// puts first.
155
5
pub fn textarea<'a>(html: &'a str, name: &str) -> Option<&'a str> {
156
5
    let (_, tail) = html.split_once(&format!("<textarea name=\"{name}\""))?;
157
5
    let (_, text) = tail.split_once(">\n")?;
158
5
    text.split("</textarea>").next()
159
5
}
160

            
161
/// The id of the account or commodity option labelled `label`.
162
2
pub async fn option_id(user: &User, source: forms::Source, label: &str) -> Uuid {
163
2
    rpc::forms::options(user.id, source)
164
2
        .await
165
2
        .expect("options")
166
        .into_iter()
167
3
        .find(|option| option.label == label)
168
2
        .map(|option| option.id)
169
2
        .expect("an option with the label")
170
2
}
171

            
172
/// Whether the select control labelled `name` is marked as written by a fill.
173
4
pub fn marked_filled(html: &str, name: &str) -> bool {
174
4
    html.split_once(&format!("name=\"label:{name}\""))
175
4
        .and_then(|(_, tail)| tail.split('>').next())
176
4
        .is_some_and(|tag| tag.contains("data-filled"))
177
4
}
178

            
179
/// Posts a create of 10 `commodity` from `from` to `to`.
180
3
pub async fn spend(user: &User, from: Uuid, to: Uuid, commodity: Uuid) {
181
9
    let [from, to, commodity] = [from, to, commodity].map(|id| id.to_string());
182
3
    let reply = post_form(
183
3
        user,
184
3
        &[
185
3
            ("date", "2026-01-02T03:04:00Z"),
186
3
            ("note", "n"),
187
3
            ("tags", ""),
188
3
            ("splits", ""),
189
3
            ("splits.0.key", "n1"),
190
3
            ("splits.0.from", from.as_str()),
191
3
            ("splits.0.to", to.as_str()),
192
3
            ("splits.0.from-commodity", commodity.as_str()),
193
3
            ("splits.0.value", "10"),
194
3
            ("splits.0.hidden", ""),
195
3
            ("split-tags", ""),
196
3
        ],
197
3
    )
198
3
    .await;
199
3
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
200
3
}