Lines
95.87 %
Functions
100 %
Branches
//! Writing lowered transaction rows: shared by the logical natives and the
//! form path.
use std::collections::HashMap;
use chrono::{DateTime, Utc};
use finance::price::Price;
use finance::split::Split;
use finance::tag::Tag;
use forms::FieldError;
use server::command::transaction::{CreateTransaction, UpdateTransaction};
use server::command::{CmdError, CmdResult, FinanceEntity};
use server::logical::{PhysicalSplit, PriceRow, STALE_REVISION};
use uuid::Uuid;
use crate::forms::Failure;
/// Physical lowering of a logical payload plus the tags its rows carry.
pub(crate) struct Lowered {
pub(crate) splits: Vec<PhysicalSplit>,
pub(crate) prices: Vec<PriceRow>,
pub(crate) split_tags: Vec<(Uuid, Tag)>,
}
/// Non-note transaction tags by name.
pub(crate) type TransactionTags = HashMap<String, FinanceEntity>;
/// The transaction-level values a create or an update writes.
pub(crate) struct Header {
pub(crate) note: Option<String>,
pub(crate) post_date: Option<DateTime<Utc>>,
/// Replaces the non-note transaction tags; `None` leaves them.
pub(crate) tags: Option<TransactionTags>,
/// Create the transaction for already lowered rows; shared by the logical
/// native and the form path.
pub(crate) async fn create_lowered(
ctx: &str,
user_id: Uuid,
header: Header,
lowered: Lowered,
) -> Result<Uuid, Failure> {
let tx_id = Uuid::new_v4();
let post_date = header.post_date.unwrap_or_else(Utc::now);
let enter_date = Utc::now();
let splits = physical_splits_to_entities(lowered.splits, tx_id);
let mut runner = CreateTransaction::new()
.user_id(user_id)
.id(tx_id)
.post_date(post_date)
.enter_date(enter_date)
.splits(splits);
if let Some(note) = header.note {
runner = runner.note(note);
if let Some(tags) = header.tags {
runner = runner.tags(tags);
if !lowered.prices.is_empty() {
runner = runner.prices(price_rows_to_entities(lowered.prices, post_date));
if !lowered.split_tags.is_empty() {
runner = runner.split_tags(lowered.split_tags);
dispatch_tx_result(ctx, runner.run().await)
/// Replace the splits of a transaction with already lowered rows; shared by
/// the logical native and the form path.
pub(crate) async fn update_lowered(
transaction_id: Uuid,
expected_revision: Option<&str>,
let Header {
note,
post_date,
tags,
} = header;
// A split-only edit must leave the stored dates intact: forward post_date
// only when :date was explicitly provided. The price rows still need a
// fallback observation date when none is given.
let price_date = post_date.unwrap_or_else(Utc::now);
let splits = physical_splits_to_entities(lowered.splits, transaction_id);
let mut runner = UpdateTransaction::new()
.transaction_id(transaction_id)
.splits(splits)
.refuse_unkeepable(true);
if let Some(post_date) = post_date {
runner = runner.post_date(post_date);
if let Some(note) = note {
if let Some(tags) = tags {
runner = runner.prices(price_rows_to_entities(lowered.prices, price_date));
if let Some(revision) = expected_revision {
runner = runner.expected_revision(revision.to_string());
match runner.run().await {
Err(CmdError::Args(message)) if message == STALE_REVISION => {
Err(Failure::Invalid(vec![FieldError {
field: "revision".to_string(),
message,
}]))
result => dispatch_tx_result(ctx, result),
fn dispatch_tx_result(
result: Result<Option<CmdResult>, CmdError>,
match result {
Ok(Some(CmdResult::Entity(FinanceEntity::Transaction(tx)))) => Ok(tx.id),
Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
"{ctx}: expected Transaction entity, got {other:?}"
))
.into()),
Ok(None) => Err(wasmtime::Error::msg(format!("{ctx}: command returned no entity")).into()),
Err(err) => Err(Failure::from_command(ctx, err)),
/// Convert physical splits to `FinanceEntity::Split` with the given transaction ID.
fn physical_splits_to_entities(splits: Vec<PhysicalSplit>, tx_id: Uuid) -> Vec<FinanceEntity> {
splits
.into_iter()
.map(|ps| {
FinanceEntity::Split(Split {
id: ps.id,
tx_id,
account_id: ps.account_id,
commodity_id: ps.commodity_id,
value_num: *ps.value.numer(),
value_denom: *ps.value.denom(),
reconcile_state: ps.reconcile_state,
reconcile_date: None,
lot_id: None,
})
.collect()
/// Convert price rows to `FinanceEntity::Price`, using `post_date` as the
/// fallback date when the row carries none.
fn price_rows_to_entities(
price_rows: Vec<PriceRow>,
post_date: DateTime<Utc>,
) -> Vec<FinanceEntity> {
price_rows
.map(|pr| {
FinanceEntity::Price(Price {
id: Uuid::new_v4(),
date: pr.date.unwrap_or(post_date),
commodity_id: pr.commodity_id,
currency_id: pr.currency_id,
commodity_split: Some(pr.commodity_split),
currency_split: Some(pr.currency_split),
value_num: pr.value_num,
value_denom: pr.value_denom,
#[cfg(test)]
#[path = "lowering_tests.rs"]
mod tests;