rustledger-validate 0.16.2

Beancount validation with 26 error codes for ledger correctness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! Integration tests for the validation crate.
//!
//! Tests cover all validation rules: account lifecycle, balance assertions,
//! transaction balancing, currency constraints, and booking validation.

use rust_decimal_macros::dec;
use rustledger_core::{
    Amount, Balance, Close, Directive, NaiveDate, Open, Pad, Posting, PriceAnnotation, Transaction,
};
use rustledger_parser::{Span, Spanned};
use rustledger_validate::{ErrorCode, ValidationOptions};

mod common;
use common::{validate, validate_spanned_with_options};

// ============================================================================
// Helper Functions
// ============================================================================

#[allow(clippy::missing_const_for_fn)]
fn date(year: i32, month: u32, day: u32) -> NaiveDate {
    rustledger_core::naive_date(year, month, day).unwrap()
}

fn validate_directives(directives: &[Directive]) -> Vec<ErrorCode> {
    let errors = validate(directives);
    errors.iter().map(|e| e.code).collect()
}

/// Helper to wrap a directive with span and `file_id` info for testing.
#[allow(clippy::missing_const_for_fn)]
fn spanned_directive(
    directive: Directive,
    start: usize,
    end: usize,
    file_id: u16,
) -> Spanned<Directive> {
    Spanned {
        value: directive,
        span: Span::new(start, end),
        file_id,
    }
}

// ============================================================================
// Account Lifecycle Tests (E1xxx)
// ============================================================================

#[test]
fn test_e1001_account_not_open() {
    let directives = vec![
        // No open directive, but transaction uses account
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Test")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(100), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Cash",
                    Amount::new(dec!(-100), "USD"),
                )),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::AccountNotOpen),
        "expected E1001 AccountNotOpen error"
    );
}

#[test]
fn test_e1002_account_already_open() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 2), "Assets:Bank")), // Duplicate
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::AccountAlreadyOpen),
        "expected E1002 AccountAlreadyOpen error"
    );
}

#[test]
fn test_e1003_account_closed() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Income:Salary")),
        Directive::Close(Close::new(date(2024, 6, 1), "Assets:Bank")),
        // Transaction after close
        Directive::Transaction(
            Transaction::new(date(2024, 7, 1), "After close")
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank",
                    Amount::new(dec!(100), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Income:Salary",
                    Amount::new(dec!(-100), "USD"),
                )),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::AccountClosed),
        "expected E1003 AccountClosed error"
    );
}

#[test]
fn test_valid_account_lifecycle() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Purchase")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(50), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank",
                    Amount::new(dec!(-50), "USD"),
                )),
        ),
        Directive::Close(Close::new(date(2024, 12, 31), "Expenses:Food")),
    ];

    let errors = validate_directives(&directives);
    // No E1xxx errors
    let account_errors: Vec<_> = errors
        .iter()
        .filter(|e| {
            matches!(
                e,
                ErrorCode::AccountNotOpen
                    | ErrorCode::AccountAlreadyOpen
                    | ErrorCode::AccountClosed
            )
        })
        .collect();
    assert!(
        account_errors.is_empty(),
        "expected no account lifecycle errors, got {account_errors:?}"
    );
}

// ============================================================================
// Balance Assertion Tests (E2xxx)
// ============================================================================

#[test]
fn test_e2001_balance_assertion_failed() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Groceries")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(50), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank",
                    Amount::new(dec!(-50), "USD"),
                )),
        ),
        // Balance assertion with wrong amount
        Directive::Balance(Balance::new(
            date(2024, 1, 31),
            "Assets:Bank",
            Amount::new(dec!(1000), "USD"), // Wrong - should be -50
        )),
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::BalanceAssertionFailed),
        "expected E2001 BalanceAssertionFailed error"
    );
}

#[test]
fn test_valid_balance_assertion() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Groceries")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(50), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank",
                    Amount::new(dec!(-50), "USD"),
                )),
        ),
        // Correct balance assertion
        Directive::Balance(Balance::new(
            date(2024, 1, 31),
            "Assets:Bank",
            Amount::new(dec!(-50), "USD"),
        )),
    ];

    let errors = validate_directives(&directives);
    assert!(
        !errors.contains(&ErrorCode::BalanceAssertionFailed),
        "expected no BalanceAssertionFailed error"
    );
}

// ============================================================================
// Transaction Balancing Tests (E3xxx)
// ============================================================================

