1
//! The commodity edit page over the `commodity-edit` form, served on its
2
//! production paths (plan 0016 M3i).
3

            
4
use axum::{
5
    Router,
6
    http::StatusCode,
7
    routing::{get, post},
8
};
9
use forms::COMMODITY_EDIT;
10
use server::command::commodity_tag::SetCommodityTag;
11
use sqlx::types::Uuid;
12
use web::model::User;
13
use web::pages::commodity::edit::{
14
    SUBMIT_PATH, commodity_edit_page, commodity_edit_submit, updated_message,
15
};
16

            
17
use crate::common::create_mock_user;
18
use crate::common::edit_page::{posted, with_value};
19
use crate::common::entity_edit::{
20
    form_html, form_pairs, fresh_revision, get_from, post_to, with_tags,
21
};
22
use crate::common::new_page::Reply;
23
use crate::common::seed::commodity_with_name;
24
use crate::common::tenant::{provision_tenant, tenant_connection};
25

            
26
const FORM: &str = "nf-commodity-edit";
27

            
28
12
fn router() -> Router<std::sync::Arc<web::AppState>> {
29
12
    Router::new()
30
12
        .route("/commodity/{id}/edit", get(commodity_edit_page))
31
12
        .route_layer(axum::middleware::from_fn(web::error_render::full_page))
32
12
        .route(SUBMIT_PATH, post(commodity_edit_submit))
33
12
}
34

            
35
7
async fn page(user: &User, id: &str) -> Reply {
36
7
    get_from(router(), user, &format!("/commodity/{id}/edit")).await
37
7
}
38

            
39
5
async fn submit(user: &User, pairs: &[(String, String)]) -> Reply {
40
5
    post_to(router(), user, SUBMIT_PATH, pairs).await
41
5
}
42

            
43
8
async fn set_tag(user: &User, commodity: Uuid, name: &str, value: &str) {
44
8
    SetCommodityTag::new()
45
8
        .user_id(user.id)
46
8
        .commodity_id(commodity)
47
8
        .tag_name(name.to_string())
48
8
        .tag_value(value.to_string())
49
8
        .run()
50
8
        .await
51
8
        .expect("set tag");
52
8
}
53

            
54
7
async fn seeded() -> (User, Uuid) {
55
7
    let user = create_mock_user();
56
7
    provision_tenant(user.id).await;
57
7
    let usd = commodity_with_name(user.id, "USD", "Dollar").await;
58
7
    set_tag(&user, usd, "kind", "fiat").await;
59
7
    (user, usd)
60
7
}
61

            
62
3
async fn stored(user: &User, commodity: Uuid) -> forms::FormValues {
63
3
    rpc::forms::load(user.id, &COMMODITY_EDIT, &commodity.to_string())
64
3
        .await
65
3
        .expect("load")
66
3
}
67

            
68
#[supp_macro::shared_runtime_test]
69
1
async fn the_page_renders_the_edit_form_with_the_loaded_values() {
70
1
    let (user, usd) = seeded().await;
71
1
    let reply = page(&user, &usd.to_string()).await;
72

            
73
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
74
1
    let pairs = form_pairs(&reply.body, FORM);
75
1
    assert_eq!(posted(&pairs, "id"), usd.to_string());
76
1
    assert_eq!(posted(&pairs, "symbol"), "USD");
77
1
    assert_eq!(posted(&pairs, "name"), "Dollar");
78
1
    assert_eq!(posted(&pairs, "tags.0.name"), "kind");
79
1
    assert_eq!(posted(&pairs, "tags.0.value"), "fiat");
80
1
    assert!(!posted(&pairs, "revision").is_empty());
81
}
82

            
83
#[supp_macro::shared_runtime_test]
84
1
async fn a_submit_renames_and_sets_and_clears_tags() {
85
1
    let (user, usd) = seeded().await;
86
1
    let loaded = page(&user, &usd.to_string()).await;
87
1
    let sent = with_tags(
88
1
        &with_value(
89
1
            &with_value(&form_pairs(&loaded.body, FORM), "symbol", "DOL"),
90
1
            "name",
91
1
            "Buck",
92
1
        ),
93
1
        &[("color", "green")],
94
1
    );
95
1
    let reply = submit(&user, &sent).await;
96
1
    let after = stored(&user, usd).await;
97

            
98
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
99
1
    assert!(
100
1
        reply.body.starts_with(&updated_message(usd)),
101
        "{}",
102
        reply.body
103
    );
104
1
    assert_eq!(after.text("symbol"), Some("DOL"));
105
1
    assert_eq!(after.text("name"), Some("Buck"));
106
1
    let rows = after.rows("tags").unwrap_or_default();
107
1
    assert_eq!(rows.len(), 1);
108
1
    assert_eq!(rows[0]["name"], "color");
109
}
110

            
111
#[supp_macro::shared_runtime_test]
112
1
async fn an_invalid_submit_rerenders_the_form_with_its_errors() {
113
1
    let (user, usd) = seeded().await;
114
1
    let loaded = page(&user, &usd.to_string()).await;
115
1
    let sent = with_value(&form_pairs(&loaded.body, FORM), "symbol", "");
116
1
    let reply = submit(&user, &sent).await;
117
1
    let after = stored(&user, usd).await;
118

            
119
1
    assert_eq!(
120
1
        reply.status,
121
1
        StatusCode::UNPROCESSABLE_ENTITY,
122
        "{}",
123
        reply.body
124
    );
125
1
    assert_eq!(
126
1
        reply
127
1
            .headers
128
1
            .get("hx-retarget")
129
1
            .and_then(|v| v.to_str().ok()),
130
1
        Some("#nf-commodity-edit")
131
    );
132
1
    assert!(form_html(&reply.body, FORM).contains("field-error"));
133
1
    assert_eq!(after.text("symbol"), Some("USD"));
134
}
135

            
136
#[supp_macro::shared_runtime_test]
137
1
async fn a_stale_submit_shows_the_banner_with_a_reload_link() {
138
1
    let (user, usd) = seeded().await;
139
1
    let loaded = page(&user, &usd.to_string()).await;
140
1
    set_tag(&user, usd, "color", "green").await;
141
1
    let reply = submit(&user, &form_pairs(&loaded.body, FORM)).await;
142

            
143
1
    assert_eq!(
144
1
        reply.status,
145
1
        StatusCode::UNPROCESSABLE_ENTITY,
146
        "{}",
147
        reply.body
148
    );
149
1
    let form = form_html(&reply.body, FORM);
150
1
    assert!(form.contains("form-banner"), "{form}");
151
1
    assert!(form.contains("form-reload"), "{form}");
152
1
    assert!(
153
1
        form.contains(&format!("href=\"/commodity/{usd}/edit\"")),
154
        "{form}"
155
    );
156
}
157

            
158
#[supp_macro::shared_runtime_test]
159
1
async fn a_refused_load_shows_the_refusal_page() {
160
1
    let (user, usd) = seeded().await;
161
1
    let twin = Uuid::new_v4();
162
1
    let mut conn = tenant_connection(user.id).await;
163
1
    sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, 'kind', 'again')")
