1
//! Hidden row data of `transaction-edit`: what a client carries from load to
2
//! submit untouched. Names and values only, never split, price or tag ids,
3
//! and never tags: those travel in `split-tags`.
4

            
5
use chrono::{DateTime, SecondsFormat, Utc};
6
use forms::{escape_str, parse_date};
7
use nomiscript::{Expr, Reader};
8
use num_rational::Rational64;
9
use server::logical::LogicalSplit;
10
use uuid::Uuid;
11

            
12
use super::transaction_rows::parse_rational;
13
use crate::plist::{expect_plist, take_plist_string};
14
use crate::resolve::{Directory, ResolvedIds, RowKeys};
15

            
16
const KEYS: [&str; 9] = [
17
    "from-id",
18
    "to-id",
19
    "from-commodity-id",
20
    "to-commodity-id",
21
    "value",
22
    "to-amount",
23
    "price-date",
24
    "from-reconcile",
25
    "to-reconcile",
26
];
27

            
28
#[derive(Debug, Clone)]
29
pub(super) struct Hidden {
30
    pub(super) ids: ResolvedIds,
31
    pub(super) value: Rational64,
32
    pub(super) to_amount: Option<Rational64>,
33
    pub(super) price_date: Option<DateTime<Utc>>,
34
    /// Stored reconcile states of the from and to splits.
35
    pub(super) reconcile: [Option<bool>; 2],
36
}
37

            
38
/// The wire token of an amount: `n` or `n/d`.
39
23973
fn amount_text(value: Rational64) -> String {
40
23973
    amount::wire_rational(value)
41
23973
}
42

            
43
34934
fn required(plist: &[(String, Expr)], key: &str) -> Result<String, String> {
44
34934
    take_plist_string(plist, key)?.ok_or_else(|| format!("hidden: missing :{key}"))
45
34934
}
46

            
47
/// Name-carrying keys of forms loaded before ids replaced names.
48
const LABEL_KEYS: [&str; 4] = [
49
    "from-label",
50
    "to-label",
51
    "from-commodity-label",
52
    "to-commodity-label",
53
];
54

            
55
34934
fn uuid(plist: &[(String, Expr)], key: &str) -> Result<Uuid, String> {
56
34934
    let text = required(plist, key)?;
57
34934
    Uuid::parse_str(&text).map_err(|_| format!("hidden: :{key} is not an id"))
58
34934
}
59

            
60
17464
fn amount(plist: &[(String, Expr)], key: &str) -> Result<Option<Rational64>, String> {
61
17464
    take_plist_string(plist, key)?
62
13390
        .map(|text| parse_rational(&text).map_err(|err| format!("hidden: :{key} {err}")))
63
        .transpose()
64
17464
}
65

            
66
/// Only a known-unreconciled split is ever carried, written as `"false"`.
67
17462
fn reconcile(plist: &[(String, Expr)], key: &str) -> Result<Option<bool>, String> {
68
17462
    match take_plist_string(plist, key)?.as_deref() {
69
11694
        None => Ok(None),
70
5768
        Some("false") => Ok(Some(false)),
71
        Some(_) => Err(format!("hidden: :{key} must be \"false\"")),
72
    }
73
17462
}
74

            
75
impl Hidden {
76
9077
    pub(super) fn parse(text: &str) -> Result<Self, String> {
77
9077
        let program = Reader::parse(text).map_err(|err| format!("hidden parse: {err}"))?;
78
9075
        let [expr] = <[Expr; 1]>::try_from(program.exprs)
79
2
            .map_err(|_| "hidden: expected one list".to_string())?;
80
9073
        let plist = expect_plist(expr, "hidden")?;
81
9071
        if plist
82
9071
            .iter()
83
62081
            .any(|(key, _)| key.eq_ignore_ascii_case("tags"))
84
        {
85
5
            return Err(
86
5
                "hidden: :tags is no longer carried; split tags travel in split-tags, \
87
5
                 so this client must be updated"
88
5
                    .to_string(),
89
5
            );
90
9066
        }
91
60428
        if plist.iter().any(|(key, _)| {
92
60428
            LABEL_KEYS
93
60428
                .iter()
94
240743
                .any(|label| label.eq_ignore_ascii_case(key))
95
60428
        }) {
96
325
            return Err(
97
325
                "hidden: this form was loaded by an old client; reload the form".to_string(),
98
325
            );
99
8741
        }
100
8741
        if let Some((key, _)) = plist
101
8741
            .iter()
102
240780
            .find(|(key, _)| !KEYS.iter().any(|known| known.eq_ignore_ascii_case(key)))
103
        {
104
4
            return Err(format!("hidden: unexpected :{key}"));
105
8737
        }
106
8737
        let price_date = take_plist_string(&plist, "price-date")?
107
4661
            .map(|text| {
108
4661
                parse_date(&text, false).map_err(|err| format!("hidden: :price-date {err}"))
109
4661
            })
110
2
            .transpose()?;
111
        Ok(Self {
112
            ids: ResolvedIds {
113
8735
                from: uuid(&plist, "from-id")?,
114
8733
                to: uuid(&plist, "to-id")?,
115
8733
                from_commodity: uuid(&plist, "from-commodity-id")?,
116
8733
                to_commodity: uuid(&plist, "to-commodity-id")?,
117
            },
118
8733
            value: amount(&plist, "value")?.ok_or("hidden: missing :value")?,
119
8731
            to_amount: amount(&plist, "to-amount")?,
120
8731
            price_date,
121
            reconcile: [
122
8731
                reconcile(&plist, "from-reconcile")?,
123
8731
                reconcile(&plist, "to-reconcile")?,
124
            ],
125
        })
126
9077
    }
127

            
128
15475
    pub(super) fn to_sexpr(&self) -> String {
129
15475
        let mut items = vec![
130
15475
            format!(":from-id {}", escape_str(&self.ids.from.to_string())),
131
15475
            format!(":to-id {}", escape_str(&self.ids.to.to_string())),
132
15475
            format!(
133
                ":from-commodity-id {}",
134
15475
                escape_str(&self.ids.from_commodity.to_string())
135
            ),
136
15475
            format!(
137
                ":to-commodity-id {}",
138
15475
                escape_str(&self.ids.to_commodity.to_string())
139
            ),
140
15475
            format!(":value {}", escape_str(&amount_text(self.value))),
141
        ];
142
15475
        items.extend(
143
15475
            self.to_amount
144
8498
                .map(|value| format!(":to-amount {}", escape_str(&amount_text(value)))),
145
        );
146
15475
        items.extend(self.price_date.map(|date| {
147
8498
            let date = date.to_rfc3339_opts(SecondsFormat::AutoSi, true);
148
8498
            format!(":price-date {}", escape_str(&date))
149
8498
        }));
150
15475
        for (key, state) in ["from-reconcile", "to-reconcile"]
151
15475
            .into_iter()
152
15475
            .zip(self.reconcile)
153
        {
154
30950
            items.extend(state.map(|_| format!(":{key} \"false\"")));
155
        }
156
15475
        format!("({})", items.join(" "))
157
15475
    }
158

            
159
    /// Every hidden id must be one of the user's own entities.
160
8560
    pub(super) fn verify(&self, directory: &Directory) -> Result<(), String> {
161
8560
        let (from, to) = (self.ids.from.to_string(), self.ids.to.to_string());
162
8560
        let (from_commodity, to_commodity) = (
163
8560
            self.ids.from_commodity.to_string(),
164
8560
            self.ids.to_commodity.to_string(),
165
8560
        );
166
8560
        let keys = RowKeys {
167
8560
            from: &from,
168
8560
            to: &to,
169
8560
            from_commodity: &from_commodity,
170
8560
            to_commodity: Some(&to_commodity),
171
8560
        };
172
8560
        match directory.resolve_row(&keys) {
173
8558
            Ok(ids) if ids == self.ids => Ok(()),
174
            Ok(_) => Err("hidden: ids are not the user's own".to_string()),
175
2
            Err(faults) => Err(format!(
176
                "hidden: {}",
177
2
                faults
178
2
                    .iter()
179
2
                    .map(|(_, err)| err.to_string())
180
                    .collect::<Vec<_>>()
181
2
                    .join("; ")
182
            )),
183
        }
184
8560
    }
185

            
186
    /// The same commodity pair, value and to-amount as loaded.
187
8396
    pub(super) fn unchanged(&self, split: &LogicalSplit) -> bool {
188
8396
        self.ids.from_commodity == split.from_commodity
189
8396
            && self.ids.to_commodity == split.to_commodity
190
8395
            && self.value == split.value
191
8234
            && self.to_amount == split.to_amount
192
8396
    }
193
}