Skip to main content

rpc/
preflight.rs

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
5use std::fmt;
6
7use server::db::DBError;
8use server::preflight::tenants;
9use server::user::User;
10use uuid::Uuid;
11
12use crate::natives::forms::{load_form, submit_form};
13
14const EDIT: &str = "transaction-edit";
15const CREATE: &str = "transaction-create";
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Subject {
19    Tenant,
20    Transaction,
21    Template,
22}
23
24impl 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)]
35pub struct Problem {
36    pub user: Uuid,
37    pub subject: Subject,
38    pub id: Uuid,
39    pub reason: String,
40}
41
42impl 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)]
53pub struct Report {
54    pub tenants: usize,
55    pub transactions: usize,
56    pub templates: usize,
57    pub problems: Vec<Problem>,
58}
59
60impl 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
80fn problem(user: Uuid, subject: Subject, id: Uuid, reason: impl fmt::Display) -> Problem {
81    Problem {
82        user,
83        subject,
84        id,
85        reason: format!("{reason:#}"),
86    }
87}
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.
91pub(crate) async fn content(user: Uuid, id: Uuid) -> Result<Vec<String>, String> {
92    let snapshot = User { id: user }
93        .transaction_snapshot(id)
94        .await
95        .map_err(|err| err.to_string())?
96        .ok_or("the transaction vanished")?;
97    let mut lines = vec![format!("date {:?}", snapshot.transaction.post_date)];
98    lines.extend(snapshot.tags.iter().map(tag_line));
99    lines.extend(snapshot.splits.iter().map(|split| {
100        let no_tags = Vec::new();
101        let mut tags: Vec<String> = snapshot
102            .split_tags
103            .get(&split.id)
104            .unwrap_or(&no_tags)
105            .iter()
106            .map(tag_line)
107            .collect();
108        tags.sort();
109        format!(
110            "leg {} {} {}/{} {tags:?}",
111            split.account_id, split.commodity_id, split.value_num, split.value_denom
112        )
113    }));
114    lines.sort();
115    Ok(lines)
116}
117
118fn tag_line(tag: &finance::tag::Tag) -> String {
119    format!("tag {:?}", (&tag.tag_name, &tag.tag_value))
120}
121
122/// Load the transaction into the form, save it unchanged and require the
123/// stored content to stay the same.
124async fn check_transaction(user: Uuid, id: Uuid) -> Result<(), Problem> {
125    let fail = |reason: &dyn fmt::Display| problem(user, Subject::Transaction, id, reason);
126    let payload = load_form(user, EDIT, &id.to_string())
127        .await
128        .map_err(|err| fail(&err))?;
129    let before = content(user, id).await.map_err(|err| fail(&err))?;
130    submit_form(user, EDIT, &payload)
131        .await
132        .map_err(|err| fail(&err))?;
133    let after = content(user, id).await.map_err(|err| fail(&err))?;
134    match before == after {
135        true => Ok(()),
136        false => Err(fail(&"an unchanged save changed the stored content")),
137    }
138}
139
140async fn check_template(user: Uuid, id: Uuid) -> Result<(), Problem> {
141    load_form(user, CREATE, &id.to_string())
142        .await
143        .map(drop)
144        .map_err(|reason| problem(user, Subject::Template, id, reason))
145}
146
147/// Check every transaction and template of one tenant.
148pub async fn check_tenant(user: Uuid) -> Report {
149    let mut report = Report {
150        tenants: 1,
151        ..Report::default()
152    };
153    let account = User { id: user };
154    match account.transaction_ids().await {
155        Ok(ids) => {
156            report.transactions = ids.len();
157            for id in ids {
158                report
159                    .problems
160                    .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    match account.list_templates().await {
168        Ok(templates) => {
169            report.templates = templates.len();
170            for template in templates {
171                report
172                    .problems
173                    .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    report
181}
182
183/// Check every tenant of the directory except the admin.
184///
185/// # Errors
186/// [`DBError`] when the directory cannot be listed.
187pub 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}