rustledger-core 0.13.0

Core types for rustledger: Amount, Position, Inventory, and all directive types
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
//! Directive types representing all beancount directives.
//!
//! Beancount has 12 directive types that can appear in a ledger file:
//!
//! - [`Transaction`] - The most common directive, recording transfers between accounts
//! - [`Balance`] - Assert that an account has a specific balance
//! - [`Open`] - Open an account for use
//! - [`Close`] - Close an account
//! - [`Commodity`] - Declare a commodity/currency
//! - [`Pad`] - Automatically pad an account to match a balance assertion
//! - [`Event`] - Record a life event
//! - [`Query`] - Store a named BQL query
//! - [`Note`] - Add a note to an account
//! - [`Document`] - Link a document to an account
//! - [`Price`] - Record a price for a commodity
//! - [`Custom`] - Custom directive type

use crate::NaiveDate;
use rust_decimal::Decimal;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::fmt;

use crate::intern::InternedStr;
#[cfg(feature = "rkyv")]
use crate::intern::{AsDecimal, AsInternedStr, AsNaiveDate, AsOptionInternedStr, AsVecInternedStr};
use crate::{Amount, CostSpec, IncompleteAmount};

/// Metadata value types.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub enum MetaValue {
    /// String value
    String(String),
    /// Account reference
    Account(String),
    /// Currency code
    Currency(String),
    /// Tag reference
    Tag(String),
    /// Link reference
    Link(String),
    /// Date value
    Date(#[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))] NaiveDate),
    /// Numeric value
    Number(#[cfg_attr(feature = "rkyv", rkyv(with = AsDecimal))] Decimal),
    /// Boolean value
    Bool(bool),
    /// Amount value
    Amount(Amount),
    /// Null/None value
    None,
}

impl fmt::Display for MetaValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::String(s) => write!(f, "\"{s}\""),
            Self::Account(a) => write!(f, "{a}"),
            Self::Currency(c) => write!(f, "{c}"),
            Self::Tag(t) => write!(f, "#{t}"),
            Self::Link(l) => write!(f, "^{l}"),
            Self::Date(d) => write!(f, "{d}"),
            Self::Number(n) => write!(f, "{n}"),
            Self::Bool(b) => write!(f, "{b}"),
            Self::Amount(a) => write!(f, "{a}"),
            Self::None => write!(f, "None"),
        }
    }
}

/// Metadata is a key-value map attached to directives and postings.
pub type Metadata = FxHashMap<String, MetaValue>;

/// A posting within a transaction.
///
/// Postings represent the individual legs of a transaction. Each posting
/// specifies an account and optionally an amount, cost, and price.
///
/// When the units are `None`, the entire amount will be inferred by the
/// interpolation algorithm to balance the transaction. When units is
/// `Some(IncompleteAmount)`, it may still have missing components that
/// need to be filled in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Posting {
    /// The account for this posting
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub account: InternedStr,
    /// The units (may be incomplete or None for auto-calculated postings)
    pub units: Option<IncompleteAmount>,
    /// Cost specification for the position
    pub cost: Option<CostSpec>,
    /// Price annotation (@ or @@)
    pub price: Option<PriceAnnotation>,
    /// Whether this posting has the "!" flag
    pub flag: Option<char>,
    /// Posting metadata
    pub meta: Metadata,
    /// Comments that appear before this posting (one per line)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub comments: Vec<String>,
    /// Trailing comment(s) on the same line as the posting
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub trailing_comments: Vec<String>,
}

impl Posting {
    /// Create a new posting with the given account and complete units.
    #[must_use]
    pub fn new(account: impl Into<InternedStr>, units: Amount) -> Self {
        Self {
            account: account.into(),
            units: Some(IncompleteAmount::Complete(units)),
            cost: None,
            price: None,
            flag: None,
            meta: Metadata::default(),
            comments: Vec::new(),
            trailing_comments: Vec::new(),
        }
    }

    /// Create a new posting with an incomplete amount.
    #[must_use]
    pub fn with_incomplete(account: impl Into<InternedStr>, units: IncompleteAmount) -> Self {
        Self {
            account: account.into(),
            units: Some(units),
            cost: None,
            price: None,
            flag: None,
            meta: Metadata::default(),
            comments: Vec::new(),
            trailing_comments: Vec::new(),
        }
    }

    /// Create a posting without any amount (to be fully interpolated).
    #[must_use]
    pub fn auto(account: impl Into<InternedStr>) -> Self {
        Self {
            account: account.into(),
            units: None,
            cost: None,
            price: None,
            flag: None,
            meta: Metadata::default(),
            comments: Vec::new(),
            trailing_comments: Vec::new(),
        }
    }

    /// Get the complete amount if available.
    #[must_use]
    pub fn amount(&self) -> Option<&Amount> {
        self.units.as_ref().and_then(|u| u.as_amount())
    }

    /// Add a cost specification.
    #[must_use]
    pub fn with_cost(mut self, cost: CostSpec) -> Self {
        self.cost = Some(cost);
        self
    }

    /// Add a price annotation.
    #[must_use]
    pub fn with_price(mut self, price: PriceAnnotation) -> Self {
        self.price = Some(price);
        self
    }

