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
//! Edge case generators for stress-testing beancount parsers.
//!
//! These generators produce beancount directives that exercise edge cases
//! in parsing and validation, such as:
//!
//! - Unicode in various positions
//! - Extreme decimal precision
//! - Deep account hierarchies
//! - Large transactions with many postings
//! - Boundary dates
//! - Special characters

use crate::{
    Amount, Balance, Close, Commodity, Directive, Event, Note, Open, Pad, Posting, Price,
    Transaction,
    format::{FormatConfig, format_directive},
};
use rust_decimal::Decimal;
use std::str::FromStr;

/// Collection of edge case directives grouped by category.
#[derive(Debug, Clone)]
pub struct EdgeCaseCollection {
    /// Category name (e.g., "unicode", "decimals", "hierarchy")
    pub category: String,
    /// Directives in this collection
    pub directives: Vec<Directive>,
}

impl EdgeCaseCollection {
    /// Create a new edge case collection.
    pub fn new(category: impl Into<String>, directives: Vec<Directive>) -> Self {
        Self {
            category: category.into(),
            directives,
        }
    }

    /// Format all directives to beancount text.
    pub fn to_beancount(&self) -> String {
        let config = FormatConfig::default();
        let mut output = format!("; Edge cases: {}\n\n", self.category);

        for directive in &self.directives {
            output.push_str(&format_directive(directive, &config));
            output.push_str("\n\n");
        }

        output
    }
}

/// Generate all edge case collections.
pub fn generate_all_edge_cases() -> Vec<EdgeCaseCollection> {
    vec![
        generate_unicode_edge_cases(),
        generate_decimal_edge_cases(),
        generate_hierarchy_edge_cases(),
        generate_large_transaction_edge_cases(),
        generate_boundary_date_edge_cases(),
        generate_special_character_edge_cases(),
        generate_minimal_edge_cases(),
    ]
}