#[test]
fn test_e3001_transaction_unbalanced() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
        // Transaction doesn't balance
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Unbalanced")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(100), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank",
                    Amount::new(dec!(-50), "USD"),
                )), // Missing 50
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::TransactionUnbalanced),
        "expected E3001 TransactionUnbalanced error"
    );
}

#[test]
fn test_e3003_no_postings_allowed() {
    // Python beancount allows transactions with no postings (metadata-only).
    // We match this behavior and do NOT report an error.
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        // Transaction with no postings
        Directive::Transaction(Transaction::new(date(2024, 1, 15), "Empty transaction")),
    ];

    let errors = validate_directives(&directives);
    assert!(
        !errors.contains(&ErrorCode::NoPostings),
        "should NOT report E3003 NoPostings error (Python allows empty transactions)"
    );
}

#[test]
fn test_e3004_single_posting() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        // Transaction with single posting (warning)
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Single posting").with_synthesized_posting(
                Posting::new("Assets:Bank", Amount::new(dec!(100), "USD")),
            ),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::SinglePosting),
        "expected E3004 SinglePosting warning"
    );
}

#[test]
fn test_e4005_negative_cost_per_unit() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Stock")),
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Checking")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Buy with negative cost")
                .with_synthesized_posting(
                    Posting::new("Assets:Stock", Amount::new(dec!(10), "AAPL")).with_cost(
                        rustledger_core::CostSpec::empty()
                            .with_number(rustledger_core::CostNumber::PerUnit { value: dec!(-150) })
                            .with_currency("USD"),
                    ),
                )
                .with_synthesized_posting(Posting::auto("Assets:Checking")),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::NegativeCost),
        "expected E4005 NegativeCost error for negative per-unit cost"
    );
}

#[test]
fn test_e4005_negative_total_cost() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Stock")),
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Checking")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Buy with negative total cost")
                .with_synthesized_posting(
                    Posting::new("Assets:Stock", Amount::new(dec!(10), "AAPL")).with_cost(
                        rustledger_core::CostSpec::empty()
                            .with_number(rustledger_core::CostNumber::Total { value: dec!(-1500) })
                            .with_currency("USD"),
                    ),
                )
                .with_synthesized_posting(Posting::auto("Assets:Checking")),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        errors.contains(&ErrorCode::NegativeCost),
        "expected E4005 NegativeCost error for negative total cost"
    );
}

#[test]
fn test_e4005_positive_cost_ok() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Stock")),
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Checking")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Buy with positive cost")
                .with_synthesized_posting(
                    Posting::new("Assets:Stock", Amount::new(dec!(10), "AAPL")).with_cost(
                        rustledger_core::CostSpec::empty()
                            .with_number(rustledger_core::CostNumber::PerUnit { value: dec!(150) })
                            .with_currency("USD"),
                    ),
                )
                .with_synthesized_posting(Posting::new(
                    "Assets:Checking",
                    Amount::new(dec!(-1500), "USD"),
                )),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        !errors.contains(&ErrorCode::NegativeCost),
        "expected no NegativeCost error for positive cost"
    );
}

#[test]
fn test_valid_balanced_transaction() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Balanced")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(100), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank",
                    Amount::new(dec!(-100), "USD"),
                )),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        !errors.contains(&ErrorCode::TransactionUnbalanced),
        "expected no TransactionUnbalanced error"
    );
}

// ============================================================================
// Pad Directive Tests
// ============================================================================

#[test]
fn test_valid_pad_with_balance() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Equity:Opening")),
        // Pad to fill initial balance
        Directive::Pad(Pad::new(date(2024, 1, 1), "Assets:Bank", "Equity:Opening")),
        // Balance assertion after pad
        Directive::Balance(Balance::new(
            date(2024, 1, 2),
            "Assets:Bank",
            Amount::new(dec!(1000), "USD"),
        )),
    ];

    let errors = validate_directives(&directives);
    // Pad should work correctly
    assert!(
        !errors.contains(&ErrorCode::BalanceAssertionFailed),
        "expected pad to satisfy balance assertion"
    );
}

// ============================================================================
// Multi-Currency Tests
// ============================================================================

#[test]
fn test_valid_multi_currency_with_price() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:USD")),
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:EUR")),
        // Exchange with price annotation
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Currency exchange")
                .with_synthesized_posting(
                    Posting::new("Assets:USD", Amount::new(dec!(100), "USD"))
                        .with_price(PriceAnnotation::unit(Amount::new(dec!(0.85), "EUR"))),
                )
                .with_synthesized_posting(Posting::new(
                    "Assets:EUR",
                    Amount::new(dec!(-85), "EUR"),
                )),
        ),
    ];

    let errors = validate_directives(&directives);
    assert!(
        !errors.contains(&ErrorCode::TransactionUnbalanced),
        "expected multi-currency transaction with price to balance"
    );
}

