1
//! Digest of everything a logical edit replaces, so a form loaded earlier is
2
//! refused when the stored transaction changed in between.
3

            
4
use std::collections::HashMap;
5
use std::fmt::Write;
6

            
7
use chrono::{DateTime, Utc};
8
use finance::price::Price;
9
use finance::split::Split;
10
use finance::tag::Tag;
11
use sha2::{Digest, Sha256};
12
use sqlx::types::Uuid;
13

            
14
use super::note::{is_note, pick_note};
15

            
16
/// The error text of an update whose expected revision no longer matches.
17
pub const STALE_REVISION: &str = "the transaction changed since it was loaded; reload it";
18

            
19
116390
fn tag_text(tag: &Tag) -> String {
20
116390
    format!("{:?}", (&tag.tag_name, &tag.tag_value, &tag.description))
21
116390
}
22

            
23
137734
fn split_line(split: &Split, tags: &[Tag]) -> String {
24
137734
    let mut tags: Vec<String> = tags.iter().map(tag_text).collect();
25
137734
    tags.sort();
26
137734
    format!(
27
137734
        "split {} {} {} {}/{} {:?} {:?} {:?} {tags:?}",
28
137734
        split.id,
29
137734
        split.account_id,
30
137734
        split.commodity_id,
31
137734
        split.value_num,
32
137734
        split.value_denom,
33
137734
        split.reconcile_state,
34
137734
        split.reconcile_date,
35
137734
        split.lot_id
36
    )
37
137734
}
38

            
39
19906
fn price_line(price: &Price) -> String {
40
19906
    format!(
41
        "price {} {} {:?} {:?} {}/{} {:?}",
42
19906
        price.commodity_id,
43
19906
        price.currency_id,
44
19906
        price.commodity_split,
45
19906
        price.currency_split,
46
19906
        price.value_num,
47
19906
        price.value_denom,
48
19906
        price.date
49
    )
50
19906
}
51

            
52
/// Order-independent sha256 hex of the post date, note, the other
53
/// transaction tags, splits with their reconciliation, lot and tags, and prices.
54
#[must_use]
55
54328
pub(crate) fn revision(
56
54328
    post_date: DateTime<Utc>,
57
54328
    note: Option<&str>,
58
54328
    tags: &[Tag],
59
54328
    splits: &[Split],
60
54328
    split_tags: &HashMap<Uuid, Vec<Tag>>,
61
54328
    prices: &[Price],
62
54328
) -> String {
63
54328
    let mut lines = vec![format!("date {post_date:?}"), format!("note {note:?}")];
64
54554
    lines.extend(tags.iter().map(|tag| format!("tag {}", tag_text(tag))));
65
54328
    lines.extend(
66
54328
        splits
67
54328
            .iter()
68
137734
            .map(|split| split_line(split, split_tags.get(&split.id).map_or(&[], Vec::as_slice))),
69
    );
70
54328
    lines.extend(prices.iter().map(price_line));
71
54328
    hex_digest(lines)
72
54328
}
73

            
74
/// Order-independent sha256 hex of `lines`.
75
105070
pub(crate) fn hex_digest(mut lines: Vec<String>) -> String {
76
105070
    lines.sort();
77
105070
    let digest = Sha256::digest(lines.join("\n").as_bytes());
78
3362240
    digest.iter().fold(String::new(), |mut hex, byte| {
79
3362240
        let _ = write!(hex, "{byte:02x}");
80
3362240
        hex
81
3362240
    })
82
105070
}
83

            
84
/// `revision` of the stored transaction tags as loaded, the note among
85
/// them; the last note in `tags` wins, as `GetTransactionDetail` shows it.
86
#[must_use]
87
54300
pub fn stored_revision(
88
54300
    post_date: DateTime<Utc>,
89
54300
    tags: Vec<Tag>,
90
54300
    splits: &[Split],
91
54300
    split_tags: &HashMap<Uuid, Vec<Tag>>,
92
54300
    prices: &[Price],
93
54300
) -> String {
94
54300
    let note = pick_note(tags.iter()).map(|tag| tag.tag_value.clone());
95
97422
    let others: Vec<Tag> = tags.into_iter().filter(|tag| !is_note(tag)).collect();
96
54300
    revision(
97
54300
        post_date,
98
54300
        note.as_deref(),
99
54300
        &others,
100
54300
        splits,
101
54300
        split_tags,
102
54300
        prices,
103
54300
    )
104
54300
}
105

            
106
#[cfg(test)]
107
#[path = "revision_tests.rs"]
108
mod tests;