1
use super::*;
2

            
3
const GROCERIES_SCRIPT_WASM: &[u8] =
4
    include_bytes!("../../../../web/static/wasm/groceries_markup.wasm");
5

            
6
const TAG_SYNC_SCRIPT_WASM: &[u8] = include_bytes!("../../../../web/static/wasm/tag_sync.wasm");
7

            
8
#[local_db_sqlx_test]
9
async fn test_create_transaction_with_all_scripts_completes(pool: PgPool) -> anyhow::Result<()> {
10
    let user = USER.get().unwrap();
11
    user.commit()
12
        .await
13
        .expect("Failed to commit user to database");
14

            
15
    let mut conn = user.get_connection().await?;
16

            
17
    let groceries_script_id = user
18
        .create_script(GROCERIES_SCRIPT_WASM.to_vec(), None)
19
        .await?;
20
    let tag_sync_script_id = user
21
        .create_script(TAG_SYNC_SCRIPT_WASM.to_vec(), None)
22
        .await?;
23

            
24
    let commodity_result = CreateCommodity::new()
25
        .symbol("TST".to_string())
26
        .name("Test Commodity".to_string())
27
        .user_id(user.id)
28
        .run()
29
        .await?;
30

            
31
    let commodity_id = if let Some(CmdResult::String(id)) = commodity_result {
32
        uuid::Uuid::parse_str(&id)?
33
    } else {
34
        panic!("Expected commodity ID string result");
35
    };
36

            
37
    let account1 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
38
        CreateAccount::new()
39
            .name("Account 1".to_string())
40
            .user_id(user.id)
41
            .run()
42
            .await?
43
    {
44
        account
45
    } else {
46
        panic!("Expected account entity result");
47
    };
48

            
49
    let account2 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
50
        CreateAccount::new()
51
            .name("Account 2".to_string())
52
            .user_id(user.id)
53
            .run()
54
            .await?
55
    {
56
        account
57
    } else {
58
        panic!("Expected account entity result");
59
    };
60

            
61
    let tx_id = Uuid::new_v4();
62
    let split1_id = Uuid::new_v4();
63
    let split2_id = Uuid::new_v4();
64

            
65
    let split1 = Split {
66
        id: split1_id,
67
        tx_id,
68
        account_id: account1.id,
69
        commodity_id,
70
        value_num: -5000,
71
        value_denom: 100,
72
        reconcile_state: None,
73
        reconcile_date: None,
74
        lot_id: None,
75
    };
76

            
77
    let split2 = Split {
78
        id: split2_id,
79
        tx_id,
80
        account_id: account2.id,
81
        commodity_id,
82
        value_num: 5000,
83
        value_denom: 100,
84
        reconcile_state: None,
85
        reconcile_date: None,
86
        lot_id: None,
87
    };
88

            
89
    let splits = vec![FinanceEntity::Split(split1), FinanceEntity::Split(split2)];
90
    let now = Utc::now();
91

            
92
    // A liveness guard, not a performance budget: it exists so a script that
93
    // deadlocks fails the suite instead of hanging it. The bound has to hold
94
    // on the slowest machine that runs this, which is a 4-vCPU CI node under
95
    // -Cinstrument-coverage executing two wasm scripts — 10s failed there
96
    // while passing everywhere else, which is a flaky test, not a finding.
97
    let result = tokio::time::timeout(
98
        std::time::Duration::from_secs(120),
99
        CreateTransaction::new()
100
            .user_id(user.id)
101
            .splits(splits)
102
            .id(tx_id)
103
            .post_date(now)
104
            .enter_date(now)
105
            .note("groceries".to_string())
106
            .run(),
107
    )
108
    .await;
109

            
110
    assert!(
111
        result.is_ok(),
112
        "Transaction creation with scripts hung (>120s) — a script or lock is stuck"
113
    );
114
    result.unwrap()?;
115

            
116
    let split1_tags = sqlx::query_file!("sql/select/tags/by_split.sql", split1_id)
117
        .fetch_all(&mut *conn)
118
        .await?;
119

            
120
    let split1_has_category = split1_tags
121
        .iter()
122
1
        .any(|t| t.tag_name == "category" && t.tag_value == "groceries");
123
    assert!(
124
        split1_has_category,
125
        "Split 1 should have category=groceries tag from groceries script"
126
    );
127

            
128
    user.delete_script(groceries_script_id).await?;
129
    user.delete_script(tag_sync_script_id).await?;
130
}
131

            
132
#[local_db_sqlx_test]
133
async fn test_create_transaction_with_script(pool: PgPool) -> anyhow::Result<()> {
134
    let user = USER.get().unwrap();
135
    user.commit()
136
        .await
137
        .expect("Failed to commit user to database");
138

            
139
    let mut conn = user.get_connection().await?;
140

            
141
    // Insert the groceries script into the database
142
    let script_id = user
143
        .create_script(GROCERIES_SCRIPT_WASM.to_vec(), None)
144
        .await?;
145

            
146
    // Create commodity and accounts
147
    let commodity_result = CreateCommodity::new()
148
        .symbol("TST".to_string())
149
        .name("Test Commodity".to_string())
150
        .user_id(user.id)
151
        .run()
152
        .await?;
153

            
154
    let commodity_id = if let Some(CmdResult::String(id)) = commodity_result {
155
        uuid::Uuid::parse_str(&id)?
156
    } else {
157
        panic!("Expected commodity ID string result");
158
    };
159

            
160
    let account1 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
161
        CreateAccount::new()
162
            .name("Account 1".to_string())
163
            .user_id(user.id)
164
            .run()
165
            .await?
166
    {
167
        account
168
    } else {
169
        panic!("Expected account entity result");
170
    };
171

            
172
    let account2 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
173
        CreateAccount::new()
174
            .name("Account 2".to_string())
175
            .user_id(user.id)
176
            .run()
177
            .await?
178
    {
179
        account
180
    } else {
181
        panic!("Expected account entity result");
182
    };
183

            
184
    let tx_id = Uuid::new_v4();
185
    let split1_id = Uuid::new_v4();
186
    let split2_id = Uuid::new_v4();
187

            
188
    let split1 = Split {
189
        id: split1_id,
190
        tx_id,
191
        account_id: account1.id,
192
        commodity_id,
193
        value_num: -5000,
194
        value_denom: 100,
195
        reconcile_state: None,
196
        reconcile_date: None,
197
        lot_id: None,
198
    };
199

            
200
    let split2 = Split {
201
        id: split2_id,
202
        tx_id,
203
        account_id: account2.id,
204
        commodity_id,
205
        value_num: 5000,
206
        value_denom: 100,
207
        reconcile_state: None,
208
        reconcile_date: None,
209
        lot_id: None,
210
    };
211

            
212
    let splits = vec![FinanceEntity::Split(split1), FinanceEntity::Split(split2)];
213
    let now = Utc::now();
214

            
215
    // Create transaction with note="groceries" - this should trigger the script
216
    CreateTransaction::new()
217
        .user_id(user.id)
218
        .splits(splits)
219
        .id(tx_id)
220
        .post_date(now)
221
        .enter_date(now)
222
        .note("groceries".to_string())
223
        .run()
224
        .await?;
225

            
226
    // Verify that the script added "category=groceries" tags to both splits
227
    let split1_tags = sqlx::query_file!("sql/select/tags/by_split.sql", split1_id)
228
        .fetch_all(&mut *conn)
229
        .await?;
230

            
231
    let split2_tags = sqlx::query_file!("sql/select/tags/by_split.sql", split2_id)
232
        .fetch_all(&mut *conn)
233
        .await?;
234

            
235
    // Check split1 has the category tag
236
    let split1_has_category = split1_tags
237
        .iter()
238
1
        .any(|t| t.tag_name == "category" && t.tag_value == "groceries");
239
    assert!(
240
        split1_has_category,
241
        "Split 1 should have category=groceries tag from script. Tags: {:?}",
242
        split1_tags
243
            .iter()
244
            .map(|t| format!("{}={}", t.tag_name, t.tag_value))
245
            .collect::<Vec<_>>()
246
    );
247

            
248
    // Check split2 has the category tag
249
    let split2_has_category = split2_tags
250
        .iter()
251
1
        .any(|t| t.tag_name == "category" && t.tag_value == "groceries");
252
    assert!(
253
        split2_has_category,
254
        "Split 2 should have category=groceries tag from script. Tags: {:?}",
255
        split2_tags
256
            .iter()
257
            .map(|t| format!("{}={}", t.tag_name, t.tag_value))
258
            .collect::<Vec<_>>()
259
    );
260

            
261
    // Clean up the script
262
    user.delete_script(script_id).await?;
263
}
264

            
265
#[local_db_sqlx_test]
266
async fn test_create_transaction_script_skips_non_matching(pool: PgPool) -> anyhow::Result<()> {
267
    let user = USER.get().unwrap();
268
    user.commit()
269
        .await
270
        .expect("Failed to commit user to database");
271

            
272
    let mut conn = user.get_connection().await?;
273

            
274
    // Insert the groceries script into the database
275
    let script_id = user
276
        .create_script(GROCERIES_SCRIPT_WASM.to_vec(), None)
277
        .await?;
278

            
279
    // Create commodity and accounts
280
    let commodity_result = CreateCommodity::new()
281
        .symbol("TST".to_string())
282
        .name("Test Commodity".to_string())
283
        .user_id(user.id)
284
        .run()
285
        .await?;
286

            
287
    let commodity_id = if let Some(CmdResult::String(id)) = commodity_result {
288
        uuid::Uuid::parse_str(&id)?
289
    } else {
290
        panic!("Expected commodity ID string result");
291
    };
292

            
293
    let account1 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
294
        CreateAccount::new()
295
            .name("Account 1".to_string())
296
            .user_id(user.id)
297
            .run()
298
            .await?
299
    {
300
        account
301
    } else {
302
        panic!("Expected account entity result");
303
    };
304

            
305
    let account2 = if let Some(CmdResult::Entity(FinanceEntity::Account(account))) =
306
        CreateAccount::new()
307
            .name("Account 2".to_string())
308
            .user_id(user.id)
309
            .run()
310
            .await?
311
    {
312
        account
313
    } else {
314
        panic!("Expected account entity result");
315
    };
316

            
317
    let tx_id = Uuid::new_v4();
318
    let split1_id = Uuid::new_v4();
319
    let split2_id = Uuid::new_v4();
320

            
321
    let split1 = Split {
322
        id: split1_id,
323
        tx_id,
324
        account_id: account1.id,
325
        commodity_id,
326
        value_num: -5000,
327
        value_denom: 100,
328
        reconcile_state: None,
329
        reconcile_date: None,
330
        lot_id: None,
331
    };
332

            
333
    let split2 = Split {
334
        id: split2_id,
335
        tx_id,
336
        account_id: account2.id,
337
        commodity_id,
338
        value_num: 5000,
339
        value_denom: 100,
340
        reconcile_state: None,
341
        reconcile_date: None,
342
        lot_id: None,
343
    };
344

            
345
    let splits = vec![FinanceEntity::Split(split1), FinanceEntity::Split(split2)];
346
    let now = Utc::now();
347

            
348
    // Create transaction with note="other" - this should NOT trigger the script
349
    CreateTransaction::new()
350
        .user_id(user.id)
351
        .splits(splits)
352
        .id(tx_id)
353
        .post_date(now)
354
        .enter_date(now)
355
        .note("other".to_string())
356
        .run()
357
        .await?;
358

            
359
    // Verify that the script did NOT add any tags to splits
360
    let split1_tags = sqlx::query_file!("sql/select/tags/by_split.sql", split1_id)
361
        .fetch_all(&mut *conn)
362
        .await?;
363

            
364
    let split2_tags = sqlx::query_file!("sql/select/tags/by_split.sql", split2_id)
365
        .fetch_all(&mut *conn)
366
        .await?;
367

            
368
    // Neither split should have the category tag
369
    let split1_has_category = split1_tags
370
        .iter()
371
        .any(|t| t.tag_name == "category" && t.tag_value == "groceries");
372
    assert!(
373
        !split1_has_category,
374
        "Split 1 should NOT have category tag for non-groceries transaction"
375
    );
376

            
377
    let split2_has_category = split2_tags
378
        .iter()
379
        .any(|t| t.tag_name == "category" && t.tag_value == "groceries");
380
    assert!(
381
        !split2_has_category,
382
        "Split 2 should NOT have category tag for non-groceries transaction"
383
    );
384

            
385
    // Clean up the script
386
    user.delete_script(script_id).await?;
387
}