1
use std::collections::HashMap;
2

            
3
use chrono::Utc;
4
use finance::split::Split;
5
use finance::tag::Tag;
6
use scripting::nomiscript::{Compiler, Reader, SymbolTable};
7
use sqlx::PgPool;
8
use supp_macro::local_db_sqlx_test;
9

            
10
use super::*;
11
use crate::command::script::RunScriptOnAccount;
12
use crate::command::transaction::CreateTransaction;
13
use crate::command::{CmdError, CmdResult, FinanceEntity};
14
use crate::db::install_test_pool;
15
use crate::lossless::{account, commodity, snapshot};
16

            
17
const TAG_SYNC: &str = include_str!("../../../doc/scripts/tag-sync.nms");
18

            
19
const BOOM_ON_TRIP: &str = r#"
20
(do ((i 0 (+ i 1)))
21
    ((>= i (entity-count)))
22
    (when (and (= (entity-type i) +entity-tag+)
23
               (string= (tag-name i) "trip"))
24
        (error 'boom "no")))
25
"#;
26

            
27
5
async fn setup() {}
28

            
29
struct Ledger {
30
    user: User,
31
    account: Uuid,
32
    transactions: Vec<Uuid>,
33
}
34

            
35
4
fn compile(source: &str) -> anyhow::Result<Vec<u8>> {
36
4
    let program = Reader::parse(source).map_err(|err| anyhow::anyhow!("parse: {err}"))?;
37
4
    let mut symbols = SymbolTable::with_builtins();
38
4
    Compiler::new()
39
4
        .compile(&program, &mut symbols)
40
        .map_err(|err| anyhow::anyhow!("compile: {err}"))
41
4
}
42

            
43
18
fn split(tx: Uuid, account_id: Uuid, commodity_id: Uuid, value_num: i64) -> Split {
44
18
    Split {
45
18
        id: Uuid::new_v4(),
46
18
        tx_id: tx,
47
18
        account_id,
48
18
        commodity_id,
49
18
        value_num,
50
18
        value_denom: 1,
51
18
        reconcile_state: None,
52
18
        reconcile_date: None,
53
18
        lot_id: None,
54
18
    }
55
18
}
56

            
57
/// One user and one transaction on the same account per entry of `trips`,
58
/// carrying a `trip` transaction tag with that value, or none for `None`.
59
5
async fn ledger(pool: &PgPool, trips: &[Option<&str>]) -> anyhow::Result<Ledger> {
60
5
    let user = Uuid::new_v4();
61
5
    sqlx::query_file!(
62
        "sql/insert/users/fixture.sql",
63
        user,
64
5
        format!("u{user}"),
65
5
        format!("{user}@test.com")
66
    )
67
5
    .execute(pool)
68
5
    .await?;
69
5
    let jpy = commodity(user, "JPY").await?;
70
5
    let (suica, metro) = (account(user, "Suica").await?, account(user, "Metro").await?);
71
5
    let mut transactions = Vec::new();
72
5
    for trip in trips {
73
9
        let tx = Uuid::new_v4();
74
9
        let tags: HashMap<String, FinanceEntity> = trip
75
9
            .iter()
76
6
            .map(|value| {
77
6
                let tag = Tag {
78
6
                    id: Uuid::new_v4(),
79
6
                    tag_name: "trip".to_string(),
80
6
                    tag_value: (*value).to_string(),
81
6
                    description: None,
82
6
                };
83
6
                ("trip".to_string(), FinanceEntity::Tag(tag))
84
6
            })
85
            .collect();
86
9
        CreateTransaction::new()
87
9
            .user_id(user)
88
9
            .id(tx)
89
9
            .post_date(Utc::now())
90
9
            .enter_date(Utc::now())
91
9
            .splits(vec![
92
9
                FinanceEntity::Split(split(tx, suica, jpy, -200)),
93
9
                FinanceEntity::Split(split(tx, metro, jpy, 200)),
94
9
            ])
95
9
            .note("fare".to_string())
96
9
            .tags(tags)
97
9
            .run()
98
9
            .await?;
99
9
        transactions.push(tx);
100
    }
101
5
    Ok(Ledger {
102
5
        user: User { id: user },
103
5
        account: suica,
104
5
        transactions,
105
5
    })
106
5
}
107

            
108
6
fn sorted(mut ids: Vec<Uuid>) -> Vec<Uuid> {
109
6
    ids.sort();
110
6
    ids
111
6
}
112

            
113
#[local_db_sqlx_test]
114
async fn tag_sync_runs_on_every_transaction_and_commits_the_changed(
115
    pool: PgPool,
116
) -> anyhow::Result<()> {
117
    let _guard = install_test_pool(pool.clone());
118
    let ledger = ledger(&pool, &[Some("japan"), None, Some("peru")]).await?;
119
    let script = ledger.user.create_script(compile(TAG_SYNC)?, None).await?;
120

            
121
    let run = run_on_account(&ledger.user, script, ledger.account).await?;
122

            
123
    assert_eq!(sorted(run.ran.clone()), sorted(ledger.transactions.clone()));
124
    assert_eq!(
125
        sorted(run.committed),
126
        sorted(vec![ledger.transactions[0], ledger.transactions[2]])
127
    );
128
    assert!(run.failures.is_empty());
129
}
130

            
131
#[local_db_sqlx_test]
132
async fn the_command_answers_the_same_run_as_the_function(pool: PgPool) -> anyhow::Result<()> {
133
    let _guard = install_test_pool(pool.clone());
134
    let ledger = ledger(&pool, &[Some("japan"), None]).await?;
135
    let script = ledger.user.create_script(compile(TAG_SYNC)?, None).await?;
136

            
137
    let answer = RunScriptOnAccount::new()
138
        .user_id(ledger.user.id)
139
        .script_id(script)
140
        .account_id(ledger.account)
141
        .run()
142
        .await?;
143
    let again = run_on_account(&ledger.user, script, ledger.account).await?;
144

            
145
    let Some(CmdResult::ScriptRun(run)) = answer else {
146
        anyhow::bail!("expected a script run, got {answer:?}");
147
    };
148
    assert_eq!(sorted(run.ran), sorted(again.ran));
149
    assert_eq!(run.committed, vec![ledger.transactions[0]]);
150
    assert!(again.committed.is_empty(), "the second run changes nothing");
151
}
152

            
153
#[local_db_sqlx_test]
154
async fn a_missing_script_is_not_found(pool: PgPool) -> anyhow::Result<()> {
155
    let _guard = install_test_pool(pool.clone());
156
    let ledger = ledger(&pool, &[Some("japan")]).await?;
157

            
158
    let answer = RunScriptOnAccount::new()
159
        .user_id(ledger.user.id)
160
        .script_id(Uuid::new_v4())
161
        .account_id(ledger.account)
162
        .run()
163
        .await;
164

            
165
    assert!(
166
        matches!(&answer, Err(CmdError::NotFound(message)) if message == "Script not found"),
167
        "{answer:?}"
168
    );
169
}
170

            
171
#[local_db_sqlx_test]
172
async fn a_disabled_script_still_runs(pool: PgPool) -> anyhow::Result<()> {
173
    let _guard = install_test_pool(pool.clone());
174
    let ledger = ledger(&pool, &[Some("japan")]).await?;
175
    let script = ledger.user.create_script(compile(TAG_SYNC)?, None).await?;
176
    ledger.user.set_script_enabled(script, false).await?;
177

            
178
    let run = run_on_account(&ledger.user, script, ledger.account).await?;
179

            
180
    assert_eq!(run.committed, ledger.transactions);
181
}
182

            
183
#[local_db_sqlx_test]
184
async fn a_failure_on_one_transaction_stops_the_run_and_writes_nothing(
185
    pool: PgPool,
186
) -> anyhow::Result<()> {
187
    let _guard = install_test_pool(pool.clone());
188
    let ledger = ledger(&pool, &[Some("japan"), None]).await?;
189
    let before = snapshot(&pool, ledger.transactions[1]).await?;
190
    let script = ledger
191
        .user
192
        .create_script(compile(BOOM_ON_TRIP)?, None)
193
        .await?;
194

            
195
    let run = run_on_account(&ledger.user, script, ledger.account).await?;
196

            
197
    assert!(run.committed.is_empty());
198
    assert_eq!(run.failures.len(), 1);
199
    let failure = &run.failures[0];
200
    assert_eq!(failure.transaction_id, ledger.transactions[0]);
201
    assert_eq!(failure.script_id, script);
202
    assert!(!failure.message.is_empty());
203
    assert!(!run.ran.contains(&failure.transaction_id));
204
    assert_eq!(snapshot(&pool, ledger.transactions[1]).await?, before);
205
}