Lines
96.03 %
Functions
72.22 %
Branches
100 %
//! `update-transaction` keeps the reconcile state, reconcile date and lot a
//! replacement split leaves out (plan 0016 H24).
use chrono::{DateTime, Utc};
use server::command::transaction::KeepStored;
use sqlx::PgPool;
use uuid::Uuid;
use super::parse::{parse_split_plist, parse_update_transaction_payload};
use super::run::run_update_transaction;
use super::run_logical::run_create_transaction_logical;
use super::tests_logical_update::{seed_account, seed_commodity, seed_user};
const KEEP_ALL: KeepStored = KeepStored {
reconcile_state: true,
reconcile_date: true,
lot_id: true,
};
fn parsed(fields: &str) -> Result<(finance::split::Split, KeepStored), String> {
let src = format!(
"(:transaction-id \"{}\" :splits ((:account-id \"{a}\" :commodity-id \"{a}\" :value 1 {fields}) \
(:account-id \"{a}\" :commodity-id \"{a}\" :value -1)))",
Uuid::nil(),
a = Uuid::nil()
);
let mut splits = parse_update_transaction_payload(&src)?
.splits
.ok_or("no splits")?;
Ok(splits.remove(0))
}
#[test]
fn a_split_without_state_keys_keeps_every_stored_field() -> Result<(), String> {
let (split, keep) = parsed("")?;
assert_eq!(keep, KEEP_ALL);
assert_eq!(
(split.reconcile_state, split.reconcile_date, split.lot_id),
(None, None, None)
Ok(())
fn reconciled_takes_t_nil_and_unknown() -> Result<(), String> {
for (token, state) in [("t", Some(true)), ("nil", Some(false)), (":unknown", None)] {
let (split, keep) = parsed(&format!(":reconciled {token}"))?;
assert_eq!(split.reconcile_state, state, "{token}");
assert!(!keep.reconcile_state, "{token}");
assert!(keep.reconcile_date && keep.lot_id, "{token}");
fn a_given_date_and_lot_are_set_and_nil_clears_them() -> Result<(), String> {
let lot = Uuid::new_v4();
let (split, keep) = parsed(&format!(
":reconcile-date \"2026-01-02T03:04:05Z\" :lot-id \"{lot}\""
))?;
let date: DateTime<Utc> = "2026-01-02T03:04:05Z".parse().map_err(|e| format!("{e}"))?;
(split.reconcile_date, split.lot_id),
(Some(date), Some(lot))
assert!(!keep.reconcile_date && !keep.lot_id && keep.reconcile_state);
let (split, keep) = parsed(":reconcile-date nil :lot-id nil")?;
assert_eq!((split.reconcile_date, split.lot_id), (None, None));
assert!(!keep.reconcile_date && !keep.lot_id);
fn malformed_state_values_name_the_split_and_key() {
for (fields, expected) in [
(
":reconciled 1",
"split[0]: :reconciled must be t, nil or :unknown",
),
":reconcile-date \"soon\"",
"split[0]: invalid :reconcile-date 'soon'",
(":lot-id \"x\"", "split[0]: invalid :lot-id 'x'"),
(":lot-id 3", "split[0]: :lot-id must be a string or nil"),
] {
let err = parsed(fields).map(|_| ()).unwrap_err();
assert!(err.contains(expected), "{fields}: {err}");
fn a_create_split_ignores_what_it_would_keep() -> Result<(), String> {
let program = nomiscript::Reader::parse(&format!(
"(:account-id \"{a}\" :commodity-id \"{a}\" :value 1 :reconciled t)",
))
.map_err(|e| format!("{e}"))?;
let expr = program.exprs.into_iter().next().ok_or("empty")?;
let (split, _) = parse_split_plist(expr, 0)?;
assert_eq!(split.reconcile_state, Some(true));
struct Reconciled {
user: Uuid,
tx: Uuid,
commodity: Uuid,
/// (id, value, account), the negative split first.
splits: [(Uuid, i64, Uuid); 2],
lot: Uuid,
date: DateTime<Utc>,
/// A two-split transaction whose splits are reconciled, dated and in a lot.
async fn reconciled(pool: &PgPool) -> anyhow::Result<Reconciled> {
let user = Uuid::new_v4();
seed_user(pool, user).await?;
let commodity = seed_commodity(user, "USD", "US Dollar").await?;
let from = seed_account(user, "Assets").await?;
let to = seed_account(user, "Expenses").await?;
let create = format!(
"(:splits ((:from \"{from}\" :to \"{to}\" :from-commodity \"{commodity}\" \
:to-commodity \"{commodity}\" :value 5)))"
run_create_transaction_logical(user, Some(create))
.await
.map_err(|e| anyhow::anyhow!("{e}"))?;
sqlx::query("INSERT INTO lots (id, account_id, is_closed) VALUES ($1, $2, 0)")
.bind(lot)
.bind(from)
.execute(pool)
.await?;
let date: DateTime<Utc> = "2026-01-02T03:04:05Z".parse()?;
sqlx::query("UPDATE splits SET reconcile_state = true, reconcile_date = $1, lot_id = $2")
.bind(date)
let rows: Vec<(Uuid, Uuid, i64, Uuid)> =
sqlx::query_as("SELECT id, tx_id, value_num, account_id FROM splits ORDER BY value_num")
.fetch_all(pool)
let [(a, tx, a_value, a_account), (b, _, b_value, b_account)] = rows[..] else {
anyhow::bail!("expected two splits: {rows:?}");
Ok(Reconciled {
user,
tx,
commodity,
splits: [(a, a_value, a_account), (b, b_value, b_account)],
lot,
date,
})
/// A split's reconcile state, reconcile date and lot.
type Fields = (Option<bool>, Option<DateTime<Utc>>, Option<Uuid>);
type State = (Uuid, Option<bool>, Option<DateTime<Utc>>, Option<Uuid>);
async fn states(pool: &PgPool) -> anyhow::Result<Vec<State>> {
Ok(sqlx::query_as(
"SELECT id, reconcile_state, reconcile_date, lot_id FROM splits ORDER BY value_num",
)
.await?)
/// Replace the splits with these (id, value, account, extra keys).
async fn replace(f: &Reconciled, splits: &[(Uuid, i64, Uuid, &str)]) -> anyhow::Result<()> {
let plists: String = splits
.iter()
.map(|(id, value, account, fields)| {
format!(
"(:id \"{id}\" :account-id \"{account}\" :commodity-id \"{}\" :value {value} {fields})",
f.commodity
.collect();
let payload = format!("(:transaction-id \"{}\" :splits ({plists}))", f.tx);
run_update_transaction(f.user, Some(payload))
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn a_replaced_reconciled_split_stays_reconciled_dated_and_in_its_lot(
pool: PgPool,
) -> anyhow::Result<()> {
let _guard = server::db::install_test_pool(pool.clone());
let f = reconciled(&pool).await?;
let [(a, a_value, a_account), (b, b_value, b_account)] = f.splits;
replace(
&f,
&[(a, a_value, a_account, ""), (b, b_value, b_account, "")],
let kept = (Some(true), Some(f.date), Some(f.lot));
states(&pool).await?,
[(a, kept.0, kept.1, kept.2), (b, kept.0, kept.1, kept.2)]
async fn given_state_keys_replace_the_stored_values(pool: PgPool) -> anyhow::Result<()> {
&[
(a, a_value, a_account, ":reconciled nil :reconcile-date nil"),
(b, b_value, b_account, ":lot-id nil"),
],
[
(a, Some(false), None, Some(f.lot)),
(b, Some(true), Some(f.date), None)
]
async fn a_split_with_a_new_id_keeps_nothing(pool: PgPool) -> anyhow::Result<()> {
let [(a, a_value, a_account), (_, b_value, b_account)] = f.splits;
let fresh = Uuid::new_v4();
&[(a, a_value, a_account, ""), (fresh, b_value, b_account, "")],
(a, Some(true), Some(f.date), Some(f.lot)),
(fresh, None, None, None)
async fn a_split_moved_to_another_account_keeps_nothing(pool: PgPool) -> anyhow::Result<()> {
&[(a, a_value, b_account, ""), (b, b_value, a_account, "")],
[(a, None, None, None), (b, None, None, None)]
async fn a_changed_amount_keeps_the_lot_but_not_the_reconciliation(
(a, a_value * 2, a_account, ""),
(b, b_value * 2, b_account, ""),
[(a, None, None, Some(f.lot)), (b, None, None, Some(f.lot))]
async fn create_transaction_stores_given_split_state(pool: PgPool) -> anyhow::Result<()> {
let [(_, _, a_account), (_, _, b_account)] = f.splits;
sqlx::query("DELETE FROM splits").execute(&pool).await?;
let payload = format!(
"(:post-date \"2026-03-01T00:00:00Z\" :splits (\
(:account-id \"{a_account}\" :commodity-id \"{c}\" :value -3 :reconciled t \
:reconcile-date \"2026-01-02T03:04:05Z\" :lot-id \"{lot}\") \
(:account-id \"{b_account}\" :commodity-id \"{c}\" :value 3 :RECONCILED :unknown)))",
c = f.commodity,
lot = f.lot
super::run::run_create_transaction(f.user, Some(payload))
let stored: Vec<Fields> = sqlx::query_as(
"SELECT reconcile_state, reconcile_date, lot_id FROM splits ORDER BY value_num",
.fetch_all(&pool)
stored,
[(Some(true), Some(f.date), Some(f.lot)), (None, None, None)]