Lines
96.12 %
Functions
83.33 %
Branches
100 %
//! `load-form "transaction-create"`: a template's draft as create values.
use chrono::SecondsFormat;
use forms::{FormValues, Row, parse_post_date};
use num_rational::Rational64;
use server::logical::RowTags;
use server::user::User;
use uuid::Uuid;
use super::transaction_rows::to_commodity_cell;
use super::transaction_split_tags::split_tag_rows;
use super::{Entity, Failure};
use crate::ScriptCtx;
use crate::draft::{DraftSplit, DraftTag, TransactionDraft};
use crate::host_failure::unavailable_condition;
use crate::template::{TemplateError, render_template};
const CTX: &str = "load-form";
pub(super) async fn load_transaction_create(
user_id: Uuid,
id: &str,
) -> Result<FormValues, Failure> {
let template_id = Uuid::parse_str(id.trim()).map_err(|_| Failure::MalformedId {
entity: Entity::Template,
id: id.to_string(),
})?;
let detail = User { id: user_id }
.find_template(template_id)
.await
.map_err(|err| Failure::Internal(wasmtime::Error::msg(format!("{CTX}: {err}"))))?
.ok_or(Failure::Missing(Entity::Template))?;
let draft = render_template(&ScriptCtx::new(user_id), &detail.source_text)
.map_err(render_failure)?;
template_values(&draft)
}
fn render_failure(err: TemplateError) -> Failure {
if let TemplateError::Unavailable(message) = err {
return Failure::Internal(unavailable_condition(message));
match err.is_internal() {
true => Failure::Internal(wasmtime::Error::msg(format!("{CTX}: {err}"))),
false => Failure::Refused(err.to_string()),
fn refused(reason: impl Into<String>) -> Failure {
Failure::Refused(reason.into())
fn exact(num: i64, denom: i64) -> Option<Rational64> {
(denom != 0 && num != i64::MIN && denom != i64::MIN).then(|| Rational64::new(num, denom))
fn tag_row(tag: &DraftTag) -> Row {
Row::from([
("name".to_string(), tag.name.clone()),
("value".to_string(), tag.value.clone()),
])
fn amount_of(split: &DraftSplit, position: usize) -> Result<Rational64, Failure> {
exact(split.value_num, split.value_denom)
.ok_or_else(|| refused(format!("split {position} has an invalid amount")))
/// One form row of a debit leg followed by its credit leg.
fn pair_row(pair: &[DraftSplit; 2], index: usize) -> Result<Row, Failure> {
let [from, to] = pair;
let (out, into) = (amount_of(from, 2 * index)?, amount_of(to, 2 * index + 1)?);
if out >= Rational64::from_integer(0) || into < Rational64::from_integer(0) {
return Err(refused(format!(
"splits {} and {} are not a debit followed by a credit",
2 * index,
2 * index + 1
)));
let value = -out;
let mut row = Row::from([
("key".to_string(), format!("n{}", index + 1)),
("from".to_string(), from.account_id.clone()),
("to".to_string(), to.account_id.clone()),
("from-commodity".to_string(), from.commodity_id.clone()),
(
"to-commodity".to_string(),
to_commodity_cell(&from.commodity_id, &to.commodity_id),
),
("value".to_string(), amount::wire_rational(value)),
]);
match from.commodity_id == to.commodity_id {
true if value != into => {
"splits {} and {} are in one commodity but differ in amount",
true => {}
false => {
row.insert("to-amount".to_string(), amount::wire_rational(into));
Ok(row)
/// The create values a rendered template stands for.
///
/// # Errors
/// [`Failure::Refused`] when the draft cannot be shown as form rows exactly.
pub fn template_values(draft: &TransactionDraft) -> Result<FormValues, Failure> {
let (pairs, rest) = draft.splits.as_chunks::<2>();
if !rest.is_empty() {
return Err(refused("it has an odd number of splits"));
let mut values = FormValues::default();
if let Some(raw) = &draft.date {
let instant = parse_post_date(raw).map_err(|err| refused(format!("date: {err}")))?;
values.set(
"date",
&instant.to_rfc3339_opts(SecondsFormat::AutoSi, true),
);
values.set("note", draft.note.as_deref().unwrap_or_default());
values.set_rows("tags");
for tag in &draft.tags {
values.push_row("tags", tag_row(tag));
values.set_rows("split-tags");
for (index, pair) in pairs.iter().enumerate() {
let row = pair_row(pair, index)?;
let key = format!("n{}", index + 1);
values.push_row("splits", row);
let tags = RowTags::of_legs(&from.tags, &to.tags, DraftTag::eq);
for row in split_tag_rows(&key, &tags, tag_row) {
values.push_row("split-tags", row);
Ok(values)