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

            
5
use std::collections::HashMap;
6

            
7
use finance::{price::Price, split::Split, tag::Tag};
8
use sqlx::types::Uuid;
9

            
10
use super::{ensure_single_line_names, is_note, raise_transaction};
11
use crate::command::CmdError;
12

            
13
1980
fn reason(err: CmdError) -> String {
14
1980
    match err {
15
1980
        CmdError::Args(reason) => reason,
16
        other => other.to_string(),
17
    }
18
1980
}
19

            
20
179295
fn sorted(tags: &[Tag]) -> Vec<&Tag> {
21
179295
    let mut sorted: Vec<&Tag> = tags.iter().collect();
22
179295
    sorted.sort_by_key(|tag| tag.normalized());
23
179295
    sorted
24
179295
}
25

            
26
179295
fn ensure_one_value_per_name(owner: &str, tags: &[Tag]) -> Result<(), String> {
27
179295
    let repeated = sorted(tags).windows(2).find_map(|pair| match pair {
28
54724
        [first, second] if first.normalized().0 == second.normalized().0 => {
29
541
            Some(first.normalized().0.to_string())
30
        }
31
54183
        _ => None,
32
54724
    });
33
179295
    match repeated {
34
541
        Some(name) => Err(format!(
35
541
            "{owner} holds two values for the tag '{name}'; the form keeps one value per name"
36
541
        )),
37
178754
        None => Ok(()),
38
    }
39
179295
}
40

            
41
50768
fn ensure_keepable_tags(tags: &[Tag]) -> Result<(), String> {
42
94150
    if tags.iter().filter(|tag| is_note(tag)).count() > 1 {
43
361
        return Err("the transaction holds two notes; the form keeps one".to_string());
44
50407
    }
45
50407
    ensure_one_value_per_name("the transaction", tags)?;
46
92166
    let others: Vec<Tag> = tags.iter().filter(|tag| !is_note(tag)).cloned().collect();
47
50046
    ensure_single_line_names(&others)
48
50768
}
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.
57
50768
pub fn form_refusal(
58
50768
    tags: &[Tag],
59
50768
    splits: &[Split],
60
50768
    split_tags: &HashMap<Uuid, Vec<Tag>>,
61
50768
    prices: &[Price],
62
50768
) -> Result<(), String> {
63
50768
    ensure_keepable_tags(tags)?;
64
49866
    for split in splits {
65
128888
        let own = split_tags.get(&split.id).map_or(&[][..], Vec::as_slice);
66
128888
        ensure_one_value_per_name("a split", own)?;
67
128708
        ensure_single_line_names(own)?;
68
    }
69
49506
    raise_transaction(splits, prices).map_err(reason)?;
70
47526
    Ok(())
71
50768
}
72

            
73
#[cfg(test)]
74
#[path = "refusal_tests.rs"]
75
mod tests;