Lines
97.73 %
Functions
94.44 %
Branches
100 %
//! What the logical form cannot keep of a stored transaction: the single
//! source of every refusal, applied when a form loads and under the row lock
//! of a form write.
use std::collections::HashMap;
use finance::{price::Price, split::Split, tag::Tag};
use sqlx::types::Uuid;
use super::{ensure_single_line_names, is_note, raise_transaction};
use crate::command::CmdError;
fn reason(err: CmdError) -> String {
match err {
CmdError::Args(reason) => reason,
other => other.to_string(),
}
fn sorted(tags: &[Tag]) -> Vec<&Tag> {
let mut sorted: Vec<&Tag> = tags.iter().collect();
sorted.sort_by_key(|tag| tag.normalized());
sorted
fn ensure_one_value_per_name(owner: &str, tags: &[Tag]) -> Result<(), String> {
let repeated = sorted(tags).windows(2).find_map(|pair| match pair {
[first, second] if first.normalized().0 == second.normalized().0 => {
Some(first.normalized().0.to_string())
_ => None,
});
match repeated {
Some(name) => Err(format!(
"{owner} holds two values for the tag '{name}'; the form keeps one value per name"
)),
None => Ok(()),
fn ensure_keepable_tags(tags: &[Tag]) -> Result<(), String> {
if tags.iter().filter(|tag| is_note(tag)).count() > 1 {
return Err("the transaction holds two notes; the form keeps one".to_string());
ensure_one_value_per_name("the transaction", tags)?;
let others: Vec<Tag> = tags.iter().filter(|tag| !is_note(tag)).cloned().collect();
ensure_single_line_names(&others)
/// `Ok` when the stored transaction round-trips through the logical form,
/// else the reason it does not: reconciliation or lot data, an ambiguous
/// pairing, an exchange rate off its splits, two notes, two values of one
/// tag name, or a line break in a tag name or value.
///
/// # Errors
/// The reason the transaction cannot be kept.
pub fn form_refusal(
tags: &[Tag],
splits: &[Split],
split_tags: &HashMap<Uuid, Vec<Tag>>,
prices: &[Price],
) -> Result<(), String> {
ensure_keepable_tags(tags)?;
for split in splits {
let own = split_tags.get(&split.id).map_or(&[][..], Vec::as_slice);
ensure_one_value_per_name("a split", own)?;
ensure_single_line_names(own)?;
raise_transaction(splits, prices).map_err(reason)?;
Ok(())
#[cfg(test)]
#[path = "refusal_tests.rs"]
mod tests;