Lines
90.77 %
Functions
80.77 %
Branches
100 %
//! A stored transaction as the edit form can represent it.
use std::collections::HashMap;
use finance::split::Split;
use finance::tag::Tag;
use server::command::CmdError;
use server::logical::{form_refusal, is_note, pick_note, stored_revision};
use server::user::User;
use uuid::Uuid;
use super::Failure;
use crate::host_failure::cmd_failure;
use crate::stored::raise_rows;
use crate::stored::{Detail, TaggedRow};
pub(super) struct Stored {
pub(super) detail: Detail,
/// Transaction tags except the note, sorted by name.
pub(super) tags: Vec<Tag>,
pub(super) rows: Vec<TaggedRow>,
/// The server's digest of the raw stored state; a changed digest means the
/// loaded form is stale.
pub(super) revision: String,
}
fn refusal(err: CmdError) -> Failure {
Failure::Refused(match err {
CmdError::Args(reason) => reason,
other => other.to_string(),
})
/// Every non-note tag of the transaction, sorted by name and value, with the
/// note.
fn other_tags(mut tags: Vec<Tag>) -> (Vec<Tag>, Option<String>) {
sort(&mut tags);
let note = pick_note(tags.iter()).map(|tag| tag.normalized().1.to_string());
tags.retain(|tag| !is_note(tag));
(tags, note)
fn sort(tags: &mut [Tag]) {
tags.sort_by(|a, b| (&a.tag_name, &a.tag_value).cmp(&(&b.tag_name, &b.tag_value)));
/// Every tag of each split, sorted, a split without tags included.
fn split_tags(splits: &[Split], mut all: HashMap<Uuid, Vec<Tag>>) -> HashMap<Uuid, Vec<Tag>> {
for split in splits {
sort(all.entry(split.id).or_default());
all
/// Whether the transaction is the user's, without the form's refusals.
pub(super) async fn is_owned(user_id: Uuid, transaction_id: Uuid) -> Result<bool, Failure> {
let snapshot = User { id: user_id }
.transaction_snapshot(transaction_id)
.await
.map_err(|err| cmd_failure("load-form", err.into()))?;
Ok(snapshot.is_some())
/// The user's transaction raised to rows, `None` when it is not theirs. A
/// transaction the form would corrupt is a refusal, never a form.
pub(super) async fn load_stored(
user_id: Uuid,
transaction_id: Uuid,
) -> Result<Option<Stored>, Failure> {
let Some(snapshot) = User { id: user_id }
.map_err(|err| cmd_failure("load-form", err.into()))?
else {
return Ok(None);
};
form_refusal(
&snapshot.tags,
&snapshot.splits,
&snapshot.split_tags,
&snapshot.prices,
)
.map_err(Failure::Refused)?;
let revision = stored_revision(
snapshot.transaction.post_date,
snapshot.tags.clone(),
);
let (tags, note) = other_tags(snapshot.tags);
let splits = snapshot.splits;
let split_tags = split_tags(&splits, snapshot.split_tags);
let detail = Detail {
transaction: snapshot.transaction,
note,
prices: snapshot.prices,
let rows = raise_rows(&splits, &split_tags, &detail.prices).map_err(refusal)?;
Ok(Some(Stored {
detail,
tags,
rows,
revision,
}))