server/logical/
revision.rs1use std::collections::HashMap;
5use std::fmt::Write;
6
7use chrono::{DateTime, Utc};
8use finance::price::Price;
9use finance::split::Split;
10use finance::tag::Tag;
11use sha2::{Digest, Sha256};
12use sqlx::types::Uuid;
13
14use super::note::{is_note, pick_note};
15
16pub const STALE_REVISION: &str = "the transaction changed since it was loaded; reload it";
18
19fn tag_text(tag: &Tag) -> String {
20 format!("{:?}", (&tag.tag_name, &tag.tag_value, &tag.description))
21}
22
23fn split_line(split: &Split, tags: &[Tag]) -> String {
24 let mut tags: Vec<String> = tags.iter().map(tag_text).collect();
25 tags.sort();
26 format!(
27 "split {} {} {} {}/{} {:?} {:?} {:?} {tags:?}",
28 split.id,
29 split.account_id,
30 split.commodity_id,
31 split.value_num,
32 split.value_denom,
33 split.reconcile_state,
34 split.reconcile_date,
35 split.lot_id
36 )
37}
38
39fn price_line(price: &Price) -> String {
40 format!(
41 "price {} {} {:?} {:?} {}/{} {:?}",
42 price.commodity_id,
43 price.currency_id,
44 price.commodity_split,
45 price.currency_split,
46 price.value_num,
47 price.value_denom,
48 price.date
49 )
50}
51
52#[must_use]
55pub(crate) fn revision(
56 post_date: DateTime<Utc>,
57 note: Option<&str>,
58 tags: &[Tag],
59 splits: &[Split],
60 split_tags: &HashMap<Uuid, Vec<Tag>>,
61 prices: &[Price],
62) -> String {
63 let mut lines = vec![format!("date {post_date:?}"), format!("note {note:?}")];
64 lines.extend(tags.iter().map(|tag| format!("tag {}", tag_text(tag))));
65 lines.extend(
66 splits
67 .iter()
68 .map(|split| split_line(split, split_tags.get(&split.id).map_or(&[], Vec::as_slice))),
69 );
70 lines.extend(prices.iter().map(price_line));
71 hex_digest(lines)
72}
73
74pub(crate) fn hex_digest(mut lines: Vec<String>) -> String {
76 lines.sort();
77 let digest = Sha256::digest(lines.join("\n").as_bytes());
78 digest.iter().fold(String::new(), |mut hex, byte| {
79 let _ = write!(hex, "{byte:02x}");
80 hex
81 })
82}
83
84#[must_use]
87pub fn stored_revision(
88 post_date: DateTime<Utc>,
89 tags: Vec<Tag>,
90 splits: &[Split],
91 split_tags: &HashMap<Uuid, Vec<Tag>>,
92 prices: &[Price],
93) -> String {
94 let note = pick_note(tags.iter()).map(|tag| tag.tag_value.clone());
95 let others: Vec<Tag> = tags.into_iter().filter(|tag| !is_note(tag)).collect();
96 revision(
97 post_date,
98 note.as_deref(),
99 &others,
100 splits,
101 split_tags,
102 prices,
103 )
104}
105
106#[cfg(test)]
107#[path = "revision_tests.rs"]
108mod tests;