Lines
98.5 %
Functions
83.78 %
Branches
100 %
//! Row resolution and lowering shared by the transaction create and edit
//! submits: stage 2 (resolution) and stage 3 (domain rules on ids).
use chrono::{DateTime, Utc};
use forms::{FieldError, FormValues, Row, address, parse_post_date};
use num_rational::Rational64;
use server::logical::{
LogicalSplit, PhysicalSplit, PriceRow, RowTags, SplitFault, SplitField,
lower_logical_split_located,
};
use super::hidden::Hidden;
use crate::lowering::Lowered;
use crate::resolve::{Directory, RowKeys};
type LoweredRow = (PhysicalSplit, PhysicalSplit, Option<PriceRow>);
pub(super) fn error_at(field: String, message: impl Into<String>) -> FieldError {
FieldError {
field,
message: message.into(),
}
/// The to-commodity cell of a loaded row: empty when it is the from-commodity,
/// which a submit already reads as the same commodity.
pub(super) fn to_commodity_cell<T: PartialEq + ToString>(from: &T, to: &T) -> String {
match from == to {
true => String::new(),
false => to.to_string(),
/// A field error at `field` when `value` spans several lines.
pub(super) fn single_line(field: &str, value: &str) -> Result<(), FieldError> {
match value.contains(['\n', '\r']) {
true => Err(error_at(field.to_string(), "must be a single line")),
false => Ok(()),
/// Both results, or the field errors of every failed one.
pub(super) fn joined<A, B>(
first: Result<A, Vec<FieldError>>,
second: Result<B, Vec<FieldError>>,
) -> Result<(A, B), Vec<FieldError>> {
match (first, second) {
(Ok(first), Ok(second)) => Ok((first, second)),
(first, second) => Err(first
.err()
.into_iter()
.chain(second.err())
.flatten()
.collect()),
pub(super) fn post_date(values: &FormValues) -> Result<DateTime<Utc>, FieldError> {
let text = values.text("date").unwrap_or_default();
parse_post_date(text).map_err(|message| error_at("date".to_string(), message))
/// Resolve and lower every row, collecting the errors of all of them. A row
/// with hidden data keeps it: unchanged cells submit the hidden ids, an
/// unchanged FX row its price date. Each row's `tags` go on its legs.
pub(super) fn lower_rows(
directory: &Directory,
rows: &[Row],
hidden: &[Option<Hidden>],
tags: &[RowTags],
) -> Result<Lowered, Vec<FieldError>> {
let mut lowered = Lowered {
splits: Vec::new(),
prices: Vec::new(),
split_tags: Vec::new(),
let mut errors = Vec::new();
let mut failed = false;
for (index, row) in rows.iter().enumerate() {
let hidden = hidden.get(index).and_then(Option::as_ref);
match lower_row(directory, row, index, hidden) {
Ok((from, to, price)) => {
if let Some(tags) = tags.get(index) {
lowered.split_tags.extend(tags.on_legs(from.id, to.id));
lowered.splits.extend([from, to]);
lowered.prices.extend(price);
Err(mut row_errors) => {
failed = true;
errors.append(&mut row_errors);
match failed {
true => Err(errors),
false => Ok(lowered),
fn cell<'a>(row: &'a Row, key: &str) -> &'a str {
row.get(key).map_or("", |text| text.trim())
fn lower_row(
row: &Row,
index: usize,
hidden: Option<&Hidden>,
) -> Result<LoweredRow, Vec<FieldError>> {
if let Some(hidden) = hidden {
hidden
.verify(directory)
.map_err(|message| vec![error_at(address::row("splits", index), message)])?;
let split = resolve_row(directory, row, index, hidden)?;
let (from, to, price) =
lower_logical_split_located(&split).map_err(|fault| vec![fault_error(index, fault)])?;
let kept_date = hidden
.filter(|hidden| hidden.unchanged(&split))
.and_then(|hidden| hidden.price_date);
let price = price.map(|price| PriceRow {
date: kept_date,
..price
});
Ok((from, to, price))
fn resolve_row(
) -> Result<LogicalSplit, Vec<FieldError>> {
let keys = RowKeys {
from: cell(row, "from"),
to: cell(row, "to"),
from_commodity: cell(row, "from-commodity"),
to_commodity: Some(cell(row, "to-commodity")).filter(|text| !text.is_empty()),
let ids = directory.resolve_row(&keys).map_err(|faults| {
faults
.map(|(field, err)| {
error_at(address::cell("splits", index, field.key()), err.to_string())
})
.collect::<Vec<_>>()
})?;
let value = amount_at(row, "value", index).map_err(|e| vec![e])?;
let to_amount = amount_at(row, "to-amount", index).map_err(|e| vec![e])?;
Ok(LogicalSplit {
from: ids.from,
to: ids.to,
from_commodity: ids.from_commodity,
to_commodity: ids.to_commodity,
value: value.unwrap_or_default(),
to_amount,
from_reconcile: hidden.and_then(|hidden| hidden.reconcile[0]),
to_reconcile: hidden.and_then(|hidden| hidden.reconcile[1]),
/// An amount token as an exact rational.
pub(super) fn parse_rational(text: &str) -> Result<Rational64, String> {
let (numer, denom) = amount::parse_amount(text).map_err(|err| err.to_string())?;
Ok(Rational64::new(numer, denom))
/// An empty cell is absent; syntax was already checked, so a failure here
/// only guards the conversion.
fn amount_at(row: &Row, key: &str, index: usize) -> Result<Option<Rational64>, FieldError> {
let text = cell(row, key);
if text.is_empty() {
return Ok(None);
parse_rational(text)
.map(Some)
.map_err(|err| error_at(address::cell("splits", index, key), err))
fn fault_error(index: usize, fault: SplitFault) -> FieldError {
let field = match fault.field {
Some(SplitField::Value) => address::cell("splits", index, "value"),
Some(SplitField::ToAmount) => address::cell("splits", index, "to-amount"),
None => address::row("splits", index),
error_at(field, fault.message)