Skip to main content

server/logical/
refusal.rs

1//! What the logical form cannot keep of a stored transaction: the single
2//! source of every refusal, applied when a form loads and under the row lock
3//! of a form write.
4
5use std::collections::HashMap;
6
7use finance::{price::Price, split::Split, tag::Tag};
8use sqlx::types::Uuid;
9
10use super::{ensure_single_line_names, is_note, raise_transaction};
11use crate::command::CmdError;
12
13fn reason(err: CmdError) -> String {
14    match err {
15        CmdError::Args(reason) => reason,
16        other => other.to_string(),
17    }
18}
19
20fn sorted(tags: &[Tag]) -> Vec<&Tag> {
21    let mut sorted: Vec<&Tag> = tags.iter().collect();
22    sorted.sort_by_key(|tag| tag.normalized());
23    sorted
24}
25
26fn ensure_one_value_per_name(owner: &str, tags: &[Tag]) -> Result<(), String> {
27    let repeated = sorted(tags).windows(2).find_map(|pair| match pair {
28        [first, second] if first.normalized().0 == second.normalized().0 => {
29            Some(first.normalized().0.to_string())
30        }
31        _ => None,
32    });
33    match repeated {
34        Some(name) => Err(format!(
35            "{owner} holds two values for the tag '{name}'; the form keeps one value per name"
36        )),
37        None => Ok(()),
38    }
39}
40
41fn ensure_keepable_tags(tags: &[Tag]) -> Result<(), String> {
42    if tags.iter().filter(|tag| is_note(tag)).count() > 1 {
43        return Err("the transaction holds two notes; the form keeps one".to_string());
44    }
45    ensure_one_value_per_name("the transaction", tags)?;
46    let others: Vec<Tag> = tags.iter().filter(|tag| !is_note(tag)).cloned().collect();
47    ensure_single_line_names(&others)
48}
49
50/// `Ok` when the stored transaction round-trips through the logical form,
51/// else the reason it does not: reconciliation or lot data, an ambiguous
52/// pairing, an exchange rate off its splits, two notes, two values of one
53/// tag name, or a line break in a tag name or value.
54///
55/// # Errors
56/// The reason the transaction cannot be kept.
57pub fn form_refusal(
58    tags: &[Tag],
59    splits: &[Split],
60    split_tags: &HashMap<Uuid, Vec<Tag>>,
61    prices: &[Price],
62) -> Result<(), String> {
63    ensure_keepable_tags(tags)?;
64    for split in splits {
65        let own = split_tags.get(&split.id).map_or(&[][..], Vec::as_slice);
66        ensure_one_value_per_name("a split", own)?;
67        ensure_single_line_names(own)?;
68    }
69    raise_transaction(splits, prices).map_err(reason)?;
70    Ok(())
71}
72
73#[cfg(test)]
74#[path = "refusal_tests.rs"]
75mod tests;