// ============================================================================
// Real-World Scenario Tests
// ============================================================================

#[test]
fn test_complete_ledger_validation() {
    let directives = vec![
        // Open accounts
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank:Checking")),
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank:Savings")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Transport")),
        Directive::Open(Open::new(date(2024, 1, 1), "Income:Salary")),
        Directive::Open(Open::new(date(2024, 1, 1), "Equity:Opening")),
        // Initial pad
        Directive::Pad(Pad::new(
            date(2024, 1, 1),
            "Assets:Bank:Checking",
            "Equity:Opening",
        )),
        Directive::Balance(Balance::new(
            date(2024, 1, 2),
            "Assets:Bank:Checking",
            Amount::new(dec!(5000), "USD"),
        )),
        // Salary
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Monthly salary")
                .with_payee("Employer")
                .with_synthesized_posting(Posting::new(
                    "Income:Salary",
                    Amount::new(dec!(-3000), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank:Checking",
                    Amount::new(dec!(3000), "USD"),
                )),
        ),
        // Expenses
        Directive::Transaction(
            Transaction::new(date(2024, 1, 20), "Groceries")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(150), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank:Checking",
                    Amount::new(dec!(-150), "USD"),
                )),
        ),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 22), "Gas")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Transport",
                    Amount::new(dec!(45), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank:Checking",
                    Amount::new(dec!(-45), "USD"),
                )),
        ),
        // Transfer
        Directive::Transaction(
            Transaction::new(date(2024, 1, 25), "Transfer to savings")
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank:Savings",
                    Amount::new(dec!(1000), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank:Checking",
                    Amount::new(dec!(-1000), "USD"),
                )),
        ),
        // Final balance check
        Directive::Balance(Balance::new(
            date(2024, 1, 31),
            "Assets:Bank:Checking",
            Amount::new(dec!(6805), "USD"), // 5000 + 3000 - 150 - 45 - 1000
        )),
    ];

    let errors = validate_directives(&directives);

    // Should have no critical errors
    let critical_errors: Vec<_> = errors
        .iter()
        .filter(|e| {
            matches!(
                e,
                ErrorCode::AccountNotOpen
                    | ErrorCode::TransactionUnbalanced
                    | ErrorCode::BalanceAssertionFailed
            )
        })
        .collect();

    assert!(
        critical_errors.is_empty(),
        "expected no critical validation errors, got {critical_errors:?}"
    );
}

#[test]
fn test_basic_validation() {
    let directives = vec![
        Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
        Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
        Directive::Transaction(
            Transaction::new(date(2024, 1, 15), "Test")
                .with_synthesized_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec!(100), "USD"),
                ))
                .with_synthesized_posting(Posting::new(
                    "Assets:Bank",
                    Amount::new(dec!(-100), "USD"),
                )),
        ),
    ];

    // Validate
    let errors = validate(&directives);

    // Should pass basic validation
    assert!(
        !errors
            .iter()
            .any(|e| e.code == ErrorCode::TransactionUnbalanced)
    );
}

// ============================================================================
// Spanned Validation Tests (validate_spanned_with_options)
// ============================================================================

#[test]
fn test_spanned_validation_preserves_location_for_account_not_open() {
    let directives = vec![
        // Transaction uses an unopened account
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 1, 15), "Test")
                    .with_synthesized_posting(Posting::new(
                        "Expenses:Food",
                        Amount::new(dec!(100), "USD"),
                    ))
                    .with_synthesized_posting(Posting::new(
                        "Assets:Cash",
                        Amount::new(dec!(-100), "USD"),
                    )),
            ),
            100,
            200, // span: bytes 100-200
            1,   // file_id: 1
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let account_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::AccountNotOpen)
        .expect("expected E1001 AccountNotOpen error");

    // Verify that location info was propagated
    assert_eq!(account_error.span, Some(Span::new(100, 200)));
    assert_eq!(account_error.file_id, Some(1));
}

#[test]
fn test_spanned_validation_preserves_location_for_unbalanced_transaction() {
    let directives = vec![
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            0,
            50,
            0,
        ),
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
            50,
            100,
            0,
        ),
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 1, 15), "Unbalanced")
                    .with_synthesized_posting(Posting::new(
                        "Expenses:Food",
                        Amount::new(dec!(100), "USD"),
                    ))
                    .with_synthesized_posting(Posting::new(
                        "Assets:Bank",
                        Amount::new(dec!(-50), "USD"),
                    )), // Missing 50
            ),
            100,
            250, // span: bytes 100-250
            2,   // file_id: 2 (different file)
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let unbalanced_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::TransactionUnbalanced)
        .expect("expected E3001 TransactionUnbalanced error");

    // Verify location from the transaction directive
    assert_eq!(unbalanced_error.span, Some(Span::new(100, 250)));
    assert_eq!(unbalanced_error.file_id, Some(2));
}

