Lines
96.94 %
Functions
95.65 %
Branches
100 %
//! `get-transaction-logical` and the per-row `:tags` of the logical payloads.
use finance::{price::Price, split::Split};
use server::command::account::CreateAccount;
use server::command::commodity::CreateCommodity;
use server::command::split::{ListSplits, SetSplitTag};
use server::command::transaction::CreateTransaction;
use server::command::{CmdResult, FinanceEntity};
use sqlx::PgPool;
use uuid::Uuid;
use super::logical_view::run_get_transaction_logical;
use super::run_logical::{run_create_transaction_logical, run_update_transaction_logical};
struct Fixture {
user_id: Uuid,
usd: Uuid,
eur: Uuid,
assets: Uuid,
expenses: Uuid,
}
async fn fixture(pool: &PgPool) -> anyhow::Result<Fixture> {
let user_id = Uuid::new_v4();
seed_user(pool, user_id).await?;
Ok(Fixture {
user_id,
usd: seed_commodity(user_id, "USD").await?,
eur: seed_commodity(user_id, "EUR").await?,
assets: seed_account(user_id, "Assets").await?,
expenses: seed_account(user_id, "Expenses").await?,
})
async fn seed_user(pool: &PgPool, user_id: Uuid) -> anyhow::Result<()> {
sqlx::query(
"INSERT INTO users \
(id, user_name, email, photo, verified, user_password, user_role, database_name, created_at) \
VALUES ($1, 'Test', 'test@test.com', 'x', false, 'pw', 'user', 'db', NOW())",
)
.bind(user_id)
.execute(pool)
.await?;
Ok(())
async fn seed_commodity(user_id: Uuid, symbol: &str) -> anyhow::Result<Uuid> {
match CreateCommodity::new()
.symbol(symbol.to_string())
.name(symbol.to_string())
.user_id(user_id)
.run()
.await?
{
Some(CmdResult::String(id)) => Ok(Uuid::parse_str(&id)?),
other => anyhow::bail!("unexpected CreateCommodity result: {other:?}"),
async fn seed_account(user_id: Uuid, name: &str) -> anyhow::Result<Uuid> {
match CreateAccount::new()
.name(name.to_string())
Some(CmdResult::Entity(FinanceEntity::Account(a))) => Ok(a.id),
other => anyhow::bail!("unexpected CreateAccount result: {other:?}"),
fn row(f: &Fixture, tags: &str) -> String {
let (a, b, c) = (f.assets, f.expenses, f.usd);
format!(
"(:from \"{a}\" :to \"{b}\" :from-commodity \"{c}\" :to-commodity \"{c}\" :value 100 {tags})"
async fn create(f: &Fixture, payload: String) -> anyhow::Result<String> {
run_create_transaction_logical(f.user_id, Some(payload))
.await
.map_err(|e| anyhow::anyhow!("{e}"))
async fn update(f: &Fixture, payload: String) -> anyhow::Result<String> {
run_update_transaction_logical(f.user_id, Some(payload))
async fn logical(user_id: Uuid, id: &str) -> anyhow::Result<String> {
run_get_transaction_logical(user_id, Some(id.to_string()))
const MEMO: &str = ":tags ((:name \"memo\" :value \"lunch \\\"x\\\"\" :description \"d\"))";
async fn tagged(f: &Fixture) -> anyhow::Result<String> {
create(f, format!("(:note \"n\" :splits ({}))", row(f, MEMO))).await
#[sqlx::test(migrator = "server::db::MIGRATOR")]
async fn create_with_row_tags_reads_back_on_the_row(pool: PgPool) -> anyhow::Result<()> {
let _guard = server::db::install_test_pool(pool.clone());
let f = fixture(&pool).await?;
let id = tagged(&f).await?;
let plist = logical(f.user_id, &id).await?;
assert!(
plist.starts_with(&format!("(:transaction-id \"{id}\" :date \"")),
"{plist}"
);
assert!(plist.contains(" :note \"n\" :splits ((:from \""), "{plist}");
plist.contains(
" :value 100 :tags ((:name \"memo\" :value \"lunch \\\"x\\\"\" :description \"d\"))))"
),
assert!(!plist.contains(":to-amount"), "{plist}");
async fn update_without_row_tags_replaces_them(pool: PgPool) -> anyhow::Result<()> {
update(
&f,
format!("(:transaction-id \"{id}\" :splits ({}))", row(&f, "")),
assert!(!logical(f.user_id, &id).await?.contains(":tags"));
async fn update_with_the_returned_plist_keeps_the_tags(pool: PgPool) -> anyhow::Result<()> {
let before = logical(f.user_id, &id).await?;
update(&f, before.clone()).await?;
assert_eq!(logical(f.user_id, &id).await?, before);
async fn cross_currency_round_trips(pool: PgPool) -> anyhow::Result<()> {
let (a, b, usd, eur) = (f.assets, f.expenses, f.usd, f.eur);
let payload = format!(
"(:splits ((:from \"{a}\" :to \"{b}\" :from-commodity \"{usd}\" :to-commodity \"{eur}\" \
:value 100/3 :to-amount 92 :tags ((:name \"k\" :value \"v\")))))"
let id = create(&f, payload).await?;
before.contains(":value 100/3 :to-amount 92 :tags ((:name \"k\" :value \"v\"))"),
"{before}"
async fn clearing_the_note_removes_it(pool: PgPool) -> anyhow::Result<()> {
"(:transaction-id \"{id}\" :note \"\" :splits ({}))",
row(&f, MEMO)
assert!(!logical(f.user_id, &id).await?.contains(":note"));
async fn unpairable_transaction_is_refused(pool: PgPool) -> anyhow::Result<()> {
let tx_id = Uuid::new_v4();
let leg = |account_id: Uuid, value_num: i64| {
FinanceEntity::Split(Split {
id: Uuid::new_v4(),
tx_id,
account_id,
commodity_id: f.usd,
value_num,
value_denom: 1,
reconcile_state: None,
reconcile_date: None,
lot_id: None,
};
CreateTransaction::new()
.user_id(f.user_id)
.id(tx_id)
.post_date(chrono::Utc::now())
.enter_date(chrono::Utc::now())
.splits(vec![
leg(f.assets, -100),
leg(f.expenses, 60),
leg(f.expenses, 40),
])
let err = run_get_transaction_logical(f.user_id, Some(tx_id.to_string()))
.unwrap_err();
assert_eq!(
crate::host_failure::condition_code(&err),
Some(crate::envelope::ErrorCode::ARGS)
assert!(err.to_string().contains("paired"), "{err}");
async fn per_leg_tags_read_back_on_their_leg(pool: PgPool) -> anyhow::Result<()> {
let tags = " :tags ((:name \"s\" :value \"1\")) :from-tags ((:name \"cat\" :value \"a\")) \
:to-tags ((:name \"cat\" :value \"b\"))";
let id = create(&f, format!("(:note \"n\" :splits ({}))", row(&f, tags))).await?;
assert!(plist.contains(&format!("{tags})")), "{plist}");
update(&f, plist.clone()).await?;
assert_eq!(logical(f.user_id, &id).await?, plist);
async fn a_tag_on_one_stored_leg_is_raised_to_that_leg(pool: PgPool) -> anyhow::Result<()> {
let id = create(&f, format!("(:splits ({}))", row(&f, ""))).await?;
let Some(CmdResult::TaggedSplits { entities }) = ListSplits::new()
.transaction(Uuid::parse_str(&id)?)
else {
anyhow::bail!("no splits");
let Some((split, _)) = entities.into_iter().next() else {
anyhow::bail!("no split");
SetSplitTag::new()
.split_id(split.id)
.tag_name("memo".to_string())
.tag_value("other".to_string())
let key = match split.value_num < 0 {
true => "from-tags",
false => "to-tags",
plist.contains(&format!(" :{key} ((:name \"memo\" :value \"other\")))")),
async fn unknown_transaction_is_the_not_found_condition(pool: PgPool) -> anyhow::Result<()> {
let err = run_get_transaction_logical(f.user_id, Some(Uuid::new_v4().to_string()))
Some(crate::envelope::ErrorCode::NOT_FOUND)
crate::host_failure::condition_text(&err),
Some("Transaction not found".to_string())
async fn blank_row_tag_is_rejected(pool: PgPool) -> anyhow::Result<()> {
let tags = ":tags ((:name \"memo\" :value \" \"))";
create(&f, format!("(:splits ({}))", row(&f, tags)))
.is_err()
async fn reconciled_split_is_refused(pool: PgPool) -> anyhow::Result<()> {
let leg = |account_id: Uuid, value_num: i64, reconciled: bool| {
reconcile_state: reconciled.then_some(true),
reconcile_date: reconciled.then(chrono::Utc::now),
.splits(vec![leg(f.assets, -100, true), leg(f.expenses, 100, false)])
let err = logical(f.user_id, &tx_id.to_string()).await.unwrap_err();
err.to_string().contains("reconciliation or lot data"),
"{err}"
async fn mismatched_price_rate_is_refused(pool: PgPool) -> anyhow::Result<()> {
let leg = |account_id: Uuid, commodity_id: Uuid, value_num: i64| Split {
commodity_id,
let from = leg(f.assets, f.usd, -100);
let to = leg(f.expenses, f.eur, 60);
let price = Price {
date: chrono::Utc::now(),
commodity_id: f.eur,
currency_id: f.usd,
commodity_split: Some(to.id),
currency_split: Some(from.id),
value_num: 5,
value_denom: 3,
.splits(vec![FinanceEntity::Split(from), FinanceEntity::Split(to)])
.prices(vec![FinanceEntity::Price(price)])
logical(f.user_id, &tx_id.to_string()).await?;
sqlx::query("UPDATE prices SET value_num = 1, value_denom = 1")
.execute(&pool)
assert!(err.to_string().contains("exchange rate"), "{err}");
async fn a_padded_stored_note_name_is_the_note(pool: PgPool) -> anyhow::Result<()> {
sqlx::query("UPDATE tags SET tag_name = 'note ' WHERE tag_name = 'note'")
assert!(plist.contains(" :note \"n\" :splits"), "{plist}");