1
//! Helpers of the account and commodity edit tests: the rendered form's own
2
//! fields in, the production routes behind.
3

            
4
use axum::{Router, body::Body, http::Request};
5
use web::model::User;
6

            
7
use crate::common::controls;
8
use crate::common::new_page::{Reply, send_to};
9

            
10
/// The rendered form `id`, from its id to its end.
11
53
pub fn form_html<'a>(html: &'a str, id: &str) -> &'a str {
12
53
    let start = html
13
53
        .find(&format!("id=\"{id}\""))
14
        .unwrap_or_else(|| panic!("no {id} in {html}"));
15
53
    let form = &html[start..];
16
53
    &form[..form.find("</form>").expect("form end")]
17
53
}
18

            
19
/// What a browser posts from the rendered form `id`.
20
32
pub fn form_pairs(html: &str, id: &str) -> Vec<(String, String)> {
21
32
    controls::pairs(form_html(html, id))
22
32
}
23

            
24
53
pub async fn get_from(
25
53
    router: Router<std::sync::Arc<web::AppState>>,
26
53
    user: &User,
27
53
    uri: &str,
28
53
) -> Reply {
29
53
    let request = Request::builder()
30
53
        .uri(uri)
31
53
        .body(Body::empty())
32
53
        .expect("request");
33
53
    send_to(router, user, request).await
34
53
}
35

            
36
66
pub async fn post_to(
37
66
    router: Router<std::sync::Arc<web::AppState>>,
38
66
    user: &User,
39
66
    uri: &str,
40
66
    pairs: &[(String, String)],
41
66
) -> Reply {
42
66
    let body = serde_urlencoded::to_string(pairs).expect("urlencoded");
43
66
    let request = Request::builder()
44
66
        .method("POST")
45
66
        .uri(uri)
46
66
        .header("content-type", "application/x-www-form-urlencoded")
47
66
        .header("hx-request", "true")
48
66
        .body(Body::from(body))
49
66
        .expect("request");
50
66
    send_to(router, user, request).await
51
66
}
52

            
53
/// `pairs` without the rows named `prefix`, plus the tag rows `tags`.
54
2
pub fn with_tags(pairs: &[(String, String)], tags: &[(&str, &str)]) -> Vec<(String, String)> {
55
2
    let mut kept: Vec<(String, String)> = pairs
56
2
        .iter()
57
17
        .filter(|(name, _)| !name.starts_with("tags."))
58
        .cloned()
59
        .collect();
60
2
    for (index, (name, value)) in tags.iter().enumerate() {
61
2
        kept.push((format!("tags.{index}.name"), name.to_string()));
62
2
        kept.push((format!("tags.{index}.value"), value.to_string()));
63
    }
64
2
    kept
65
2
}
66

            
67
/// The revision a save reply swaps into the form.
68
5
pub fn fresh_revision(body: &str) -> String {
69
5
    let named = body
70
5
        .find("name=\"revision\"")
71
        .unwrap_or_else(|| panic!("no fresh revision in {body}"));
72
5
    let rest = &body[named..];
73
5
    let start = rest.find("value=\"").expect("value") + "value=\"".len();
74
5
    rest[start..][..rest[start..].find('"').expect("quote")].to_string()
75
5
}