1
//! `load-form "transaction-create"`: a template's draft as create values.
2

            
3
use chrono::SecondsFormat;
4
use forms::{FormValues, Row, parse_post_date};
5
use num_rational::Rational64;
6
use server::logical::RowTags;
7
use server::user::User;
8
use uuid::Uuid;
9

            
10
use super::transaction_rows::to_commodity_cell;
11
use super::transaction_split_tags::split_tag_rows;
12
use super::{Entity, Failure};
13
use crate::ScriptCtx;
14
use crate::draft::{DraftSplit, DraftTag, TransactionDraft};
15
use crate::host_failure::unavailable_condition;
16
use crate::template::{TemplateError, render_template};
17

            
18
const CTX: &str = "load-form";
19

            
20
3854
pub(super) async fn load_transaction_create(
21
3854
    user_id: Uuid,
22
3854
    id: &str,
23
3854
) -> Result<FormValues, Failure> {
24
3854
    let template_id = Uuid::parse_str(id.trim()).map_err(|_| Failure::MalformedId {
25
1
        entity: Entity::Template,
26
1
        id: id.to_string(),
27
1
    })?;
28
3853
    let detail = User { id: user_id }
29
3853
        .find_template(template_id)
30
3853
        .await
31
        .map_err(|err| Failure::Internal(wasmtime::Error::msg(format!("{CTX}: {err}"))))?
32
3853
        .ok_or(Failure::Missing(Entity::Template))?;
33
3531
    let draft = render_template(&ScriptCtx::new(user_id), &detail.source_text)
34
3531
        .await
35
3531
        .map_err(render_failure)?;
36
3370
    template_values(&draft)
37
3854
}
38

            
39
161
fn render_failure(err: TemplateError) -> Failure {
40
161
    if let TemplateError::Unavailable(message) = err {
41
        return Failure::Internal(unavailable_condition(message));
42
161
    }
43
161
    match err.is_internal() {
44
        true => Failure::Internal(wasmtime::Error::msg(format!("{CTX}: {err}"))),
45
161
        false => Failure::Refused(err.to_string()),
46
    }
47
161
}
48

            
49
1449
fn refused(reason: impl Into<String>) -> Failure {
50
1449
    Failure::Refused(reason.into())
51
1449
}
52

            
53
7704
fn exact(num: i64, denom: i64) -> Option<Rational64> {
54
7704
    (denom != 0 && num != i64::MIN && denom != i64::MIN).then(|| Rational64::new(num, denom))
55
7704
}
56

            
57
5454
fn tag_row(tag: &DraftTag) -> Row {
58
5454
    Row::from([
59
5454
        ("name".to_string(), tag.name.clone()),
60
5454
        ("value".to_string(), tag.value.clone()),
61
5454
    ])
62
5454
}
63

            
64
7704
fn amount_of(split: &DraftSplit, position: usize) -> Result<Rational64, Failure> {
65
7704
    exact(split.value_num, split.value_denom)
66
        .ok_or_else(|| refused(format!("split {position} has an invalid amount")))
67
7704
}
68

            
69
/// One form row of a debit leg followed by its credit leg.
70
3852
fn pair_row(pair: &[DraftSplit; 2], index: usize) -> Result<Row, Failure> {
71
3852
    let [from, to] = pair;
72
3852
    let (out, into) = (amount_of(from, 2 * index)?, amount_of(to, 2 * index + 1)?);
73
3852
    if out >= Rational64::from_integer(0) || into < Rational64::from_integer(0) {
74
2
        return Err(refused(format!(
75
2
            "splits {} and {} are not a debit followed by a credit",
76
2
            2 * index,
77
2
            2 * index + 1
78
2
        )));
79
3850
    }
80
3850
    let value = -out;
81
3850
    let mut row = Row::from([
82
3850
        ("key".to_string(), format!("n{}", index + 1)),
83
3850
        ("from".to_string(), from.account_id.clone()),
84
3850
        ("to".to_string(), to.account_id.clone()),
85
3850
        ("from-commodity".to_string(), from.commodity_id.clone()),
86
3850
        (
87
3850
            "to-commodity".to_string(),
88
3850
            to_commodity_cell(&from.commodity_id, &to.commodity_id),
89
3850
        ),
90
3850
        ("value".to_string(), amount::wire_rational(value)),
91
3850
    ]);
92
3850
    match from.commodity_id == to.commodity_id {
93
3849
        true if value != into => {
94
2
            return Err(refused(format!(
95
2
                "splits {} and {} are in one commodity but differ in amount",
96
2
                2 * index,
97
2
                2 * index + 1
98
2
            )));
99
        }
100
3847
        true => {}
101
        false => {
102
1
            row.insert("to-amount".to_string(), amount::wire_rational(into));
103
        }
104
    }
105
3848
    Ok(row)
106
3852
}
107

            
108
/// The create values a rendered template stands for.
109
///
110
/// # Errors
111
/// [`Failure::Refused`] when the draft cannot be shown as form rows exactly.
112
5301
pub fn template_values(draft: &TransactionDraft) -> Result<FormValues, Failure> {
113
5301
    let (pairs, rest) = draft.splits.as_chunks::<2>();
114
5301
    if !rest.is_empty() {
115
803
        return Err(refused("it has an odd number of splits"));
116
4498
    }
117
4498
    let mut values = FormValues::default();
118
4498
    if let Some(raw) = &draft.date {
119
4011
        let instant = parse_post_date(raw).map_err(|err| refused(format!("date: {err}")))?;
120
3369
        values.set(
121
3369
            "date",
122
3369
            &instant.to_rfc3339_opts(SecondsFormat::AutoSi, true),
123
3369
        );
124
487
    }
125
3856
    values.set("note", draft.note.as_deref().unwrap_or_default());
126
3856
    values.set_rows("tags");
127
3856
    for tag in &draft.tags {
128
3529
        values.push_row("tags", tag_row(tag));
129
    }
130
3856
    values.set_rows("split-tags");
131
3856
    for (index, pair) in pairs.iter().enumerate() {
132
3852
        let row = pair_row(pair, index)?;
133
3848
        let key = format!("n{}", index + 1);
134
3848
        values.push_row("splits", row);
135
3848
        let [from, to] = pair;
136
3848
        let tags = RowTags::of_legs(&from.tags, &to.tags, DraftTag::eq);
137
3848
        for row in split_tag_rows(&key, &tags, tag_row) {
138
1925
            values.push_row("split-tags", row);
139
        }
140
    }
141
3852
    Ok(values)
142
5301
}