1
use chrono::{DateTime, Duration, NaiveDate, Utc};
2
use forms::{FieldError, Form, FormValues};
3
use server::command::CmdResult;
4
use server::command::report::fixture::render;
5
use server::command::report::fixture::seed::{Ledger, seed};
6
use server::user::User;
7
use sqlx::PgPool;
8

            
9
use super::test_seed::seed_user;
10
use crate::forms::{Failure, Outcome, typed_report_on};
11

            
12
/// A ledger transaction posted two days from now, after the end of any default as-of.
13
1
pub(super) async fn post_after_today(ledger: &Ledger) -> anyhow::Result<()> {
14
1
    let later = Utc::now() + Duration::days(2);
15
1
    ledger
16
1
        .post(
17
1
            later,
18
1
            &[("Checking", "USD", 777, 1), ("Salary", "USD", -777, 1)],
19
1
        )
20
1
        .await?;
21
1
    Ok(())
22
1
}
23

            
24
/// The day the default dates are computed from; after every fixture transaction.
25
75
pub(super) fn today() -> NaiveDate {
26
75
    NaiveDate::from_ymd_opt(2030, 6, 15).expect("date")
27
75
}
28

            
29
/// [`today`] at noon UTC, the instant the default dates are computed at.
30
71
pub(super) fn now() -> DateTime<Utc> {
31
71
    today().and_hms_opt(12, 0, 0).expect("time").and_utc()
32
71
}
33

            
34
/// One fixture case: its title in the golden file and the form values that express it.
35
pub(super) struct Case {
36
    pub title: &'static str,
37
    pub values: FormValues,
38
}
39

            
40
72
pub(super) fn case(title: &'static str, pairs: &[(&str, &str)]) -> Case {
41
72
    let mut values = FormValues::default();
42
72
    for (key, value) in pairs {
43
171
        values.set(key, value);
44
    }
45
72
    Case { title, values }
46
72
}
47

            
48
impl Case {
49
    /// A `rows` field of the given rows; no rows marks the field present and empty.
50
7
    pub(super) fn rows(mut self, key: &str, rows: &[&[(&str, &str)]]) -> Self {
51
7
        self.values.set_rows(key);
52
7
        for row in rows {
53
32
            let cells = row.iter().map(|(k, v)| (k.to_string(), v.to_string()));
54
12
            self.values.push_row(key, cells.collect());
55
        }
56
7
        self
57
7
    }
58
}
59

            
60
33
pub(super) async fn ledger(pool: &PgPool) -> anyhow::Result<Ledger> {
61
33
    let id = seed_user(pool).await?;
62
33
    seed(User { id }).await
63
33
}
64

            
65
50
fn result(ledger: &Ledger, outcome: Outcome) -> String {
66
50
    let data = match outcome {
67
16
        Outcome::Balance(data) => CmdResult::Report(data),
68
14
        Outcome::Activity(data) => CmdResult::Activity(data),
69
20
        Outcome::Breakdown(data) => CmdResult::Breakdown(data),
70
        other => return format!("unexpected outcome {other:?}\n"),
71
    };
72
50
    render::data(ledger, &data)
73
50
}
74

            
75
/// A refusal reads as the command's own error; the field error the handler raises in its place
76
/// carries the same message under the `Wrong arguments` prefix.
77
11
fn failure(failure: Failure) -> String {
78
11
    match failure {
79
        Failure::Invalid(errors) => {
80
5
            let messages: Vec<&str> = errors.iter().map(|e| e.message.as_str()).collect();
81
5
            render::failure(format!("Wrong arguments: {}", messages.join("; ")))
82
        }
83
6
        other => render::failure(other),
84
    }
85
11
}
86

            
87
/// The cases run through the report form on the fixed [`today`], rendered like the M3k golden
88
/// file; the as-of that defaults to that day reads as the golden's open end.
89
3
pub(super) async fn golden(form: &Form, ledger: &Ledger, cases: &[Case]) -> String {
90
3
    let mut text = String::new();
91
3
    for case in cases {
92
61
        if !text.is_empty() {
93
58
            text.push('\n');
94
3
        }
95
61
        text.push_str(&format!("== {}\n", case.title));
96
61
        text.push_str(
97
61
            &match typed_report_on(ledger.user.id, form, &case.values, now())
98
61
                .await
99
61
                .map(Outcome::from)
100
            {
101
50
                Ok(outcome) => result(ledger, outcome),
102
11
                Err(error) => failure(error),
103
            },
104
        );
105
    }
106
3
    let open_end = format!("to={}T23:59:59.999999+00:00", today());
107
3
    text.replace(&open_end, "to=-")
108
3
}
109

            
110
8
fn field_errors(result: Result<Outcome, Failure>) -> anyhow::Result<Vec<(String, String)>> {
111
8
    match result {
112
8
        Err(Failure::Invalid(errors)) => Ok(errors
113
8
            .into_iter()
114
14
            .map(|FieldError { field, message }| (field, message))
115
            .collect()),
116
        other => anyhow::bail!("expected field errors, got {other:?}"),
117
    }
118
8
}
119

            
120
8
pub(super) async fn invalid(
121
8
    pool: &PgPool,
122
8
    form: &Form,
123
8
    values: &FormValues,
124
8
) -> anyhow::Result<Vec<(String, String)>> {
125
8
    let l = ledger(pool).await?;
126
8
    field_errors(
127
8
        typed_report_on(l.user.id, form, values, now())
128
8
            .await
129
8
            .map(Outcome::from),
130
    )
131
8
}