    /// Add a flag.
    #[must_use]
    pub const fn with_flag(mut self, flag: char) -> Self {
        self.flag = Some(flag);
        self
    }

    /// Check if this posting has an amount.
    #[must_use]
    pub const fn has_units(&self) -> bool {
        self.units.is_some()
    }
}

impl fmt::Display for Posting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "  ")?;
        if let Some(flag) = self.flag {
            write!(f, "{flag} ")?;
        }
        write!(f, "{}", self.account)?;
        if let Some(units) = &self.units {
            write!(f, "  {units}")?;
        }
        if let Some(cost) = &self.cost {
            write!(f, " {cost}")?;
        }
        if let Some(price) = &self.price {
            write!(f, " {price}")?;
        }
        // Posting-level metadata
        for (key, value) in &self.meta {
            write!(f, "\n    {key}: {value}")?;
        }
        Ok(())
    }
}

/// Price annotation for a posting (@ or @@).
///
/// Price annotations can be incomplete (missing number or currency)
/// before interpolation fills in the missing values.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub enum PriceAnnotation {
    /// Per-unit price (@) with complete amount
    Unit(Amount),
    /// Total price (@@) with complete amount
    Total(Amount),
    /// Per-unit price (@) with incomplete amount
    UnitIncomplete(IncompleteAmount),
    /// Total price (@@) with incomplete amount
    TotalIncomplete(IncompleteAmount),
    /// Empty per-unit price (@ with no amount)
    UnitEmpty,
    /// Empty total price (@@ with no amount)
    TotalEmpty,
}

impl PriceAnnotation {
    /// Get the complete amount if available.
    #[must_use]
    pub const fn amount(&self) -> Option<&Amount> {
        match self {
            Self::Unit(a) | Self::Total(a) => Some(a),
            Self::UnitIncomplete(ia) | Self::TotalIncomplete(ia) => ia.as_amount(),
            Self::UnitEmpty | Self::TotalEmpty => None,
        }
    }

    /// Check if this is a per-unit price (@ vs @@).
    #[must_use]
    pub const fn is_unit(&self) -> bool {
        matches!(
            self,
            Self::Unit(_) | Self::UnitIncomplete(_) | Self::UnitEmpty
        )
    }
}

impl fmt::Display for PriceAnnotation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unit(a) => write!(f, "@ {a}"),
            Self::Total(a) => write!(f, "@@ {a}"),
            Self::UnitIncomplete(ia) => write!(f, "@ {ia}"),
            Self::TotalIncomplete(ia) => write!(f, "@@ {ia}"),
            Self::UnitEmpty => write!(f, "@"),
            Self::TotalEmpty => write!(f, "@@"),
        }
    }
}

/// Directive ordering priority for sorting.
///
/// When directives have the same date, they are sorted by type priority
/// to ensure proper processing order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DirectivePriority {
    /// Open accounts first so they exist before use
    Open = 0,
    /// Commodities declared before use
    Commodity = 1,
    /// Padding before balance assertions
    Pad = 2,
    /// Balance assertions checked at start of day
    Balance = 3,
    /// Main entries
    Transaction = 4,
    /// Annotations after transactions
    Note = 5,
    /// Attachments after transactions
    Document = 6,
    /// State changes
    Event = 7,
    /// Queries defined after data
    Query = 8,
    /// Prices at end of day
    Price = 9,
    /// Accounts closed after all activity
    Close = 10,
    /// User extensions last
    Custom = 11,
}

/// All directive types in beancount.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub enum Directive {
    /// Transaction directive - records transfers between accounts
    Transaction(Transaction),
    /// Balance assertion - asserts an account balance at a point in time
    Balance(Balance),
    /// Open account - opens an account for use
    Open(Open),
    /// Close account - closes an account
    Close(Close),
    /// Commodity declaration - declares a currency/commodity
    Commodity(Commodity),
    /// Pad directive - auto-pad an account to match a balance
    Pad(Pad),
    /// Event directive - records a life event
    Event(Event),
    /// Query directive - stores a named BQL query
    Query(Query),
    /// Note directive - adds a note to an account
    Note(Note),
    /// Document directive - links a document to an account
    Document(Document),
    /// Price directive - records a commodity price
    Price(Price),
    /// Custom directive - custom user-defined directive
    Custom(Custom),
}

impl Directive {
    /// Get the date of this directive.
    #[must_use]
    pub const fn date(&self) -> NaiveDate {
        match self {
            Self::Transaction(t) => t.date,
            Self::Balance(b) => b.date,
            Self::Open(o) => o.date,
            Self::Close(c) => c.date,
            Self::Commodity(c) => c.date,
            Self::Pad(p) => p.date,
            Self::Event(e) => e.date,
            Self::Query(q) => q.date,
            Self::Note(n) => n.date,
            Self::Document(d) => d.date,
            Self::Price(p) => p.date,
            Self::Custom(c) => c.date,
        }
    }