/// Generate Unicode edge cases.
///
/// Tests Unicode handling in:
/// - Account names (via valid account segments)
/// - Payee and narration strings
/// - Metadata values
/// - Event descriptions
pub fn generate_unicode_edge_cases() -> EdgeCaseCollection {
    let base_date = crate::naive_date(2024, 1, 1).unwrap();
    let open_date = base_date.yesterday().ok().unwrap();

    let directives = vec![
        // Open accounts first
        Directive::Open(Open::new(open_date, "Assets:Bank:Checking")),
        Directive::Open(Open::new(open_date, "Assets:Bank:Savings")),
        Directive::Open(Open::new(open_date, "Assets:Cash")),
        Directive::Open(Open::new(open_date, "Expenses:Food")),
        Directive::Open(Open::new(open_date, "Expenses:Food:Cafe")),
        Directive::Open(Open::new(open_date, "Expenses:Food:Groceries")),
        Directive::Open(Open::new(open_date, "Expenses:Travel")),
        // Transaction with Unicode in payee and narration
        Directive::Transaction(
            Transaction::new(base_date, "Café Purchase")
                .with_flag('*')
                .with_payee("Bäckerei München")
                .with_posting(Posting::new(
                    "Expenses:Food:Cafe",
                    Amount::new(dec("5.50"), "EUR"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Japanese characters
        Directive::Transaction(
            Transaction::new(base_date, "東京での買い物")
                .with_flag('*')
                .with_payee("コンビニ")
                .with_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec("1000"), "JPY"),
                ))
                .with_posting(Posting::auto("Assets:Cash")),
        ),
        // Russian Cyrillic
        Directive::Transaction(
            Transaction::new(base_date, "Покупка продуктов")
                .with_flag('*')
                .with_payee("Магазин")
                .with_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec("500"), "RUB"),
                ))
                .with_posting(Posting::auto("Assets:Cash")),
        ),
        // Arabic
        Directive::Transaction(
            Transaction::new(base_date, "شراء طعام")
                .with_flag('*')
                .with_payee("متجر")
                .with_posting(Posting::new(
                    "Expenses:Food",
                    Amount::new(dec("100"), "SAR"),
                ))
                .with_posting(Posting::auto("Assets:Cash")),
        ),
        // Emoji in narration
        Directive::Transaction(
            Transaction::new(base_date, "Grocery run with emoji")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Food:Groceries",
                    Amount::new(dec("45.99"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Mixed scripts
        Directive::Transaction(
            Transaction::new(base_date, "International trip")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Travel",
                    Amount::new(dec("2500"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Savings")),
        ),
        // Note with Unicode
        Directive::Note(Note::new(
            base_date,
            "Assets:Bank:Checking",
            "Überprüfung der Kontoauszüge für März",
        )),
        // Event with Unicode
        Directive::Event(Event::new(base_date, "location", "Zürich, Schweiz")),
    ];

    EdgeCaseCollection::new("unicode", directives)
}

/// Generate decimal precision edge cases.
///
/// Tests handling of:
/// - High decimal precision (up to 20 decimal places)
/// - Very large numbers
/// - Very small numbers
/// - Numbers with trailing zeros
pub fn generate_decimal_edge_cases() -> EdgeCaseCollection {
    let base_date = crate::naive_date(2024, 1, 1).unwrap();
    let open_date = base_date.yesterday().ok().unwrap();

    let directives = vec![
        // Open accounts first
        Directive::Open(Open::new(open_date, "Assets:Bank:Checking")),
        Directive::Open(Open::new(open_date, "Assets:Crypto:BTC")),
        Directive::Open(Open::new(open_date, "Assets:Investments:Stock")),
        Directive::Open(Open::new(open_date, "Expenses:Test")),
        Directive::Open(Open::new(open_date, "Equity:Opening")),
        // High precision (8 decimal places - crypto common)
        Directive::Transaction(
            Transaction::new(base_date, "Bitcoin purchase")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Crypto:BTC",
                    Amount::new(dec("0.00012345"), "BTC"),
                ))
                .with_posting(Posting::new(
                    "Assets:Bank:Checking",
                    Amount::new(dec("-5.00"), "USD"),
                )),
        ),
        // Very high precision (16 decimal places)
        Directive::Transaction(
            Transaction::new(base_date, "High precision test")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Investments:Stock",
                    Amount::new(dec("1.1234567890123456"), "MICRO"),
                ))
                .with_posting(Posting::auto("Equity:Opening")),
        ),
        // Very large number
        Directive::Transaction(
            Transaction::new(base_date, "Large number test")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Bank:Checking",
                    Amount::new(dec("999999999999.99"), "USD"),
                ))
                .with_posting(Posting::auto("Equity:Opening")),
        ),
        // Very small fractional amount
        Directive::Transaction(
            Transaction::new(base_date, "Tiny amount")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("0.00000001"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Trailing zeros (should preserve precision)
        Directive::Transaction(
            Transaction::new(base_date, "Trailing zeros")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("100.10000"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Negative with high precision
        Directive::Transaction(
            Transaction::new(base_date, "Negative high precision")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("-0.12345678"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Price with high precision
        Directive::Price(Price::new(
            base_date,
            "BTC",
            Amount::new(dec("45678.12345678"), "USD"),
        )),
    ];

    EdgeCaseCollection::new("decimals", directives)
}

/// Generate deep account hierarchy edge cases.
///
/// Tests parsing of accounts with many segments.
pub fn generate_hierarchy_edge_cases() -> EdgeCaseCollection {
    let base_date = crate::naive_date(2024, 1, 1).unwrap();
    let open_date = base_date.yesterday().ok().unwrap();

    // Deep hierarchy accounts
    let deep_asset = "Assets:Bank:Region:Country:City:Branch:Department:Team:SubTeam:Account";
    let deep_expense = "Expenses:Category:SubCategory:Type:SubType:Detail:MoreDetail:Final";

    let directives = vec![
        // Open deep accounts
        Directive::Open(Open::new(open_date, deep_asset)),
        Directive::Open(Open::new(open_date, deep_expense)),
        Directive::Open(Open::new(open_date, "Assets:A:B:C:D:E:F:G:H:I:J")),
        Directive::Open(Open::new(
            open_date,
            "Liabilities:Debt:Type:Lender:Account:SubAccount",
        )),
        Directive::Open(Open::new(open_date, "Equity:Opening")),
        // Transaction with deep accounts
        Directive::Transaction(
            Transaction::new(base_date, "Deep hierarchy transfer")
                .with_flag('*')
                .with_posting(Posting::new(
                    deep_expense,
                    Amount::new(dec("100.00"), "USD"),
                ))
                .with_posting(Posting::auto(deep_asset)),
        ),
        // Balance assertion on deep account
        Directive::Balance(Balance::new(
            base_date,
            deep_asset,
            Amount::new(dec("-100.00"), "USD"),
        )),
        // Pad with deep accounts
        Directive::Pad(Pad::new(
            base_date,
            "Assets:A:B:C:D:E:F:G:H:I:J",
            "Equity:Opening",
        )),
    ];

    EdgeCaseCollection::new("hierarchy", directives)
}

/// Generate edge cases with large transactions (many postings).
pub fn generate_large_transaction_edge_cases() -> EdgeCaseCollection {
    let base_date = crate::naive_date(2024, 1, 1).unwrap();
    let open_date = base_date.yesterday().ok().unwrap();

    // Generate open directives for accounts
    let mut directives: Vec<Directive> = (0..25)
        .map(|i| Directive::Open(Open::new(open_date, format!("Expenses:Category{i}"))))
        .collect();

    directives.push(Directive::Open(Open::new(
        open_date,
        "Assets:Bank:Checking",
    )));

    // Create a transaction with 20 postings
    let mut txn =
        Transaction::new(base_date, "Expense allocation with 20 categories").with_flag('*');

    for i in 0..20 {
        txn = txn.with_posting(Posting::new(
            format!("Expenses:Category{i}"),
            Amount::new(dec("10.00"), "USD"),
        ));
    }

    // Add the balancing posting
    txn = txn.with_posting(Posting::new(
        "Assets:Bank:Checking",
        Amount::new(dec("-200.00"), "USD"),
    ));

    directives.push(Directive::Transaction(txn));

    // Transaction with many tags and links
    let mut txn2 = Transaction::new(base_date, "Tagged transaction")
        .with_flag('*')
        .with_posting(Posting::new(
            "Expenses:Category0",
            Amount::new(dec("50.00"), "USD"),
        ))
        .with_posting(Posting::auto("Assets:Bank:Checking"));

    for i in 0..10 {
        txn2 = txn2.with_tag(format!("tag{i}"));
    }
    for i in 0..10 {
        txn2 = txn2.with_link(format!("link{i}"));
    }

    directives.push(Directive::Transaction(txn2));

    EdgeCaseCollection::new("large-transactions", directives)
}

/// Generate boundary date edge cases.
pub fn generate_boundary_date_edge_cases() -> EdgeCaseCollection {
    // Early date (1900)
    let early_date = crate::naive_date(1900, 1, 1).unwrap();
    // Late date
    let late_date = crate::naive_date(2099, 12, 31).unwrap();
    // Leap year dates
    let leap_date = crate::naive_date(2024, 2, 29).unwrap();
    // End of months
    let end_jan = crate::naive_date(2024, 1, 31).unwrap();
    let end_apr = crate::naive_date(2024, 4, 30).unwrap();

    let directives = vec![
        // Open accounts at early date
        Directive::Open(Open::new(
            crate::naive_date(1899, 12, 31).unwrap(),
            "Assets:Historical:Account",
        )),
        Directive::Open(Open::new(
            crate::naive_date(1899, 12, 31).unwrap(),
            "Equity:Opening",
        )),
        // Early date transaction
        Directive::Transaction(
            Transaction::new(early_date, "Historical transaction from 1900")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Historical:Account",
                    Amount::new(dec("1.00"), "USD"),
                ))
                .with_posting(Posting::auto("Equity:Opening")),
        ),
        // Late date transaction
        Directive::Transaction(
            Transaction::new(late_date, "Far future transaction")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Historical:Account",
                    Amount::new(dec("1000000.00"), "USD"),
                ))
                .with_posting(Posting::auto("Equity:Opening")),
        ),
        // Leap year
        Directive::Transaction(
            Transaction::new(leap_date, "Leap day transaction")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Historical:Account",
                    Amount::new(dec("29.02"), "USD"),
                ))
                .with_posting(Posting::auto("Equity:Opening")),
        ),
        // End of month
        Directive::Transaction(
            Transaction::new(end_jan, "End of January")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Historical:Account",
                    Amount::new(dec("31.00"), "USD"),
                ))
                .with_posting(Posting::auto("Equity:Opening")),
        ),
        Directive::Transaction(
            Transaction::new(end_apr, "End of April")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:Historical:Account",
                    Amount::new(dec("30.00"), "USD"),
                ))
                .with_posting(Posting::auto("Equity:Opening")),
        ),
    ];

    EdgeCaseCollection::new("boundary-dates", directives)
}

