1
use super::wire::{
2
    IndexTable, TagLink, TagLinks, apply_parsed_entities, millis_to_datetime, serialize_state,
3
};
4
use super::*;
5
use finance::transaction::TransactionBuilder;
6
use scripting::{EntityData, EntityType, Operation, ParsedEntity};
7
use sqlx::types::chrono::Local;
8

            
9
#[test]
10
1
fn test_transaction_state_new() {
11
1
    let tx = TransactionBuilder::new()
12
1
        .id(Uuid::new_v4())
13
1
        .post_date(Local::now().into())
14
1
        .enter_date(Local::now().into())
15
1
        .build()
16
1
        .unwrap();
17

            
18
1
    let state = TransactionState::new(tx);
19
1
    assert!(state.splits.is_empty());
20
1
    assert!(state.transaction_tags.is_empty());
21
1
    assert!(state.split_tags.is_empty());
22
1
    assert!(state.prices.is_empty());
23
1
}
24

            
25
#[test]
26
1
fn test_serialize_empty_state() {
27
1
    let tx = TransactionBuilder::new()
28
1
        .id(Uuid::new_v4())
29
1
        .post_date(Local::now().into())
30
1
        .enter_date(Local::now().into())
31
1
        .build()
32
1
        .unwrap();
33

            
34
1
    let state = TransactionState::new(tx);
35
1
    let (bytes, index_table, _) = serialize_state(&state);
36
1
    assert!(!bytes.is_empty());
37
1
    assert!(
38
1
        index_table.contains_key(&0),
39
        "transaction missing at index 0"
40
    );
41
1
}
42

            
43
#[test]
44
1
fn test_apply_tag_to_transaction() {
45
1
    let tx_id = Uuid::new_v4();
46
1
    let tx = TransactionBuilder::new()
47
1
        .id(tx_id)
48
1
        .post_date(Local::now().into())
49
1
        .enter_date(Local::now().into())
50
1
        .build()
51
1
        .unwrap();
52

            
53
1
    let mut state = TransactionState::new(tx);
54
1
    let mut index_table = IndexTable::new();
55
1
    index_table.insert(0, (EntityType::Transaction, tx_id));
56

            
57
1
    let tag_entity = ParsedEntity {
58
1
        entity_type: EntityType::Tag,
59
1
        operation: Operation::Create,
60
1
        flags: 0,
61
1
        id: *Uuid::new_v4().as_bytes(),
62
1
        parent_idx: 0, // Points to transaction at index 0
63
1
        data: EntityData::Tag {
64
1
            name: "category".to_string(),
65
1
            value: "groceries".to_string(),
66
1
        },
67
1
    };
68

            
69
1
    apply_parsed_entities(
70
1
        &mut state,
71
1
        vec![tag_entity],
72
1
        &mut index_table,
73
1
        &TagLinks::new(),
74
1
    )
75
1
    .unwrap();
76
1
    assert_eq!(state.transaction_tags.len(), 1);
77
1
    assert_eq!(state.transaction_tags[0].tag_name, "category");
78
1
    assert_eq!(state.transaction_tags[0].tag_value, "groceries");
79
1
}
80

            
81
#[test]
82
1
fn test_apply_tag_to_split() {
83
1
    let tx_id = Uuid::new_v4();
84
1
    let split_id = Uuid::new_v4();
85
1
    let tx = TransactionBuilder::new()
86
1
        .id(tx_id)
87
1
        .post_date(Local::now().into())
88
1
        .enter_date(Local::now().into())
89
1
        .build()
90
1
        .unwrap();
91

            
92
1
    let split = Split {
93
1
        id: split_id,
94
1
        tx_id,
95
1
        account_id: Uuid::new_v4(),
96
1
        commodity_id: Uuid::new_v4(),
97
1
        value_num: 100,
98
1
        value_denom: 1,
99
1
        reconcile_state: None,
100
1
        reconcile_date: None,
101
1
        lot_id: None,
102
1
    };
103

            
104
1
    let mut state = TransactionState::new(tx).with(vec![FinanceEntity::Split(split)]);
105
1
    let mut index_table = IndexTable::new();
106
1
    index_table.insert(0, (EntityType::Transaction, tx_id));
107
1
    index_table.insert(1, (EntityType::Split, split_id));
108

            
109
1
    let tag_entity = ParsedEntity {
110
1
        entity_type: EntityType::Tag,
111
1
        operation: Operation::Create,
112
1
        flags: 0,
113
1
        id: *Uuid::new_v4().as_bytes(),
114
1
        parent_idx: 1, // Points to split at index 1
115
1
        data: EntityData::Tag {
116
1
            name: "category".to_string(),
117
1
            value: "groceries".to_string(),
118
1
        },
119
1
    };
120

            
121
1
    apply_parsed_entities(
122
1
        &mut state,
123
1
        vec![tag_entity],
124
1
        &mut index_table,
125
1
        &TagLinks::new(),
126
1
    )
127
1
    .unwrap();
128
1
    assert_eq!(state.split_tags.len(), 1);
129
1
    assert_eq!(state.split_tags[0].0, split_id);
130
1
    assert_eq!(state.split_tags[0].1.tag_name, "category");
131
1
    assert_eq!(state.split_tags[0].1.tag_value, "groceries");
132
1
}
133

            
134
#[test]
135
1
fn test_serialize_state_with_split_tags() {
136
1
    let tx_id = Uuid::new_v4();
137
1
    let split_id = Uuid::new_v4();
138
1
    let tx = TransactionBuilder::new()
139
1
        .id(tx_id)
140
1
        .post_date(Local::now().into())
141
1
        .enter_date(Local::now().into())
142
1
        .build()
143
1
        .unwrap();
144

            
145
1
    let split = Split {
146
1
        id: split_id,
147
1
        tx_id,
148
1
        account_id: Uuid::new_v4(),
149
1
        commodity_id: Uuid::new_v4(),
150
1
        value_num: 100,
151
1
        value_denom: 1,
152
1
        reconcile_state: None,
153
1
        reconcile_date: None,
154
1
        lot_id: None,
155
1
    };
156

            
157
1
    let tag = Tag {
158
1
        id: Uuid::new_v4(),
159
1
        tag_name: "category".to_string(),
160
1
        tag_value: "food".to_string(),
161
1
        description: None,
162
1
    };
163

            
164
1
    let state = TransactionState::new(tx)
165
1
        .with(vec![FinanceEntity::Split(split)])
166
1
        .with_split_tags(vec![(split_id, tag)]);
167

            
168
1
    assert_eq!(state.split_tags.len(), 1);
169
1
    assert_eq!(state.split_tags[0].0, split_id);
170

            
171
1
    let (bytes, index_table, _) = serialize_state(&state);
172
1
    assert!(!bytes.is_empty());
173
1
    assert_eq!(index_table.len(), 2); // transaction + split
174
1
    assert_eq!(index_table.get(&1).unwrap(), &(EntityType::Split, split_id));
175
1
}
176

            
177
#[test]
178
1
fn test_millis_to_datetime() {
179
1
    let dt = millis_to_datetime(1704067200000);
180
1
    assert_eq!(dt.timestamp(), 1704067200);
181
1
}
182

            
183
#[test]
184
1
fn test_tag_sync_copies_split_tags_to_transaction() {
185
    const TAG_SYNC_WASM: &[u8] = include_bytes!("../../../web/static/wasm/tag_sync.wasm");
186

            
187
1
    let tx_id = Uuid::new_v4();
188
1
    let split1_id = Uuid::new_v4();
189
1
    let split2_id = Uuid::new_v4();
190
1
    let commodity_id = Uuid::new_v4();
191

            
192
1
    let tx = TransactionBuilder::new()
193
1
        .id(tx_id)
194
1
        .post_date(Local::now().into())
195
1
        .enter_date(Local::now().into())
196
1
        .build()
197
1
        .unwrap();
198

            
199
1
    let split1 = Split {
200
1
        id: split1_id,
201
1
        tx_id,
202
1
        account_id: Uuid::new_v4(),
203
1
        commodity_id,
204
1
        value_num: -5000,
205
1
        value_denom: 100,
206
1
        reconcile_state: None,
207
1
        reconcile_date: None,
208
1
        lot_id: None,
209
1
    };
210

            
211
1
    let split2 = Split {
212
1
        id: split2_id,
213
1
        tx_id,
214
1
        account_id: Uuid::new_v4(),
215
1
        commodity_id,
216
1
        value_num: 5000,
217
1
        value_denom: 100,
218
1
        reconcile_state: None,
219
1
        reconcile_date: None,
220
1
        lot_id: None,
221
1
    };
222

            
223
1
    let category_tag = Tag {
224
1
        id: Uuid::new_v4(),
225
1
        tag_name: "category".to_string(),
226
1
        tag_value: "food".to_string(),
227
1
        description: None,
228
1
    };
229

            
230
1
    let state = TransactionState::new(tx)
231
1
        .with(vec![
232
1
            FinanceEntity::Split(split1),
233
1
            FinanceEntity::Split(split2),
234
1
        ])
235
1
        .with_note(Some("groceries".to_string()))
236
1
        .with_split_tags(vec![(split1_id, category_tag)]);
237

            
238
1
    assert_eq!(state.transaction_tags.len(), 1);
239
1
    assert_eq!(state.split_tags.len(), 1);
240

            
241
1
    let script_id = Uuid::new_v4();
242
1
    let executor = ScriptExecutor::try_new().expect("baseline engine");
243
1
    let report = state
244
1
        .run_scripts(&executor, &[(script_id, TAG_SYNC_WASM.to_vec())])
245
1
        .expect("run_scripts failed");
246
1
    assert!(
247
1
        report.failures.is_empty(),
248
        "tag_sync.wasm must run cleanly: {:?}",
249
        report.failures
250
    );
251

            
252
1
    let new_tx_tags: Vec<_> = report
253
1
        .state
254
1
        .transaction_tags
255
1
        .iter()
256
2
        .filter(|t| t.tag_name != "note")
257
        .collect();
258
1
    assert_eq!(
259
1
        new_tx_tags.len(),
260
1
        1,
261
        "tag_sync should copy category tag from split to transaction"
262
    );
263
1
    assert_eq!(new_tx_tags[0].tag_name, "category");
264
1
    assert_eq!(new_tx_tags[0].tag_value, "food");
265
1
}
266

            
267
/// Bad bytecode lands as a structured `ScriptFailure` in the report
268
/// rather than being silently swallowed. The state is preserved
269
/// (no side effects from a failed script).
270
#[test]
271
1
fn run_scripts_captures_failed_script_into_structured_report() {
272
1
    let tx_id = Uuid::new_v4();
273
1
    let tx = TransactionBuilder::new()
274
1
        .id(tx_id)
275
1
        .post_date(Local::now().into())
276
1
        .enter_date(Local::now().into())
277
1
        .build()
278
1
        .unwrap();
279
1
    let state = TransactionState::new(tx);
280

            
281
1
    let script_id = Uuid::new_v4();
282
1
    let invalid_bytecode: Vec<u8> = vec![0xde, 0xad, 0xbe, 0xef];
283
1
    let executor = ScriptExecutor::try_new().expect("baseline engine");
284
1
    let report = state
285
1
        .run_scripts(&executor, &[(script_id, invalid_bytecode)])
286
1
        .expect("run_scripts must surface bad-bytecode as a failure cell, not an outer Err");
287

            
288
1
    assert_eq!(
289
1
        report.failures.len(),
290
1
        1,
291
        "single bad script should produce exactly one captured failure"
292
    );
293
1
    assert_eq!(report.failures[0].script_id, script_id);
294
1
    assert!(
295
1
        !report.failures[0].code.is_empty(),
296
        "captured failure must carry a non-empty code symbol"
297
    );
298
1
    assert!(
299
1
        report.state.transaction_tags.is_empty(),
300
        "failed script must not have mutated state"
301
    );
302
1
    assert_eq!(report.state.transaction.id, tx_id);
303
1
}
304

            
305
/// A mixed batch — one failing script followed by a working one —
306
/// captures the failure but still applies the second script's
307
/// output. Validates the "successive scripts still see state
308
/// mutations from earlier successes" invariant of the report shape.
309
/// Setup mirrors `test_tag_sync_copies_split_tags_to_transaction`'s
310
/// two-split balanced shape because tag_sync.wasm only fires once
311
/// the transaction's splits sum to zero.
312
#[test]
313
1
fn run_scripts_continues_past_failure_and_applies_subsequent_scripts() {
314
    const TAG_SYNC_WASM: &[u8] = include_bytes!("../../../web/static/wasm/tag_sync.wasm");
315

            
316
1
    let tx_id = Uuid::new_v4();
317
1
    let split1_id = Uuid::new_v4();
318
1
    let split2_id = Uuid::new_v4();
319
1
    let commodity_id = Uuid::new_v4();
320
1
    let tx = TransactionBuilder::new()
321
1
        .id(tx_id)
322
1
        .post_date(Local::now().into())
323
1
        .enter_date(Local::now().into())
324
1
        .build()
325
1
        .unwrap();
326
1
    let split1 = Split {
327
1
        id: split1_id,
328
1
        tx_id,
329
1
        account_id: Uuid::new_v4(),
330
1
        commodity_id,
331
1
        value_num: -5000,
332
1
        value_denom: 100,
333
1
        reconcile_state: None,
334
1
        reconcile_date: None,
335
1
        lot_id: None,
336
1
    };
337
1
    let split2 = Split {
338
1
        id: split2_id,
339
1
        tx_id,
340
1
        account_id: Uuid::new_v4(),
341
1
        commodity_id,
342
1
        value_num: 5000,
343
1
        value_denom: 100,
344
1
        reconcile_state: None,
345
1
        reconcile_date: None,
346
1
        lot_id: None,
347
1
    };
348
1
    let category_tag = Tag {
349
1
        id: Uuid::new_v4(),
350
1
        tag_name: "category".to_string(),
351
1
        tag_value: "food".to_string(),
352
1
        description: None,
353
1
    };
354
1
    let state = TransactionState::new(tx)
355
1
        .with(vec![
356
1
            FinanceEntity::Split(split1),
357
1
            FinanceEntity::Split(split2),
358
1
        ])
359
1
        .with_note(Some("groceries".to_string()))
360
1
        .with_split_tags(vec![(split1_id, category_tag)]);
361

            
362
1
    let bad_id = Uuid::new_v4();
363
1
    let good_id = Uuid::new_v4();
364
1
    let executor = ScriptExecutor::try_new().expect("baseline engine");
365
1
    let report = state
366
1
        .run_scripts(
367
1
            &executor,
368
1
            &[
369
1
                (bad_id, vec![0xde, 0xad, 0xbe, 0xef]),
370
1
                (good_id, TAG_SYNC_WASM.to_vec()),
371
1
            ],
372
1
        )
373
1
        .expect("run_scripts must capture per-script failures structurally");
374

            
375
1
    assert_eq!(report.failures.len(), 1);
376
1
    assert_eq!(report.failures[0].script_id, bad_id);
377

            
378
1
    let category_tx_tags: Vec<_> = report
379
1
        .state
380
1
        .transaction_tags
381
1
        .iter()
382
2
        .filter(|t| t.tag_name == "category")
383
        .collect();
384
1
    assert_eq!(
385
1
        category_tx_tags.len(),
386
1
        1,
387
        "tag_sync.wasm must still copy the split's category tag onto the transaction \
388
         after an earlier script failed"
389
    );
390
1
}
391

            
392
/// `classify_script_failure` routes engine-classified errors
393
/// through `err_code_and_message` so the code symbols match catch-each's
394
/// err cells. A commodity mismatch is the load-bearing case — it now
395
/// `throw`s `$nomi_error` in-guest and arrives as a `ScriptRaised`
396
/// carrying the reader-folded symbol `COMMODITY-MISMATCH` (ADR-0026),
397
/// the structural signal scripts react to, distinct from generic traps.
398
#[test]
399
1
fn classify_script_failure_maps_engine_error_to_symbol_code() {
400
    use scripting::runtime::EngineError;
401
1
    let engine_err = EngineError::ScriptRaised {
402
1
        code: "COMMODITY-MISMATCH".to_string(),
403
1
        message: "USD vs EUR".to_string(),
404
1
        detail: None,
405
1
    };
406
1
    let hook_err = HookError::Engine(engine_err);
407
1
    let id = Uuid::new_v4();
408
1
    let failure = classify_script_failure(id, &hook_err);
409
1
    assert_eq!(failure.script_id, id);
410
1
    assert_eq!(failure.code, "COMMODITY-MISMATCH");
411
1
    assert_eq!(failure.message, "USD vs EUR");
412
1
}
413

            
414
/// Non-engine `HookError` variants (Parse / Lock / Script) fall
415
/// through to a `runtime` code with the engine's own message —
416
/// the catch-all path that keeps `ScriptFailure`'s shape
417
/// non-empty for any cause `executor.execute` can surface.
418
#[test]
419
1
fn classify_script_failure_falls_back_to_runtime_for_non_engine_error() {
420
1
    let hook_err = HookError::Script("synthetic test failure".to_string());
421
1
    let id = Uuid::new_v4();
422
1
    let failure = classify_script_failure(id, &hook_err);
423
1
    assert_eq!(failure.script_id, id);
424
1
    assert_eq!(failure.code, "runtime");
425
1
    assert!(failure.message.contains("synthetic test failure"));
426
1
}
427

            
428
2
fn shared_tag_state() -> anyhow::Result<(TransactionState, Uuid, [Uuid; 2])> {
429
2
    let tx = TransactionBuilder::new()
430
2
        .id(Uuid::new_v4())
431
2
        .post_date(Local::now().into())
432
2
        .enter_date(Local::now().into())
433
2
        .build()?;
434
2
    let splits = [Uuid::new_v4(), Uuid::new_v4()];
435
2
    let trip = Tag {
436
2
        id: Uuid::new_v4(),
437
2
        tag_name: "trip".to_string(),
438
2
        tag_value: "japan".to_string(),
439
2
        description: None,
440
2
    };
441
2
    let mut state = TransactionState::new(tx)
442
4
        .with_split_tags(splits.iter().map(|id| (*id, trip.clone())).collect());
443
2
    state.transaction_tags.push(trip.clone());
444
2
    Ok((state, trip.id, splits))
445
2
}
446

            
447
3
fn delete_entity(wire_id: Uuid) -> ParsedEntity {
448
3
    ParsedEntity {
449
3
        entity_type: EntityType::Tag,
450
3
        operation: Operation::Delete,
451
3
        flags: 0,
452
3
        id: *wire_id.as_bytes(),
453
3
        parent_idx: -1,
454
3
        data: EntityData::Tag {
455
3
            name: String::new(),
456
3
            value: String::new(),
457
3
        },
458
3
    }
459
3
}
460

            
461
2
fn wire_id_of(tag_links: &TagLinks, link: TagLink) -> anyhow::Result<Uuid> {
462
2
    tag_links
463
2
        .iter()
464
6
        .find_map(|(wire_id, candidate)| (*candidate == link).then_some(*wire_id))
465
        .ok_or_else(|| anyhow::anyhow!("{link:?} not serialized"))
466
2
}
467

            
468
#[test]
469
1
fn deleting_a_shared_tag_on_one_split_keeps_its_other_owners() -> anyhow::Result<()> {
470
1
    let (mut state, trip, splits) = shared_tag_state()?;
471
1
    let (_, mut index_table, tag_links) = serialize_state(&state);
472
1
    let wire_id = wire_id_of(&tag_links, TagLink::Split(splits[0], trip))?;
473
1
    apply_parsed_entities(
474
1
        &mut state,
475
1
        vec![delete_entity(wire_id)],
476
1
        &mut index_table,
477
1
        &tag_links,
478
1
    )?;
479
1
    assert_eq!(state.transaction_tags.len(), 1);
480
1
    assert_eq!(state.split_tags.len(), 1);
481
1
    assert_eq!(state.split_tags[0].0, splits[1]);
482
1
    assert!(state.deleted_transaction_tags.is_empty());
483
1
    assert_eq!(state.deleted_split_tags, HashSet::from([(splits[0], trip)]));
484
1
    Ok(())
485
1
}
486

            
487
#[test]
488
1
fn deleting_a_shared_transaction_tag_keeps_its_split_owners() -> anyhow::Result<()> {
489
1
    let (mut state, trip, _) = shared_tag_state()?;
490
1
    let (_, mut index_table, tag_links) = serialize_state(&state);
491
1
    let wire_id = wire_id_of(&tag_links, TagLink::Transaction(trip))?;
492
1
    let twice = vec![delete_entity(wire_id), delete_entity(wire_id)];
493
1
    apply_parsed_entities(&mut state, twice, &mut index_table, &tag_links)?;
494
1
    assert!(state.transaction_tags.is_empty());
495
1
    assert_eq!(state.split_tags.len(), 2);
496
1
    assert_eq!(state.deleted_transaction_tags, HashSet::from([trip]));
497
1
    assert!(state.deleted_split_tags.is_empty());
498
1
    Ok(())
499
1
}