1
//! Form preflight: opens every stored transaction and template in the form
2
//! the way the clients do, and saves each transaction unchanged. The saves
3
//! commit: run it on a disposable restored copy only.
4

            
5
use std::fmt;
6

            
7
use server::db::DBError;
8
use server::preflight::tenants;
9
use server::user::User;
10
use uuid::Uuid;
11

            
12
use crate::natives::forms::{load_form, submit_form};
13

            
14
const EDIT: &str = "transaction-edit";
15
const CREATE: &str = "transaction-create";
16

            
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub enum Subject {
19
    Tenant,
20
    Transaction,
21
    Template,
22
}
23

            
24
impl fmt::Display for Subject {
25
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26
        f.write_str(match self {
27
            Self::Tenant => "tenant",
28
            Self::Transaction => "transaction",
29
            Self::Template => "template",
30
        })
31
    }
32
}
33

            
34
#[derive(Debug, Clone, PartialEq, Eq)]
35
pub struct Problem {
36
    pub user: Uuid,
37
    pub subject: Subject,
38
    pub id: Uuid,
39
    pub reason: String,
40
}
41

            
42
impl fmt::Display for Problem {
43
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44
        write!(
45
            f,
46
            "user {} {} {}: {}",
47
            self.user, self.subject, self.id, self.reason
48
        )
49
    }
50
}
51

            
52
#[derive(Debug, Default)]
53
pub struct Report {
54
    pub tenants: usize,
55
    pub transactions: usize,
56
    pub templates: usize,
57
    pub problems: Vec<Problem>,
58
}
59

            
60
impl Report {
61
    #[must_use]
62
    pub fn summary(&self) -> String {
63
        format!(
64
            "{} tenants, {} transactions, {} templates checked: {} problems",
65
            self.tenants,
66
            self.transactions,
67
            self.templates,
68
            self.problems.len()
69
        )
70
    }
71

            
72
    fn absorb(&mut self, other: Self) {
73
        self.tenants += other.tenants;
74
        self.transactions += other.transactions;
75
        self.templates += other.templates;
76
        self.problems.extend(other.problems);
77
    }
78
}
79

            
80
3
fn problem(user: Uuid, subject: Subject, id: Uuid, reason: impl fmt::Display) -> Problem {
81
3
    Problem {
82
3
        user,
83
3
        subject,
84
3
        id,
85
3
        reason: format!("{reason:#}"),
86
3
    }
87
3
}
88

            
89
/// What a save must not change: the date, the transaction tags with the note
90
/// and, per leg, account, commodity, value and tags, as sorted lines.
91
10
pub(crate) async fn content(user: Uuid, id: Uuid) -> Result<Vec<String>, String> {
92
10
    let snapshot = User { id: user }
93
10
        .transaction_snapshot(id)
94
10
        .await
95
        .map_err(|err| err.to_string())?
96
10
        .ok_or("the transaction vanished")?;
97
10
    let mut lines = vec![format!("date {:?}", snapshot.transaction.post_date)];
98
10
    lines.extend(snapshot.tags.iter().map(tag_line));
99
28
    lines.extend(snapshot.splits.iter().map(|split| {
100
28
        let no_tags = Vec::new();
101
28
        let mut tags: Vec<String> = snapshot
102
28
            .split_tags
103
28
            .get(&split.id)
104
28
            .unwrap_or(&no_tags)
105
28
            .iter()
106
28
            .map(tag_line)
107
28
            .collect();
108
28
        tags.sort();
109
28
        format!(
110
28
            "leg {} {} {}/{} {tags:?}",
111
28
            split.account_id, split.commodity_id, split.value_num, split.value_denom
112
        )
113
28
    }));
114
10
    lines.sort();
115
10
    Ok(lines)
116
10
}
117

            
118
12
fn tag_line(tag: &finance::tag::Tag) -> String {
119
12
    format!("tag {:?}", (&tag.tag_name, &tag.tag_value))
120
12
}
121

            
122
/// Load the transaction into the form, save it unchanged and require the
123
/// stored content to stay the same.
124
5
async fn check_transaction(user: Uuid, id: Uuid) -> Result<(), Problem> {
125
2
    let fail = |reason: &dyn fmt::Display| problem(user, Subject::Transaction, id, reason);
126
5
    let payload = load_form(user, EDIT, &id.to_string())
127
5
        .await
128
2
        .map_err(|err| fail(&err))?;
129
3
    let before = content(user, id).await.map_err(|err| fail(&err))?;
130
3
    submit_form(user, EDIT, &payload)
131
3
        .await
132
        .map_err(|err| fail(&err))?;
133
3
    let after = content(user, id).await.map_err(|err| fail(&err))?;
134
3
    match before == after {
135
3
        true => Ok(()),
136
        false => Err(fail(&"an unchanged save changed the stored content")),
137
    }
138
5
}
139

            
140
2
async fn check_template(user: Uuid, id: Uuid) -> Result<(), Problem> {
141
2
    load_form(user, CREATE, &id.to_string())
142
2
        .await
143
2
        .map(drop)
144
1
        .map_err(|reason| problem(user, Subject::Template, id, reason))
145
2
}
146

            
147
/// Check every transaction and template of one tenant.
148
5
pub async fn check_tenant(user: Uuid) -> Report {
149
5
    let mut report = Report {
150
5
        tenants: 1,
151
5
        ..Report::default()
152
5
    };
153
5
    let account = User { id: user };
154
5
    match account.transaction_ids().await {
155
        Ok(ids) => {
156
5
            report.transactions = ids.len();
157
5
            for id in ids {
158
5
                report
159
5
                    .problems
160
5
                    .extend(check_transaction(user, id).await.err());
161
            }
162
        }
163
        Err(err) => report
164
            .problems
165
            .push(problem(user, Subject::Tenant, user, err)),
166
    }
167
5
    match account.list_templates().await {
168
        Ok(templates) => {
169
5
            report.templates = templates.len();
170
5
            for template in templates {
171
2
                report
172
2
                    .problems
173
2
                    .extend(check_template(user, template.id).await.err());
174
            }
175
        }
176
        Err(err) => report
177
            .problems
178
            .push(problem(user, Subject::Tenant, user, err)),
179
    }
180
5
    report
181
5
}
182

            
183
/// Check every tenant of the directory except the admin.
184
///
185
/// # Errors
186
/// [`DBError`] when the directory cannot be listed.
187
pub async fn check_forms(admin: Uuid) -> Result<Report, DBError> {
188
    let mut report = Report::default();
189
    for user in tenants(admin).await? {
190
        report.absorb(check_tenant(user).await);
191
    }
192
    Ok(report)
193
}