    /// Get the metadata of this directive.
    #[must_use]
    pub const fn meta(&self) -> &Metadata {
        match self {
            Self::Transaction(t) => &t.meta,
            Self::Balance(b) => &b.meta,
            Self::Open(o) => &o.meta,
            Self::Close(c) => &c.meta,
            Self::Commodity(c) => &c.meta,
            Self::Pad(p) => &p.meta,
            Self::Event(e) => &e.meta,
            Self::Query(q) => &q.meta,
            Self::Note(n) => &n.meta,
            Self::Document(d) => &d.meta,
            Self::Price(p) => &p.meta,
            Self::Custom(c) => &c.meta,
        }
    }

    /// Check if this is a transaction.
    #[must_use]
    pub const fn is_transaction(&self) -> bool {
        matches!(self, Self::Transaction(_))
    }

    /// Get as a transaction, if this is one.
    #[must_use]
    pub const fn as_transaction(&self) -> Option<&Transaction> {
        match self {
            Self::Transaction(t) => Some(t),
            _ => None,
        }
    }

    /// Get the directive type name.
    #[must_use]
    pub const fn type_name(&self) -> &'static str {
        match self {
            Self::Transaction(_) => "transaction",
            Self::Balance(_) => "balance",
            Self::Open(_) => "open",
            Self::Close(_) => "close",
            Self::Commodity(_) => "commodity",
            Self::Pad(_) => "pad",
            Self::Event(_) => "event",
            Self::Query(_) => "query",
            Self::Note(_) => "note",
            Self::Document(_) => "document",
            Self::Price(_) => "price",
            Self::Custom(_) => "custom",
        }
    }

    /// Get the sorting priority for this directive.
    ///
    /// Used to determine order when directives have the same date.
    #[must_use]
    pub const fn priority(&self) -> DirectivePriority {
        match self {
            Self::Open(_) => DirectivePriority::Open,
            Self::Commodity(_) => DirectivePriority::Commodity,
            Self::Pad(_) => DirectivePriority::Pad,
            Self::Balance(_) => DirectivePriority::Balance,
            Self::Transaction(_) => DirectivePriority::Transaction,
            Self::Note(_) => DirectivePriority::Note,
            Self::Document(_) => DirectivePriority::Document,
            Self::Event(_) => DirectivePriority::Event,
            Self::Query(_) => DirectivePriority::Query,
            Self::Price(_) => DirectivePriority::Price,
            Self::Close(_) => DirectivePriority::Close,
            Self::Custom(_) => DirectivePriority::Custom,
        }
    }

    /// Check if this directive has any cost-basis reductions.
    ///
    /// A transaction "reduces" inventory when it has a posting with a cost
    /// spec and negative units (selling lots). Used to order same-date
    /// transactions: augmentations (buying) should process before
    /// reductions (selling) so lots exist when they're matched.
    #[must_use]
    pub fn has_cost_reduction(&self) -> bool {
        if let Self::Transaction(txn) = self {
            txn.postings.iter().any(|p| {
                p.cost.is_some()
                    && p.units
                        .as_ref()
                        .and_then(IncompleteAmount::number)
                        .is_some_and(|n| n.is_sign_negative())
            })
        } else {
            false
        }
    }
}

/// Sort directives by date, then type priority, then cost-basis reductions last.
///
/// This is a stable sort that preserves file order for directives
/// with the same date, type, and reduction status.
///
/// Within the same date, transactions without cost-basis reductions
/// (no negative-units + cost-spec postings) are processed before
/// those that do reduce cost-basis lots. This ensures lots exist
/// when they're matched, regardless of file ordering.
pub fn sort_directives(directives: &mut [Directive]) {
    directives.sort_by_cached_key(|d| (d.date(), d.priority(), d.has_cost_reduction()));
}

/// A transaction directive.
///
/// Transactions are the most common directive type. They record transfers
/// between accounts and must balance (sum of all postings equals zero).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Transaction {
    /// Transaction date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Transaction flag (* or !)
    pub flag: char,
    /// Payee (optional)
    #[cfg_attr(feature = "rkyv", rkyv(with = AsOptionInternedStr))]
    pub payee: Option<InternedStr>,
    /// Narration (description)
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub narration: InternedStr,
    /// Tags attached to this transaction
    #[cfg_attr(feature = "rkyv", rkyv(with = AsVecInternedStr))]
    pub tags: Vec<InternedStr>,
    /// Links attached to this transaction
    #[cfg_attr(feature = "rkyv", rkyv(with = AsVecInternedStr))]
    pub links: Vec<InternedStr>,
    /// Transaction metadata
    pub meta: Metadata,
    /// Postings (account entries)
    pub postings: Vec<Posting>,
    /// Comments that appear after all postings
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub trailing_comments: Vec<String>,
}

impl Transaction {
    /// Create a new transaction.
    #[must_use]
    pub fn new(date: NaiveDate, narration: impl Into<InternedStr>) -> Self {
        Self {
            date,
            flag: '*',
            payee: None,
            narration: narration.into(),
            tags: Vec::new(),
            links: Vec::new(),
            meta: Metadata::default(),
            postings: Vec::new(),
            trailing_comments: Vec::new(),
        }
    }

    /// Set the flag.
    #[must_use]
    pub const fn with_flag(mut self, flag: char) -> Self {
        self.flag = flag;
        self
    }

    /// Set the payee.
    #[must_use]
    pub fn with_payee(mut self, payee: impl Into<InternedStr>) -> Self {
        self.payee = Some(payee.into());
        self
    }

