Skip to main content

rpc/forms/
transaction_create_load.rs

1//! `load-form "transaction-create"`: a template's draft as create values.
2
3use chrono::SecondsFormat;
4use forms::{FormValues, Row, parse_post_date};
5use num_rational::Rational64;
6use server::logical::RowTags;
7use server::user::User;
8use uuid::Uuid;
9
10use super::transaction_rows::to_commodity_cell;
11use super::transaction_split_tags::split_tag_rows;
12use super::{Entity, Failure};
13use crate::ScriptCtx;
14use crate::draft::{DraftSplit, DraftTag, TransactionDraft};
15use crate::host_failure::unavailable_condition;
16use crate::template::{TemplateError, render_template};
17
18const CTX: &str = "load-form";
19
20pub(super) async fn load_transaction_create(
21    user_id: Uuid,
22    id: &str,
23) -> Result<FormValues, Failure> {
24    let template_id = Uuid::parse_str(id.trim()).map_err(|_| Failure::MalformedId {
25        entity: Entity::Template,
26        id: id.to_string(),
27    })?;
28    let detail = User { id: user_id }
29        .find_template(template_id)
30        .await
31        .map_err(|err| Failure::Internal(wasmtime::Error::msg(format!("{CTX}: {err}"))))?
32        .ok_or(Failure::Missing(Entity::Template))?;
33    let draft = render_template(&ScriptCtx::new(user_id), &detail.source_text)
34        .await
35        .map_err(render_failure)?;
36    template_values(&draft)
37}
38
39fn render_failure(err: TemplateError) -> Failure {
40    if let TemplateError::Unavailable(message) = err {
41        return Failure::Internal(unavailable_condition(message));
42    }
43    match err.is_internal() {
44        true => Failure::Internal(wasmtime::Error::msg(format!("{CTX}: {err}"))),
45        false => Failure::Refused(err.to_string()),
46    }
47}
48
49fn refused(reason: impl Into<String>) -> Failure {
50    Failure::Refused(reason.into())
51}
52
53fn exact(num: i64, denom: i64) -> Option<Rational64> {
54    (denom != 0 && num != i64::MIN && denom != i64::MIN).then(|| Rational64::new(num, denom))
55}
56
57fn tag_row(tag: &DraftTag) -> Row {
58    Row::from([
59        ("name".to_string(), tag.name.clone()),
60        ("value".to_string(), tag.value.clone()),
61    ])
62}
63
64fn amount_of(split: &DraftSplit, position: usize) -> Result<Rational64, Failure> {
65    exact(split.value_num, split.value_denom)
66        .ok_or_else(|| refused(format!("split {position} has an invalid amount")))
67}
68
69/// One form row of a debit leg followed by its credit leg.
70fn pair_row(pair: &[DraftSplit; 2], index: usize) -> Result<Row, Failure> {
71    let [from, to] = pair;
72    let (out, into) = (amount_of(from, 2 * index)?, amount_of(to, 2 * index + 1)?);
73    if out >= Rational64::from_integer(0) || into < Rational64::from_integer(0) {
74        return Err(refused(format!(
75            "splits {} and {} are not a debit followed by a credit",
76            2 * index,
77            2 * index + 1
78        )));
79    }
80    let value = -out;
81    let mut row = Row::from([
82        ("key".to_string(), format!("n{}", index + 1)),
83        ("from".to_string(), from.account_id.clone()),
84        ("to".to_string(), to.account_id.clone()),
85        ("from-commodity".to_string(), from.commodity_id.clone()),
86        (
87            "to-commodity".to_string(),
88            to_commodity_cell(&from.commodity_id, &to.commodity_id),
89        ),
90        ("value".to_string(), amount::wire_rational(value)),
91    ]);
92    match from.commodity_id == to.commodity_id {
93        true if value != into => {
94            return Err(refused(format!(
95                "splits {} and {} are in one commodity but differ in amount",
96                2 * index,
97                2 * index + 1
98            )));
99        }
100        true => {}
101        false => {
102            row.insert("to-amount".to_string(), amount::wire_rational(into));
103        }
104    }
105    Ok(row)
106}
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.
112pub fn template_values(draft: &TransactionDraft) -> Result<FormValues, Failure> {
113    let (pairs, rest) = draft.splits.as_chunks::<2>();
114    if !rest.is_empty() {
115        return Err(refused("it has an odd number of splits"));
116    }
117    let mut values = FormValues::default();
118    if let Some(raw) = &draft.date {
119        let instant = parse_post_date(raw).map_err(|err| refused(format!("date: {err}")))?;
120        values.set(
121            "date",
122            &instant.to_rfc3339_opts(SecondsFormat::AutoSi, true),
123        );
124    }
125    values.set("note", draft.note.as_deref().unwrap_or_default());
126    values.set_rows("tags");
127    for tag in &draft.tags {
128        values.push_row("tags", tag_row(tag));
129    }
130    values.set_rows("split-tags");
131    for (index, pair) in pairs.iter().enumerate() {
132        let row = pair_row(pair, index)?;
133        let key = format!("n{}", index + 1);
134        values.push_row("splits", row);
135        let [from, to] = pair;
136        let tags = RowTags::of_legs(&from.tags, &to.tags, DraftTag::eq);
137        for row in split_tag_rows(&key, &tags, tag_row) {
138            values.push_row("split-tags", row);
139        }
140    }
141    Ok(values)
142}