#[test]
fn test_spanned_validation_preserves_location_for_balance_error() {
    let directives = vec![
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            0,
            50,
            0,
        ),
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
            50,
            100,
            0,
        ),
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 1, 15), "Purchase")
                    .with_synthesized_posting(Posting::new(
                        "Expenses:Food",
                        Amount::new(dec!(50), "USD"),
                    ))
                    .with_synthesized_posting(Posting::new(
                        "Assets:Bank",
                        Amount::new(dec!(-50), "USD"),
                    )),
            ),
            100,
            200,
            0,
        ),
        // Balance assertion with wrong amount
        spanned_directive(
            Directive::Balance(Balance::new(
                date(2024, 1, 31),
                "Assets:Bank",
                Amount::new(dec!(1000), "USD"), // Wrong
            )),
            200,
            280, // span: bytes 200-280
            3,   // file_id: 3
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let balance_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::BalanceAssertionFailed)
        .expect("expected E2001 BalanceAssertionFailed error");

    assert_eq!(balance_error.span, Some(Span::new(200, 280)));
    assert_eq!(balance_error.file_id, Some(3));
}

#[test]
fn test_spanned_validation_preserves_location_for_duplicate_open() {
    let directives = vec![
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            0,
            50,
            0,
        ),
        // Duplicate open
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 2), "Assets:Bank")),
            50,
            100, // span: bytes 50-100
            1,   // file_id: 1
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let dup_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::AccountAlreadyOpen)
        .expect("expected E1002 AccountAlreadyOpen error");

    assert_eq!(dup_error.span, Some(Span::new(50, 100)));
    assert_eq!(dup_error.file_id, Some(1));
}

#[test]
fn test_spanned_validation_preserves_location_for_account_closed() {
    let directives = vec![
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            0,
            50,
            0,
        ),
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Income:Salary")),
            50,
            100,
            0,
        ),
        spanned_directive(
            Directive::Close(Close::new(date(2024, 6, 1), "Assets:Bank")),
            100,
            150,
            0,
        ),
        // Transaction after close
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 7, 1), "After close")
                    .with_synthesized_posting(Posting::new(
                        "Assets:Bank",
                        Amount::new(dec!(100), "USD"),
                    ))
                    .with_synthesized_posting(Posting::new(
                        "Income:Salary",
                        Amount::new(dec!(-100), "USD"),
                    )),
            ),
            150,
            300, // span: bytes 150-300
            4,   // file_id: 4
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let closed_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::AccountClosed)
        .expect("expected E1003 AccountClosed error");

    assert_eq!(closed_error.span, Some(Span::new(150, 300)));
    assert_eq!(closed_error.file_id, Some(4));
}

#[test]
fn test_spanned_validation_single_posting_warning_has_location() {
    let directives = vec![
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            0,
            50,
            0,
        ),
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 1, 15), "Single posting").with_synthesized_posting(
                    Posting::new("Assets:Bank", Amount::new(dec!(100), "USD")),
                ),
            ),
            50,
            150, // span: bytes 50-150
            5,   // file_id: 5
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let single_post_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::SinglePosting)
        .expect("expected E3004 SinglePosting warning");

    assert_eq!(single_post_error.span, Some(Span::new(50, 150)));
    assert_eq!(single_post_error.file_id, Some(5));
}

#[test]
fn test_spanned_validation_multiple_errors_have_correct_locations() {
    // Test that multiple errors in the same file get their respective locations
    let directives = vec![
        // First error: unopened account
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 1, 15), "First error")
                    .with_synthesized_posting(Posting::new(
                        "Expenses:A",
                        Amount::new(dec!(100), "USD"),
                    ))
                    .with_synthesized_posting(Posting::new(
                        "Assets:A",
                        Amount::new(dec!(-100), "USD"),
                    )),
            ),
            0,
            100, // First location
            0,
        ),
        // Second error: different unopened accounts
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 1, 16), "Second error")
                    .with_synthesized_posting(Posting::new(
                        "Expenses:B",
                        Amount::new(dec!(50), "USD"),
                    ))
                    .with_synthesized_posting(Posting::new(
                        "Assets:B",
                        Amount::new(dec!(-50), "USD"),
                    )),
            ),
            100,
            200, // Second location
            0,
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    // Should have multiple AccountNotOpen errors with different locations
    let account_errors: Vec<_> = errors
        .iter()
        .filter(|e| e.code == ErrorCode::AccountNotOpen)
        .collect();

    assert!(
        account_errors.len() >= 2,
        "expected at least 2 AccountNotOpen errors"
    );

    // Verify at least some have different spans
    let spans: std::collections::HashSet<_> =
        account_errors.iter().filter_map(|e| e.span).collect();
    assert!(spans.len() >= 2, "expected errors to have different spans");
}