    /// Add a tag.
    #[must_use]
    pub fn with_tag(mut self, tag: impl Into<InternedStr>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Add a link.
    #[must_use]
    pub fn with_link(mut self, link: impl Into<InternedStr>) -> Self {
        self.links.push(link.into());
        self
    }

    /// Add a posting.
    #[must_use]
    pub fn with_posting(mut self, posting: Posting) -> Self {
        self.postings.push(posting);
        self
    }

    /// Check if this transaction is marked as complete (*).
    #[must_use]
    pub const fn is_complete(&self) -> bool {
        self.flag == '*'
    }

    /// Check if this transaction is marked as incomplete/pending (!).
    #[must_use]
    pub const fn is_incomplete(&self) -> bool {
        self.flag == '!'
    }

    /// Check if this transaction is marked as pending (!).
    /// Alias for `is_incomplete`.
    #[must_use]
    pub const fn is_pending(&self) -> bool {
        self.flag == '!'
    }

    /// Check if this transaction was generated by a pad directive (P).
    #[must_use]
    pub const fn is_pad_generated(&self) -> bool {
        self.flag == 'P'
    }

    /// Check if this is a summarization transaction (S).
    #[must_use]
    pub const fn is_summarization(&self) -> bool {
        self.flag == 'S'
    }

    /// Check if this is a transfer transaction (T).
    #[must_use]
    pub const fn is_transfer(&self) -> bool {
        self.flag == 'T'
    }

    /// Check if this is a currency conversion transaction (C).
    #[must_use]
    pub const fn is_conversion(&self) -> bool {
        self.flag == 'C'
    }

    /// Check if this is an unrealized gains transaction (U).
    #[must_use]
    pub const fn is_unrealized(&self) -> bool {
        self.flag == 'U'
    }

    /// Check if this is a return/dividend transaction (R).
    #[must_use]
    pub const fn is_return(&self) -> bool {
        self.flag == 'R'
    }

    /// Check if this is a merge transaction (M).
    #[must_use]
    pub const fn is_merge(&self) -> bool {
        self.flag == 'M'
    }

    /// Check if this transaction is bookmarked (#).
    #[must_use]
    pub const fn is_bookmarked(&self) -> bool {
        self.flag == '#'
    }

    /// Check if this transaction needs investigation (?).
    #[must_use]
    pub const fn needs_investigation(&self) -> bool {
        self.flag == '?'
    }

    /// Check if the given character is a valid transaction flag.
    #[must_use]
    pub const fn is_valid_flag(flag: char) -> bool {
        matches!(
            flag,
            '*' | '!' | 'P' | 'S' | 'T' | 'C' | 'U' | 'R' | 'M' | '#' | '?' | '%' | '&'
        )
    }
}

impl fmt::Display for Transaction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} ", self.date, self.flag)?;
        if let Some(payee) = &self.payee {
            write!(f, "\"{payee}\" ")?;
        }
        write!(f, "\"{}\"", self.narration)?;
        for tag in &self.tags {
            write!(f, " #{tag}")?;
        }
        for link in &self.links {
            write!(f, " ^{link}")?;
        }
        // Transaction-level metadata
        for (key, value) in &self.meta {
            write!(f, "\n  {key}: {value}")?;
        }
        for posting in &self.postings {
            write!(f, "\n{posting}")?;
        }
        Ok(())
    }
}

/// A balance assertion directive.
///
/// Asserts that an account has a specific balance at the beginning of a date.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Balance {
    /// Assertion date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Account to check
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub account: InternedStr,
    /// Expected amount
    pub amount: Amount,
    /// Tolerance (if explicitly specified)
    #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<AsDecimal>))]
    pub tolerance: Option<Decimal>,
    /// Metadata
    pub meta: Metadata,
}

impl Balance {
    /// Create a new balance assertion.
    #[must_use]
    pub fn new(date: NaiveDate, account: impl Into<InternedStr>, amount: Amount) -> Self {
        Self {
            date,
            account: account.into(),
            amount,
            tolerance: None,
            meta: Metadata::default(),
        }
    }

    /// Set explicit tolerance.
    #[must_use]
    pub const fn with_tolerance(mut self, tolerance: Decimal) -> Self {
        self.tolerance = Some(tolerance);
        self
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Balance {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} balance {} {}", self.date, self.account, self.amount)?;
        if let Some(tol) = self.tolerance {
            write!(f, " ~ {tol}")?;
        }
        Ok(())
    }
}

/// An open account directive.
///
/// Opens an account for use. Accounts must be opened before they can be used.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Open {
    /// Date account was opened
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Account name (e.g., "Assets:Bank:Checking")
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub account: InternedStr,
    /// Allowed currencies (empty = any currency allowed)
    #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<AsInternedStr>))]
    pub currencies: Vec<InternedStr>,
    /// Booking method for this account
    pub booking: Option<String>,
    /// Metadata
    pub meta: Metadata,
}

impl Open {
    /// Create a new open directive.
    #[must_use]
    pub fn new(date: NaiveDate, account: impl Into<InternedStr>) -> Self {
        Self {
            date,
            account: account.into(),
            currencies: Vec::new(),
            booking: None,
            meta: Metadata::default(),
        }
    }