/// Generate special character edge cases.
///
/// Tests handling of escaped characters and special strings.
pub fn generate_special_character_edge_cases() -> EdgeCaseCollection {
    let base_date = crate::naive_date(2024, 1, 1).unwrap();
    let open_date = base_date.yesterday().ok().unwrap();

    let directives = vec![
        Directive::Open(Open::new(open_date, "Assets:Bank:Checking")),
        Directive::Open(Open::new(open_date, "Expenses:Test")),
        // Quotes in narration (escaped)
        Directive::Transaction(
            Transaction::new(base_date, "Purchase at Joe's Diner")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("25.00"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Backslash in narration
        Directive::Transaction(
            Transaction::new(base_date, r"Path: C:\Users\Documents\file.txt")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("10.00"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Multi-line description split across text
        Directive::Transaction(
            Transaction::new(base_date, "Multi-line description split across text")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("5.00"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Long narration (200 characters)
        Directive::Transaction(
            Transaction::new(base_date, "A".repeat(200))
                .with_flag('*')
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("1.00"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
        // Special whitespace in payee
        Directive::Transaction(
            Transaction::new(base_date, "Regular narration")
                .with_flag('*')
                .with_payee("Company Name") // No tab - tabs are invalid in beancount
                .with_posting(Posting::new(
                    "Expenses:Test",
                    Amount::new(dec("15.00"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:Bank:Checking")),
        ),
    ];

    EdgeCaseCollection::new("special-characters", directives)
}

/// Generate minimal/empty edge cases.
///
/// Tests handling of minimal valid directives.
pub fn generate_minimal_edge_cases() -> EdgeCaseCollection {
    let base_date = crate::naive_date(2024, 1, 1).unwrap();

    let directives = vec![
        // Minimal open
        Directive::Open(Open::new(base_date, "Assets:Minimal")),
        // Open with currencies
        Directive::Open(
            Open::new(base_date, "Assets:WithCurrency").with_currencies(vec!["USD".into()]),
        ),
        // Close
        Directive::Close(Close::new(
            base_date.tomorrow().ok().unwrap(),
            "Assets:Minimal",
        )),
        // Minimal commodity
        Directive::Commodity(Commodity::new(base_date, "MINI")),
        // Minimal price
        Directive::Price(Price::new(
            base_date,
            "MINI",
            Amount::new(dec("1.00"), "USD"),
        )),
        // Minimal note
        Directive::Note(Note::new(base_date, "Assets:WithCurrency", "A note")),
        // Minimal event
        Directive::Event(Event::new(base_date, "type", "value")),
        // Transaction with empty narration
        Directive::Transaction(Transaction::new(base_date, "").with_flag('*').with_posting(
            Posting::new("Assets:WithCurrency", Amount::new(dec("0.00"), "USD")),
        )),
        // Transaction with only auto-balanced postings
        Directive::Transaction(
            Transaction::new(base_date, "Auto-balanced")
                .with_flag('*')
                .with_posting(Posting::new(
                    "Assets:WithCurrency",
                    Amount::new(dec("100.00"), "USD"),
                ))
                .with_posting(Posting::auto("Assets:WithCurrency")),
        ),
    ];

    EdgeCaseCollection::new("minimal", directives)
}

/// Generate a complete beancount file with all edge cases.
///
/// Returns a string containing all edge cases formatted as valid beancount.
pub fn generate_all_edge_cases_beancount() -> String {
    let mut output = String::new();
    output.push_str("; Synthetic edge case beancount file\n");
    output.push_str("; Generated by rustledger synthetic module\n\n");

    for collection in generate_all_edge_cases() {
        output.push_str(&format!(
            "\n; === {} ===\n\n",
            collection.category.to_uppercase()
        ));
        output.push_str(&collection.to_beancount());
    }

    output
}

// Helper function to parse decimal from string
fn dec(s: &str) -> Decimal {
    Decimal::from_str(s).expect("Invalid decimal string")
}

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

    #[test]
    fn test_generate_unicode_edge_cases() {
        let collection = generate_unicode_edge_cases();
        assert!(!collection.directives.is_empty());
        assert_eq!(collection.category, "unicode");

        let text = collection.to_beancount();
        assert!(text.contains("Café"));
        assert!(text.contains("東京"));
    }

    #[test]
    fn test_generate_decimal_edge_cases() {
        let collection = generate_decimal_edge_cases();
        assert!(!collection.directives.is_empty());

        let text = collection.to_beancount();
        assert!(text.contains("0.00012345"));
    }

    #[test]
    fn test_generate_all_edge_cases() {
        let collections = generate_all_edge_cases();
        assert!(!collections.is_empty());

        // Check all categories are present
        let categories: Vec<_> = collections.iter().map(|c| c.category.as_str()).collect();
        assert!(categories.contains(&"unicode"));
        assert!(categories.contains(&"decimals"));
        assert!(categories.contains(&"hierarchy"));
    }

    #[test]
    fn test_generate_all_edge_cases_beancount() {
        let text = generate_all_edge_cases_beancount();
        assert!(text.contains("UNICODE"));
        assert!(text.contains("DECIMALS"));
        assert!(text.contains("HIERARCHY"));
    }
}