Lines
98.4 %
Functions
79.07 %
Branches
100 %
//! The lossless fixture of the client form tests: one transaction holding
//! everything an edit could lose, and a snapshot of what is stored for it.
use std::collections::HashMap;
use chrono::{DateTime, Utc};
use finance::price::Price;
use finance::split::Split;
use finance::tag::Tag;
use num_rational::Rational64;
use sqlx::PgPool;
use sqlx::types::Uuid;
use crate::command::account::CreateAccount;
use crate::command::commodity::CreateCommodity;
use crate::command::transaction::CreateTransaction;
use crate::command::{CmdError, CmdResult, FinanceEntity};
use crate::logical::{LogicalSplit, lower_logical_transaction};
/// An exact instant with microseconds.
pub const POST_DATE: &str = "2026-10-27T09:15:42.123456Z";
/// The FX price date: distinct from the post date, with microseconds.
pub const PRICE_DATE: &str = "2026-10-20T08:30:15.654321Z";
pub const NOTE: &str = "first line\nsecond \"quoted\" back\\slash";
/// The note a note-only edit writes.
pub const EDITED_NOTE: &str = "edited\nnote";
pub struct Lossless {
pub user: Uuid,
pub transaction: Uuid,
}
fn tag(name: &str, value: &str, description: Option<&str>) -> Tag {
Tag {
id: Uuid::new_v4(),
tag_name: name.to_string(),
tag_value: value.to_string(),
description: description.map(str::to_string),
fn instant(text: &str) -> Result<DateTime<Utc>, CmdError> {
DateTime::parse_from_rfc3339(text)
.map(|date| date.with_timezone(&Utc))
.map_err(|err| CmdError::Args(err.to_string()))
pub(crate) async fn commodity(user: Uuid, symbol: &str) -> Result<Uuid, CmdError> {
let created = CreateCommodity::new()
.symbol(symbol.to_string())
.name(symbol.to_string())
.user_id(user)
.run()
.await?;
match created {
Some(CmdResult::String(id)) => {
Uuid::parse_str(&id).map_err(|err| CmdError::Args(err.to_string()))
other => Err(CmdError::Args(format!("commodity: {other:?}"))),
pub(crate) async fn account(user: Uuid, name: &str) -> Result<Uuid, CmdError> {
let created = CreateAccount::new()
.name(name.to_string())
Some(CmdResult::Entity(FinanceEntity::Account(account))) => Ok(account.id),
other => Err(CmdError::Args(format!("account: {other:?}"))),
/// An FX row (reconcile carried, distinct price date) and an exact
/// fraction row, from `Cash` to `Food`.
fn rows(cash: Uuid, food: Uuid, usd: Uuid, eur: Uuid) -> [LogicalSplit; 2] {
[
LogicalSplit {
from: cash,
to: food,
from_commodity: usd,
to_commodity: eur,
value: Rational64::new(10, 1),
to_amount: Some(Rational64::new(9, 1)),
from_reconcile: Some(false),
to_reconcile: Some(false),
},
to_commodity: usd,
value: Rational64::new(1, 3),
to_amount: None,
from_reconcile: None,
to_reconcile: None,
]
fn split_entity(split: &crate::logical::PhysicalSplit, tx_id: Uuid) -> FinanceEntity {
FinanceEntity::Split(Split {
id: split.id,
tx_id,
account_id: split.account_id,
commodity_id: split.commodity_id,
value_num: *split.value.numer(),
value_denom: *split.value.denom(),
reconcile_state: split.reconcile_state,
reconcile_date: None,
lot_id: None,
})
fn transaction_tags(carriage_returns: bool) -> HashMap<String, FinanceEntity> {
tag("trip", "japan", Some("spring \"trip\" \\ notes\nday two")),
tag("project", "nomisync", Some("client forms")),
tag("cleared", "yes", None),
tag("windows", "crlf", Some("dos\r\nline\rmac end")),
tag("blank", "empty", Some("")),
.into_iter()
.filter(|tag| carriage_returns || tag.tag_name != "windows")
.map(|tag| (tag.tag_name.clone(), FinanceEntity::Tag(tag)))
.collect()
/// A user with the lossless transaction: transaction tags with and without
/// (multiline, CR and CRLF, or empty) descriptions, split tags, an FX price dated apart from the
/// exact post date, a fraction and a multiline note.
///
/// # Errors
/// Any failing seed command.
pub async fn seed(pool: &PgPool) -> Result<Lossless, CmdError> {
let user = Uuid::new_v4();
sqlx::query_file!(
"sql/insert/users/fixture.sql",
user,
format!("u{user}"),
format!("{user}@test.com")
)
.execute(pool)
let transaction = seed_transaction(user).await?;
Ok(Lossless { user, transaction })
/// The lossless transaction in the store of the existing `user`.
pub async fn seed_transaction(user: Uuid) -> Result<Uuid, CmdError> {
seed_with(user, true).await
/// [`seed_transaction`] without the carriage-return tag, for the web edit
/// page, which refuses carriage returns by design.
pub async fn seed_transaction_without_cr(user: Uuid) -> Result<Uuid, CmdError> {
seed_with(user, false).await
async fn seed_with(user: Uuid, carriage_returns: bool) -> Result<Uuid, CmdError> {
let (usd, eur) = (commodity(user, "USD").await?, commodity(user, "EUR").await?);
let (cash, food) = (account(user, "Cash").await?, account(user, "Food").await?);
let (splits, mut prices) = lower_logical_transaction(&rows(cash, food, usd, eur))?;
let price_date = instant(PRICE_DATE)?;
prices
.iter_mut()
.for_each(|price| price.date = Some(price_date));
let transaction = Uuid::new_v4();
let split_tags = splits
.iter()
.enumerate()
.map(|(index, split)| match index / 2 {
0 => (
split.id,
tag("memo", "m\\x", Some("split memo\nsecond line")),
),
_ => (split.id, tag("category", "food", None)),
.collect();
let prices = prices
.map(|price| {
FinanceEntity::Price(Price {
date: price_date,
commodity_id: price.commodity_id,
currency_id: price.currency_id,
commodity_split: Some(price.commodity_split),
currency_split: Some(price.currency_split),
value_num: price.value_num,
value_denom: price.value_denom,
CreateTransaction::new()
.id(transaction)
.post_date(instant(POST_DATE)?)
.enter_date(Utc::now())
.splits(
splits
.map(|s| split_entity(s, transaction))
.collect(),
.prices(prices)
.note(NOTE.to_string())
.tags(transaction_tags(carriage_returns))
.split_tags(split_tags)
Ok(transaction)
/// Everything stored for the transaction, one sorted line per fact, without
/// the split and price ids an edit regenerates.
/// The query failing.
pub async fn snapshot<'e>(
executor: impl sqlx::PgExecutor<'e>,
transaction: Uuid,
) -> Result<Vec<String>, sqlx::Error> {
let facts = sqlx::query_file_scalar!("sql/select/transactions/snapshot.sql", transaction)
.fetch_all(executor)
Ok(facts.into_iter().flatten().collect())
/// The snapshot without its note line.
#[must_use]
pub fn without_note(snapshot: &[String]) -> Vec<String> {
snapshot
.filter(|fact| !fact.starts_with("tag note "))
.cloned()
/// The name of the first split tag the loaded payload gives row `r1`.
pub fn first_row_tag(loaded: &str) -> Option<&str> {
let (_, rest) = loaded.split_once("(:row \"r1\" :name \"")?;
rest.split('"').next()
fn facts<'a>(snapshot: &'a [String], kind: &str) -> impl Iterator<Item = &'a String> {
let prefix = format!("{kind} ");
.filter(move |fact| fact.starts_with(&prefix))
/// The split-tag facts of the snapshot whose tag is named `name`.
pub fn split_tag_facts(snapshot: &[String], name: &str) -> Vec<String> {
let name = format!(" {name} ");
facts(snapshot, "split-tag")
.filter(|fact| fact.contains(&name))
/// The sorted transaction-tag facts of the snapshot, the note fact excluded.
pub fn tag_facts(snapshot: &[String]) -> Vec<String> {
let mut facts: Vec<_> = without_note(snapshot)
.filter(|fact| fact.starts_with("tag "))
facts.sort();
facts
/// Whether the snapshot holds three rows and, as split tags, exactly the
/// non-empty `kept` facts: what an edit that drops row `r2` and adds two
/// untagged rows stores.
pub fn kept_only(snapshot: &[String], kept: &[String]) -> bool {
!kept.is_empty()
&& facts(snapshot, "split").count() == 6
&& facts(snapshot, "split-tag").eq(kept.iter())