    /// Set allowed currencies.
    #[must_use]
    pub fn with_currencies(mut self, currencies: Vec<InternedStr>) -> Self {
        self.currencies = currencies;
        self
    }

    /// Set booking method.
    #[must_use]
    pub fn with_booking(mut self, booking: impl Into<String>) -> Self {
        self.booking = Some(booking.into());
        self
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Open {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} open {}", self.date, self.account)?;
        if !self.currencies.is_empty() {
            let currencies: Vec<&str> = self.currencies.iter().map(InternedStr::as_str).collect();
            write!(f, " {}", currencies.join(","))?;
        }
        if let Some(booking) = &self.booking {
            write!(f, " \"{booking}\"")?;
        }
        Ok(())
    }
}

/// A close account directive.
///
/// Closes an account. The account should have zero balance when closed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Close {
    /// Date account was closed
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Account name
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub account: InternedStr,
    /// Metadata
    pub meta: Metadata,
}

impl Close {
    /// Create a new close directive.
    #[must_use]
    pub fn new(date: NaiveDate, account: impl Into<InternedStr>) -> Self {
        Self {
            date,
            account: account.into(),
            meta: Metadata::default(),
        }
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Close {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} close {}", self.date, self.account)
    }
}

/// A commodity declaration directive.
///
/// Declares a commodity/currency that can be used in the ledger.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Commodity {
    /// Declaration date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Currency/commodity code (e.g., "USD", "AAPL")
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub currency: InternedStr,
    /// Metadata
    pub meta: Metadata,
}

impl Commodity {
    /// Create a new commodity declaration.
    #[must_use]
    pub fn new(date: NaiveDate, currency: impl Into<InternedStr>) -> Self {
        Self {
            date,
            currency: currency.into(),
            meta: Metadata::default(),
        }
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Commodity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} commodity {}", self.date, self.currency)
    }
}

/// A pad directive.
///
/// Automatically inserts a transaction to pad an account to match
/// a subsequent balance assertion.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Pad {
    /// Pad date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Account to pad
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub account: InternedStr,
    /// Source account for padding (e.g., Equity:Opening-Balances)
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub source_account: InternedStr,
    /// Metadata
    pub meta: Metadata,
}

impl Pad {
    /// Create a new pad directive.
    #[must_use]
    pub fn new(
        date: NaiveDate,
        account: impl Into<InternedStr>,
        source_account: impl Into<InternedStr>,
    ) -> Self {
        Self {
            date,
            account: account.into(),
            source_account: source_account.into(),
            meta: Metadata::default(),
        }
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Pad {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} pad {} {}",
            self.date, self.account, self.source_account
        )
    }
}

/// An event directive.
///
/// Records a life event (e.g., location changes, employment changes).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Event {
    /// Event date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Event type (e.g., "location", "employer")
    pub event_type: String,
    /// Event value
    pub value: String,
    /// Metadata
    pub meta: Metadata,
}

impl Event {
    /// Create a new event directive.
    #[must_use]
    pub fn new(date: NaiveDate, event_type: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            date,
            event_type: event_type.into(),
            value: value.into(),
            meta: Metadata::default(),
        }
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Event {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} event \"{}\" \"{}\"",
            self.date, self.event_type, self.value
        )
    }
}

/// A query directive.
///
/// Stores a named BQL query that can be referenced later.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Query {
    /// Query date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Query name
    pub name: String,
    /// BQL query string
    pub query: String,
    /// Metadata
    pub meta: Metadata,
}

impl Query {
    /// Create a new query directive.
    #[must_use]
    pub fn new(date: NaiveDate, name: impl Into<String>, query: impl Into<String>) -> Self {
        Self {
            date,
            name: name.into(),
            query: query.into(),
            meta: Metadata::default(),
        }
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Query {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} query \"{}\" \"{}\"",
            self.date, self.name, self.query
        )
    }
}

/// A note directive.
///
/// Adds a note/comment to an account on a specific date.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Note {
    /// Note date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Account
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub account: InternedStr,
    /// Note text
    pub comment: String,
    /// Metadata
    pub meta: Metadata,
}

impl Note {
    /// Create a new note directive.
    #[must_use]
    pub fn new(
        date: NaiveDate,
        account: impl Into<InternedStr>,
        comment: impl Into<String>,
    ) -> Self {
        Self {
            date,
            account: account.into(),
            comment: comment.into(),
            meta: Metadata::default(),
        }
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Note {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} note {} \"{}\"",
            self.date, self.account, self.comment
        )
    }
}

/// A document directive.
///
/// Links an external document file to an account.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Document {
    /// Document date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Account
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub account: InternedStr,
    /// File path to the document
    pub path: String,
    /// Tags
    #[cfg_attr(feature = "rkyv", rkyv(with = AsVecInternedStr))]
    pub tags: Vec<InternedStr>,
    /// Links
    #[cfg_attr(feature = "rkyv", rkyv(with = AsVecInternedStr))]
    pub links: Vec<InternedStr>,
    /// Metadata
    pub meta: Metadata,
}