#[test]
fn test_spanned_validation_valid_ledger_no_errors() {
    let directives = vec![
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            0,
            50,
            0,
        ),
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Expenses:Food")),
            50,
            100,
            0,
        ),
        spanned_directive(
            Directive::Transaction(
                Transaction::new(date(2024, 1, 15), "Valid")
                    .with_synthesized_posting(Posting::new(
                        "Expenses:Food",
                        Amount::new(dec!(100), "USD"),
                    ))
                    .with_synthesized_posting(Posting::new(
                        "Assets:Bank",
                        Amount::new(dec!(-100), "USD"),
                    )),
            ),
            100,
            250,
            0,
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    // Filter out any info-level "date out of order" messages
    let critical_errors: Vec<_> = errors
        .iter()
        .filter(|e| !matches!(e.code, ErrorCode::DateOutOfOrder | ErrorCode::FutureDate))
        .collect();

    assert!(
        critical_errors.is_empty(),
        "expected no validation errors, got {critical_errors:?}"
    );
}

#[test]
fn test_spanned_validation_out_of_order_dates_have_location() {
    // Test that date ordering warnings include location info
    let directives = vec![
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            0,
            50,
            0,
        ),
        // Later date first
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 10), "Expenses:Food")),
            50,
            100,
            0,
        ),
        // Earlier date second (out of order)
        spanned_directive(
            Directive::Open(Open::new(date(2024, 1, 5), "Expenses:Transport")),
            100,
            150, // span: bytes 100-150
            6,   // file_id: 6
        ),
    ];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let date_error = errors.iter().find(|e| e.code == ErrorCode::DateOutOfOrder);

    // DateOutOfOrder is detected when directives are sorted - the error should have location
    if let Some(error) = date_error {
        assert!(
            error.span.is_some(),
            "DateOutOfOrder error should have span"
        );
        assert!(
            error.file_id.is_some(),
            "DateOutOfOrder error should have file_id"
        );
    }
}

// ============================================================================
// Plugin-synthesized directive attribution (issue #896)
// ============================================================================

#[test]
fn test_plugin_synthesized_directive_gets_attribution_note() {
    // A validator error raised on a directive whose file_id is the synthesized
    // sentinel must carry an advisory note telling the user a plugin generated
    // the directive. Without this, errors from plugin-generated Opens look
    // like they came from nowhere.
    let directives = vec![spanned_directive(
        Directive::Open(Open::new(date(2024, 1, 1), "Equity:Currency:FSS_AUSFIX")),
        0,
        0,
        rustledger_parser::SYNTHESIZED_FILE_ID,
    )];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let account_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::InvalidAccountName)
        .expect("expected E1005 for the '_'-containing account name");

    let note = account_error
        .note
        .as_deref()
        .expect("plugin-synthesized directive must have an attribution note");
    assert!(
        note.contains("synthesized by a plugin"),
        "note should clearly identify the directive as plugin-generated, got: {note}",
    );
    assert!(
        note.contains("plugin"),
        "note should point users at their `plugin` declarations, got: {note}",
    );
}

#[test]
fn test_source_directive_does_not_get_attribution_note() {
    // Complement to the test above: errors on directives with a real file_id
    // (i.e. directly parsed from source) must NOT get the plugin attribution
    // note, or we would confuse users whose accounts ARE in their files.
    let directives = vec![spanned_directive(
        Directive::Open(Open::new(date(2024, 1, 1), "Invalid:Root")),
        10,
        40,
        0, // real source file_id
    )];

    let errors = validate_spanned_with_options(&directives, ValidationOptions::default());

    let account_error = errors
        .iter()
        .find(|e| e.code == ErrorCode::InvalidAccountName)
        .expect("expected E1005 for bad root account type");

    assert!(
        account_error.note.is_none(),
        "source-parsed directive must not be tagged as plugin-synthesized, got note: {:?}",
        account_error.note,
    );
}