Lines
98.53 %
Functions
80 %
Branches
100 %
use std::collections::HashMap;
use chrono::Utc;
use finance::split::Split;
use finance::tag::Tag;
use scripting::nomiscript::{Compiler, Reader, SymbolTable};
use sqlx::PgPool;
use supp_macro::local_db_sqlx_test;
use super::*;
use crate::command::script::RunScriptOnAccount;
use crate::command::transaction::CreateTransaction;
use crate::command::{CmdError, CmdResult, FinanceEntity};
use crate::db::install_test_pool;
use crate::lossless::{account, commodity, snapshot};
const TAG_SYNC: &str = include_str!("../../../doc/scripts/tag-sync.nms");
const BOOM_ON_TRIP: &str = r#"
(do ((i 0 (+ i 1)))
((>= i (entity-count)))
(when (and (= (entity-type i) +entity-tag+)
(string= (tag-name i) "trip"))
(error 'boom "no")))
"#;
async fn setup() {}
struct Ledger {
user: User,
account: Uuid,
transactions: Vec<Uuid>,
}
fn compile(source: &str) -> anyhow::Result<Vec<u8>> {
let program = Reader::parse(source).map_err(|err| anyhow::anyhow!("parse: {err}"))?;
let mut symbols = SymbolTable::with_builtins();
Compiler::new()
.compile(&program, &mut symbols)
.map_err(|err| anyhow::anyhow!("compile: {err}"))
fn split(tx: Uuid, account_id: Uuid, commodity_id: Uuid, value_num: i64) -> Split {
Split {
id: Uuid::new_v4(),
tx_id: tx,
account_id,
commodity_id,
value_num,
value_denom: 1,
reconcile_state: None,
reconcile_date: None,
lot_id: None,
/// One user and one transaction on the same account per entry of `trips`,
/// carrying a `trip` transaction tag with that value, or none for `None`.
async fn ledger(pool: &PgPool, trips: &[Option<&str>]) -> anyhow::Result<Ledger> {
let user = Uuid::new_v4();
sqlx::query_file!(
"sql/insert/users/fixture.sql",
user,
format!("u{user}"),
format!("{user}@test.com")
)
.execute(pool)
.await?;
let jpy = commodity(user, "JPY").await?;
let (suica, metro) = (account(user, "Suica").await?, account(user, "Metro").await?);
let mut transactions = Vec::new();
for trip in trips {
let tx = Uuid::new_v4();
let tags: HashMap<String, FinanceEntity> = trip
.iter()
.map(|value| {
let tag = Tag {
tag_name: "trip".to_string(),
tag_value: (*value).to_string(),
description: None,
};
("trip".to_string(), FinanceEntity::Tag(tag))
})
.collect();
CreateTransaction::new()
.user_id(user)
.id(tx)
.post_date(Utc::now())
.enter_date(Utc::now())
.splits(vec![
FinanceEntity::Split(split(tx, suica, jpy, -200)),
FinanceEntity::Split(split(tx, metro, jpy, 200)),
])
.note("fare".to_string())
.tags(tags)
.run()
transactions.push(tx);
Ok(Ledger {
user: User { id: user },
account: suica,
transactions,
fn sorted(mut ids: Vec<Uuid>) -> Vec<Uuid> {
ids.sort();
ids
#[local_db_sqlx_test]
async fn tag_sync_runs_on_every_transaction_and_commits_the_changed(
pool: PgPool,
) -> anyhow::Result<()> {
let _guard = install_test_pool(pool.clone());
let ledger = ledger(&pool, &[Some("japan"), None, Some("peru")]).await?;
let script = ledger.user.create_script(compile(TAG_SYNC)?, None).await?;
let run = run_on_account(&ledger.user, script, ledger.account).await?;
assert_eq!(sorted(run.ran.clone()), sorted(ledger.transactions.clone()));
assert_eq!(
sorted(run.committed),
sorted(vec![ledger.transactions[0], ledger.transactions[2]])
);
assert!(run.failures.is_empty());
async fn the_command_answers_the_same_run_as_the_function(pool: PgPool) -> anyhow::Result<()> {
let ledger = ledger(&pool, &[Some("japan"), None]).await?;
let answer = RunScriptOnAccount::new()
.user_id(ledger.user.id)
.script_id(script)
.account_id(ledger.account)
let again = run_on_account(&ledger.user, script, ledger.account).await?;
let Some(CmdResult::ScriptRun(run)) = answer else {
anyhow::bail!("expected a script run, got {answer:?}");
assert_eq!(sorted(run.ran), sorted(again.ran));
assert_eq!(run.committed, vec![ledger.transactions[0]]);
assert!(again.committed.is_empty(), "the second run changes nothing");
async fn a_missing_script_is_not_found(pool: PgPool) -> anyhow::Result<()> {
let ledger = ledger(&pool, &[Some("japan")]).await?;
.script_id(Uuid::new_v4())
.await;
assert!(
matches!(&answer, Err(CmdError::NotFound(message)) if message == "Script not found"),
"{answer:?}"
async fn a_disabled_script_still_runs(pool: PgPool) -> anyhow::Result<()> {
ledger.user.set_script_enabled(script, false).await?;
assert_eq!(run.committed, ledger.transactions);
async fn a_failure_on_one_transaction_stops_the_run_and_writes_nothing(
let before = snapshot(&pool, ledger.transactions[1]).await?;
let script = ledger
.user
.create_script(compile(BOOM_ON_TRIP)?, None)
assert!(run.committed.is_empty());
assert_eq!(run.failures.len(), 1);
let failure = &run.failures[0];
assert_eq!(failure.transaction_id, ledger.transactions[0]);
assert_eq!(failure.script_id, script);
assert!(!failure.message.is_empty());
assert!(!run.ran.contains(&failure.transaction_id));
assert_eq!(snapshot(&pool, ledger.transactions[1]).await?, before);