impl Document {
    /// Create a new document directive.
    #[must_use]
    pub fn new(date: NaiveDate, account: impl Into<InternedStr>, path: impl Into<String>) -> Self {
        Self {
            date,
            account: account.into(),
            path: path.into(),
            tags: Vec::new(),
            links: Vec::new(),
            meta: Metadata::default(),
        }
    }

    /// Add a tag.
    #[must_use]
    pub fn with_tag(mut self, tag: impl Into<InternedStr>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Add a link.
    #[must_use]
    pub fn with_link(mut self, link: impl Into<InternedStr>) -> Self {
        self.links.push(link.into());
        self
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Document {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} document {} \"{}\"",
            self.date, self.account, self.path
        )
    }
}

/// A price directive.
///
/// Records the price of a commodity in another currency.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Price {
    /// Price date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Currency being priced
    #[cfg_attr(feature = "rkyv", rkyv(with = AsInternedStr))]
    pub currency: InternedStr,
    /// Price amount (in another currency)
    pub amount: Amount,
    /// Metadata
    pub meta: Metadata,
}

impl Price {
    /// Create a new price directive.
    #[must_use]
    pub fn new(date: NaiveDate, currency: impl Into<InternedStr>, amount: Amount) -> Self {
        Self {
            date,
            currency: currency.into(),
            amount,
            meta: Metadata::default(),
        }
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Price {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} price {} {}", self.date, self.currency, self.amount)
    }
}

/// A custom directive.
///
/// User-defined directive type for extensions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub struct Custom {
    /// Custom directive date
    #[cfg_attr(feature = "rkyv", rkyv(with = AsNaiveDate))]
    pub date: NaiveDate,
    /// Custom type name (e.g., "budget", "autopay")
    pub custom_type: String,
    /// Values/arguments for this custom directive
    pub values: Vec<MetaValue>,
    /// Metadata
    pub meta: Metadata,
}

impl Custom {
    /// Create a new custom directive.
    #[must_use]
    pub fn new(date: NaiveDate, custom_type: impl Into<String>) -> Self {
        Self {
            date,
            custom_type: custom_type.into(),
            values: Vec::new(),
            meta: Metadata::default(),
        }
    }

    /// Add a value.
    #[must_use]
    pub fn with_value(mut self, value: MetaValue) -> Self {
        self.values.push(value);
        self
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: Metadata) -> Self {
        self.meta = meta;
        self
    }
}

impl fmt::Display for Custom {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} custom \"{}\"", self.date, self.custom_type)?;
        for value in &self.values {
            write!(f, " {value}")?;
        }
        Ok(())
    }
}

