Lines
100 %
Functions
Branches
//! Digest of everything a logical edit replaces, so a form loaded earlier is
//! refused when the stored transaction changed in between.
use std::collections::HashMap;
use std::fmt::Write;
use chrono::{DateTime, Utc};
use finance::price::Price;
use finance::split::Split;
use finance::tag::Tag;
use sha2::{Digest, Sha256};
use sqlx::types::Uuid;
use super::note::{is_note, pick_note};
/// The error text of an update whose expected revision no longer matches.
pub const STALE_REVISION: &str = "the transaction changed since it was loaded; reload it";
fn tag_text(tag: &Tag) -> String {
format!("{:?}", (&tag.tag_name, &tag.tag_value, &tag.description))
}
fn split_line(split: &Split, tags: &[Tag]) -> String {
let mut tags: Vec<String> = tags.iter().map(tag_text).collect();
tags.sort();
format!(
"split {} {} {} {}/{} {:?} {:?} {:?} {tags:?}",
split.id,
split.account_id,
split.commodity_id,
split.value_num,
split.value_denom,
split.reconcile_state,
split.reconcile_date,
split.lot_id
)
fn price_line(price: &Price) -> String {
"price {} {} {:?} {:?} {}/{} {:?}",
price.commodity_id,
price.currency_id,
price.commodity_split,
price.currency_split,
price.value_num,
price.value_denom,
price.date
/// Order-independent sha256 hex of the post date, note, the other
/// transaction tags, splits with their reconciliation, lot and tags, and prices.
#[must_use]
pub(crate) fn revision(
post_date: DateTime<Utc>,
note: Option<&str>,
tags: &[Tag],
splits: &[Split],
split_tags: &HashMap<Uuid, Vec<Tag>>,
prices: &[Price],
) -> String {
let mut lines = vec![format!("date {post_date:?}"), format!("note {note:?}")];
lines.extend(tags.iter().map(|tag| format!("tag {}", tag_text(tag))));
lines.extend(
splits
.iter()
.map(|split| split_line(split, split_tags.get(&split.id).map_or(&[], Vec::as_slice))),
);
lines.extend(prices.iter().map(price_line));
hex_digest(lines)
/// Order-independent sha256 hex of `lines`.
pub(crate) fn hex_digest(mut lines: Vec<String>) -> String {
lines.sort();
let digest = Sha256::digest(lines.join("\n").as_bytes());
digest.iter().fold(String::new(), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
})
/// `revision` of the stored transaction tags as loaded, the note among
/// them; the last note in `tags` wins, as `GetTransactionDetail` shows it.
pub fn stored_revision(
tags: Vec<Tag>,
let note = pick_note(tags.iter()).map(|tag| tag.tag_value.clone());
let others: Vec<Tag> = tags.into_iter().filter(|tag| !is_note(tag)).collect();
revision(
post_date,
note.as_deref(),
&others,
splits,
split_tags,
prices,
#[cfg(test)]
#[path = "revision_tests.rs"]
mod tests;