Lines
65.18 %
Functions
27.78 %
Branches
100 %
//! Form preflight: opens every stored transaction and template in the form
//! the way the clients do, and saves each transaction unchanged. The saves
//! commit: run it on a disposable restored copy only.
use std::fmt;
use server::db::DBError;
use server::preflight::tenants;
use server::user::User;
use uuid::Uuid;
use crate::natives::forms::{load_form, submit_form};
const EDIT: &str = "transaction-edit";
const CREATE: &str = "transaction-create";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Subject {
Tenant,
Transaction,
Template,
}
impl fmt::Display for Subject {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Tenant => "tenant",
Self::Transaction => "transaction",
Self::Template => "template",
})
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
pub user: Uuid,
pub subject: Subject,
pub id: Uuid,
pub reason: String,
impl fmt::Display for Problem {
write!(
f,
"user {} {} {}: {}",
self.user, self.subject, self.id, self.reason
)
#[derive(Debug, Default)]
pub struct Report {
pub tenants: usize,
pub transactions: usize,
pub templates: usize,
pub problems: Vec<Problem>,
impl Report {
#[must_use]
pub fn summary(&self) -> String {
format!(
"{} tenants, {} transactions, {} templates checked: {} problems",
self.tenants,
self.transactions,
self.templates,
self.problems.len()
fn absorb(&mut self, other: Self) {
self.tenants += other.tenants;
self.transactions += other.transactions;
self.templates += other.templates;
self.problems.extend(other.problems);
fn problem(user: Uuid, subject: Subject, id: Uuid, reason: impl fmt::Display) -> Problem {
Problem {
user,
subject,
id,
reason: format!("{reason:#}"),
/// What a save must not change: the date, the transaction tags with the note
/// and, per leg, account, commodity, value and tags, as sorted lines.
pub(crate) async fn content(user: Uuid, id: Uuid) -> Result<Vec<String>, String> {
let snapshot = User { id: user }
.transaction_snapshot(id)
.await
.map_err(|err| err.to_string())?
.ok_or("the transaction vanished")?;
let mut lines = vec![format!("date {:?}", snapshot.transaction.post_date)];
lines.extend(snapshot.tags.iter().map(tag_line));
lines.extend(snapshot.splits.iter().map(|split| {
let no_tags = Vec::new();
let mut tags: Vec<String> = snapshot
.split_tags
.get(&split.id)
.unwrap_or(&no_tags)
.iter()
.map(tag_line)
.collect();
tags.sort();
"leg {} {} {}/{} {tags:?}",
split.account_id, split.commodity_id, split.value_num, split.value_denom
}));
lines.sort();
Ok(lines)
fn tag_line(tag: &finance::tag::Tag) -> String {
format!("tag {:?}", (&tag.tag_name, &tag.tag_value))
/// Load the transaction into the form, save it unchanged and require the
/// stored content to stay the same.
async fn check_transaction(user: Uuid, id: Uuid) -> Result<(), Problem> {
let fail = |reason: &dyn fmt::Display| problem(user, Subject::Transaction, id, reason);
let payload = load_form(user, EDIT, &id.to_string())
.map_err(|err| fail(&err))?;
let before = content(user, id).await.map_err(|err| fail(&err))?;
submit_form(user, EDIT, &payload)
let after = content(user, id).await.map_err(|err| fail(&err))?;
match before == after {
true => Ok(()),
false => Err(fail(&"an unchanged save changed the stored content")),
async fn check_template(user: Uuid, id: Uuid) -> Result<(), Problem> {
load_form(user, CREATE, &id.to_string())
.map(drop)
.map_err(|reason| problem(user, Subject::Template, id, reason))
/// Check every transaction and template of one tenant.
pub async fn check_tenant(user: Uuid) -> Report {
let mut report = Report {
tenants: 1,
..Report::default()
};
let account = User { id: user };
match account.transaction_ids().await {
Ok(ids) => {
report.transactions = ids.len();
for id in ids {
report
.problems
.extend(check_transaction(user, id).await.err());
Err(err) => report
.push(problem(user, Subject::Tenant, user, err)),
match account.list_templates().await {
Ok(templates) => {
report.templates = templates.len();
for template in templates {
.extend(check_template(user, template.id).await.err());
/// Check every tenant of the directory except the admin.
///
/// # Errors
/// [`DBError`] when the directory cannot be listed.
pub async fn check_forms(admin: Uuid) -> Result<Report, DBError> {
let mut report = Report::default();
for user in tenants(admin).await? {
report.absorb(check_tenant(user).await);
Ok(report)