impl fmt::Display for Directive {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Transaction(t) => write!(f, "{t}"),
            Self::Balance(b) => write!(f, "{b}"),
            Self::Open(o) => write!(f, "{o}"),
            Self::Close(c) => write!(f, "{c}"),
            Self::Commodity(c) => write!(f, "{c}"),
            Self::Pad(p) => write!(f, "{p}"),
            Self::Event(e) => write!(f, "{e}"),
            Self::Query(q) => write!(f, "{q}"),
            Self::Note(n) => write!(f, "{n}"),
            Self::Document(d) => write!(f, "{d}"),
            Self::Price(p) => write!(f, "{p}"),
            Self::Custom(c) => write!(f, "{c}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal_macros::dec;

    fn date(year: i32, month: u32, day: u32) -> NaiveDate {
        crate::naive_date(year, month, day).unwrap()
    }

    #[test]
    fn test_transaction() {
        let txn = Transaction::new(date(2024, 1, 15), "Grocery shopping")
            .with_payee("Whole Foods")
            .with_flag('*')
            .with_tag("food")
            .with_posting(Posting::new(
                "Expenses:Food",
                Amount::new(dec!(50.00), "USD"),
            ))
            .with_posting(Posting::auto("Assets:Checking"));

        assert_eq!(txn.flag, '*');
        assert_eq!(txn.payee.as_deref(), Some("Whole Foods"));
        assert_eq!(txn.postings.len(), 2);
        assert!(txn.is_complete());
    }

    #[test]
    fn test_balance() {
        let bal = Balance::new(
            date(2024, 1, 1),
            "Assets:Checking",
            Amount::new(dec!(1000.00), "USD"),
        );

        assert_eq!(bal.account, "Assets:Checking");
        assert_eq!(bal.amount.number, dec!(1000.00));
    }

    #[test]
    fn test_open() {
        let open = Open::new(date(2024, 1, 1), "Assets:Bank:Checking")
            .with_currencies(vec!["USD".into()])
            .with_booking("FIFO");

        assert_eq!(open.currencies, vec![InternedStr::from("USD")]);
        assert_eq!(open.booking, Some("FIFO".to_string()));
    }

    #[test]
    fn test_directive_date() {
        let txn = Transaction::new(date(2024, 1, 15), "Test");
        let dir = Directive::Transaction(txn);

        assert_eq!(dir.date(), date(2024, 1, 15));
        assert!(dir.is_transaction());
        assert_eq!(dir.type_name(), "transaction");
    }

    #[test]
    fn test_posting_display() {
        let posting = Posting::new("Assets:Checking", Amount::new(dec!(100.00), "USD"));
        let s = format!("{posting}");
        assert!(s.contains("Assets:Checking"));
        assert!(s.contains("100.00 USD"));
    }

    #[test]
    fn test_transaction_display() {
        let txn = Transaction::new(date(2024, 1, 15), "Test transaction")
            .with_payee("Test Payee")
            .with_posting(Posting::new(
                "Expenses:Test",
                Amount::new(dec!(50.00), "USD"),
            ))
            .with_posting(Posting::auto("Assets:Cash"));

        let s = format!("{txn}");
        assert!(s.contains("2024-01-15"));
        assert!(s.contains("Test Payee"));
        assert!(s.contains("Test transaction"));
    }

    #[test]
    fn test_directive_priority() {
        // Test that priorities are ordered correctly
        assert!(DirectivePriority::Open < DirectivePriority::Transaction);
        assert!(DirectivePriority::Pad < DirectivePriority::Balance);
        assert!(DirectivePriority::Balance < DirectivePriority::Transaction);
        assert!(DirectivePriority::Transaction < DirectivePriority::Close);
        assert!(DirectivePriority::Price < DirectivePriority::Close);
    }

    #[test]
    fn test_sort_directives_by_date() {
        let mut directives = vec![
            Directive::Transaction(Transaction::new(date(2024, 1, 15), "Third")),
            Directive::Transaction(Transaction::new(date(2024, 1, 1), "First")),
            Directive::Transaction(Transaction::new(date(2024, 1, 10), "Second")),
        ];

        sort_directives(&mut directives);

        assert_eq!(directives[0].date(), date(2024, 1, 1));
        assert_eq!(directives[1].date(), date(2024, 1, 10));
        assert_eq!(directives[2].date(), date(2024, 1, 15));
    }

    #[test]
    fn test_sort_directives_by_type_same_date() {
        // On the same date, open should come before transaction, transaction before close
        let mut directives = vec![
            Directive::Close(Close::new(date(2024, 1, 1), "Assets:Bank")),
            Directive::Transaction(Transaction::new(date(2024, 1, 1), "Payment")),
            Directive::Open(Open::new(date(2024, 1, 1), "Assets:Bank")),
            Directive::Balance(Balance::new(
                date(2024, 1, 1),
                "Assets:Bank",
                Amount::new(dec!(0), "USD"),
            )),
        ];

        sort_directives(&mut directives);

        assert_eq!(directives[0].type_name(), "open");
        assert_eq!(directives[1].type_name(), "balance");
        assert_eq!(directives[2].type_name(), "transaction");
        assert_eq!(directives[3].type_name(), "close");
    }

    #[test]
    fn test_sort_directives_pad_before_balance() {
        // Pad must come before balance assertion on the same day
        let mut directives = vec![
            Directive::Balance(Balance::new(
                date(2024, 1, 1),
                "Assets:Bank",
                Amount::new(dec!(1000), "USD"),
            )),
            Directive::Pad(Pad::new(
                date(2024, 1, 1),
                "Assets:Bank",
                "Equity:Opening-Balances",
            )),
        ];

        sort_directives(&mut directives);

        assert_eq!(directives[0].type_name(), "pad");
        assert_eq!(directives[1].type_name(), "balance");
    }

    #[test]
    fn test_sort_augmentations_before_reductions_same_date() {
        // Issue #841: same-date transactions should process augmentations
        // (buying lots) before reductions (selling lots) so lots exist
        // when they're matched.
        let reduction = Directive::Transaction(
            Transaction::new(date(2024, 9, 1), "Transfer Received")
                .with_posting(
                    Posting::new("Assets:AccountB", Amount::new(dec!(11.11), "USD")).with_cost(
                        CostSpec::empty()
                            .with_number_per(dec!(0.90))
                            .with_currency("EUR"),
                    ),
                )
                .with_posting(
                    Posting::new("Assets:Transit", Amount::new(dec!(-11.11), "USD")).with_cost(
                        CostSpec::empty()
                            .with_number_per(dec!(0.90))
                            .with_currency("EUR"),
                    ),
                ),
        );

        let augmentation = Directive::Transaction(
            Transaction::new(date(2024, 9, 1), "Transfer Sent")
                .with_posting(Posting::new(
                    "Assets:AccountA",
                    Amount::new(dec!(-10.00), "EUR"),
                ))
                .with_posting(
                    Posting::new("Assets:Transit", Amount::new(dec!(11.11), "USD")).with_cost(
                        CostSpec::empty()
                            .with_number_per(dec!(0.90))
                            .with_currency("EUR"),
                    ),
                ),
        );

        // Reduction first in file order — sort should fix this
        let mut directives = vec![reduction, augmentation];
        sort_directives(&mut directives);

        // Augmentation (no negative cost posting) should come first
        assert!(
            !directives[0].has_cost_reduction(),
            "first directive should be augmentation"
        );
        assert!(
            directives[1].has_cost_reduction(),
            "second directive should be reduction"
        );
    }

    #[test]
    fn test_has_cost_reduction() {
        // Transaction with negative units + cost = reduction
        let reduction = Directive::Transaction(
            Transaction::new(date(2024, 1, 1), "Sell")
                .with_posting(
                    Posting::new("Assets:Stock", Amount::new(dec!(-10), "AAPL")).with_cost(
                        CostSpec::empty()
                            .with_number_per(dec!(150))
                            .with_currency("USD"),
                    ),
                )
                .with_posting(Posting::new("Assets:Cash", Amount::new(dec!(1500), "USD"))),
        );
        assert!(reduction.has_cost_reduction());

        // Transaction with positive units + cost = augmentation
        let augmentation = Directive::Transaction(
            Transaction::new(date(2024, 1, 1), "Buy")
                .with_posting(
                    Posting::new("Assets:Stock", Amount::new(dec!(10), "AAPL")).with_cost(
                        CostSpec::empty()
                            .with_number_per(dec!(150))
                            .with_currency("USD"),
                    ),
                )
                .with_posting(Posting::new("Assets:Cash", Amount::new(dec!(-1500), "USD"))),
        );
        assert!(!augmentation.has_cost_reduction());

        // Transaction without cost = not a reduction
        let simple = Directive::Transaction(
            Transaction::new(date(2024, 1, 1), "Payment")
                .with_posting(Posting::new("Expenses:Food", Amount::new(dec!(50), "USD")))
                .with_posting(Posting::new("Assets:Cash", Amount::new(dec!(-50), "USD"))),
        );
        assert!(!simple.has_cost_reduction());
    }

    #[test]
    fn test_transaction_flags() {
        let make_txn = |flag: char| Transaction::new(date(2024, 1, 15), "Test").with_flag(flag);

        // Standard flags
        assert!(make_txn('*').is_complete());
        assert!(make_txn('!').is_incomplete());
        assert!(make_txn('!').is_pending());

        // Extended flags
        assert!(make_txn('P').is_pad_generated());
        assert!(make_txn('S').is_summarization());
        assert!(make_txn('T').is_transfer());
        assert!(make_txn('C').is_conversion());
        assert!(make_txn('U').is_unrealized());
        assert!(make_txn('R').is_return());
        assert!(make_txn('M').is_merge());
        assert!(make_txn('#').is_bookmarked());
        assert!(make_txn('?').needs_investigation());

        // Negative cases
        assert!(!make_txn('*').is_pending());
        assert!(!make_txn('!').is_complete());
        assert!(!make_txn('*').is_pad_generated());
    }

    #[test]
    fn test_is_valid_flag() {
        // Valid flags
        for flag in [
            '*', '!', 'P', 'S', 'T', 'C', 'U', 'R', 'M', '#', '?', '%', '&',
        ] {
            assert!(
                Transaction::is_valid_flag(flag),
                "Flag '{flag}' should be valid"
            );
        }

        // Invalid flags
        for flag in ['x', 'X', '0', ' ', 'a', 'Z'] {
            assert!(
                !Transaction::is_valid_flag(flag),
                "Flag '{flag}' should be invalid"
            );
        }
    }

    #[test]
    fn test_transaction_display_includes_metadata() {
        let mut meta = Metadata::default();
        meta.insert(
            "document".to_string(),
            MetaValue::String("myfile.pdf".to_string()),
        );

        let txn = Transaction {
            date: date(2026, 2, 23),
            flag: '*',
            payee: None,
            narration: "Example".into(),
            tags: vec![],
            links: vec![],
            meta,
            postings: vec![
                Posting::new("Assets:Bank", Amount::new(dec!(-2), "USD")),
                Posting::auto("Expenses:Example"),
            ],
            trailing_comments: Vec::new(),
        };

        let output = txn.to_string();
        assert!(
            output.contains("document: \"myfile.pdf\""),
            "Transaction Display should include metadata: {output}"
        );
        assert!(
            output.contains("Assets:Bank"),
            "Transaction Display should include postings: {output}"
        );
    }

    #[test]
    fn test_posting_display_includes_metadata() {
        let mut meta = Metadata::default();
        meta.insert(
            "category".to_string(),
            MetaValue::String("groceries".to_string()),
        );

        let posting = Posting {
            account: "Expenses:Food".into(),
            units: Some(IncompleteAmount::Complete(Amount::new(dec!(50), "USD"))),
            cost: None,
            price: None,
            flag: None,
            meta,
            comments: Vec::new(),
            trailing_comments: Vec::new(),
        };

        let output = posting.to_string();
        assert!(
            output.contains("category: \"groceries\""),
            "Posting Display should include metadata: {output}"
        );
    }

    #[test]
    fn test_directive_display() {
        // Test that Directive enum delegates to inner type's Display
        let txn = Transaction::new(date(2024, 1, 15), "Test transaction");
        let dir = Directive::Transaction(txn.clone());

        // Directive::Display should produce same output as Transaction::Display
        assert_eq!(format!("{dir}"), format!("{txn}"));

        // Test other directive types
        let open = Open::new(date(2024, 1, 1), "Assets:Bank");
        let dir_open = Directive::Open(open.clone());
        assert_eq!(format!("{dir_open}"), format!("{open}"));

        let balance = Balance::new(
            date(2024, 1, 1),
            "Assets:Bank",
            Amount::new(dec!(100), "USD"),
        );
        let dir_balance = Directive::Balance(balance.clone());
        assert_eq!(format!("{dir_balance}"), format!("{balance}"));
    }
}