164
1
        .bind(twin)
165
1
        .execute(&mut *conn)
166
1
        .await
167
1
        .expect("tag");
168
1
    sqlx::query("INSERT INTO commodity_tags (commodity_id, tag_id) VALUES ($1, $2)")
169
1
        .bind(usd)
170
1
        .bind(twin)
171
1
        .execute(&mut *conn)
172
1
        .await
173
1
        .expect("link");
174
1
    let reply = page(&user, &usd.to_string()).await;
175

            
176
1
    assert_eq!(
177
1
        reply.status,
178
1
        StatusCode::UNPROCESSABLE_ENTITY,
179
        "{}",
180
        reply.body
181
    );
182
1
    assert!(
183
1
        reply.body.contains("two values of the tag"),
184
        "{}",
185
        reply.body
186
    );
187
1
    assert!(!reply.body.contains(FORM), "{}", reply.body);
188
}
189

            
190
#[supp_macro::shared_runtime_test]
191
1
async fn an_unknown_commodity_has_its_typed_page() {
192
1
    let (user, _) = seeded().await;
193
1
    let reply = page(&user, &Uuid::new_v4().to_string()).await;
194

            
195
1
    assert_eq!(reply.status, StatusCode::NOT_FOUND, "{}", reply.body);
196
}
197

            
198
#[supp_macro::shared_runtime_test]
199
1
async fn two_saves_from_one_page_both_succeed_with_the_swapped_revision() {
200
1
    let (user, usd) = seeded().await;
201
1
    let loaded = page(&user, &usd.to_string()).await;
202
1
    let first = with_value(&form_pairs(&loaded.body, FORM), "name", "Buck");
203
1
    let saved = submit(&user, &first).await;
204
1
    let next = with_value(
205
1
        &with_value(&first, "revision", &fresh_revision(&saved.body)),
206
1
        "name",
207
1
        "Bucks",
208
1
    );
209
1
    let again = submit(&user, &next).await;
210
1
    let after = stored(&user, usd).await;
211

            
212
1
    assert_eq!(saved.status, StatusCode::OK, "{}", saved.body);
213
1
    assert!(
214
1
        saved.body.starts_with(&updated_message(usd)),
215
        "{}",
216
        saved.body
217
    );
218
1
    assert_eq!(again.status, StatusCode::OK, "{}", again.body);
219
1
    assert_eq!(after.text("name"), Some("Bucks"));
220
}