use-bai2 0.1.0

Initial BAI2 banking file primitives for RustUse finance crates
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
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

use core::{fmt, str::FromStr};
use std::error::Error;

use use_amount::Amount;
use use_transaction::TransactionDirection;

/// Common BAI2 primitives.
pub mod prelude {
    pub use crate::{
        AccountIdentifierRecord, AccountTrailerRecord, Bai2Error, ContinuationRecord,
        FileHeaderRecord, FileTrailerRecord, FundsTypeCode, GroupHeaderRecord, GroupTrailerRecord,
        NormalizedTransaction, RawRecord, RecordCode, TransactionDetailRecord, TransactionTypeCode,
        parse_line, parse_logical_records,
    };
}

/// Supported BAI2 record codes.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum RecordCode {
    /// `01` file header.
    FileHeader,
    /// `02` group header.
    GroupHeader,
    /// `03` account identifier.
    AccountIdentifier,
    /// `16` transaction detail.
    TransactionDetail,
    /// `49` account trailer.
    AccountTrailer,
    /// `88` continuation.
    Continuation,
    /// `98` group trailer.
    GroupTrailer,
    /// `99` file trailer.
    FileTrailer,
}

impl RecordCode {
    /// Parses a BAI2 record code.
    ///
    /// # Errors
    ///
    /// Returns [`Bai2Error::UnknownRecordCode`] when the code is not supported.
    pub fn new(value: impl AsRef<str>) -> Result<Self, Bai2Error> {
        match value.as_ref().trim() {
            "01" => Ok(Self::FileHeader),
            "02" => Ok(Self::GroupHeader),
            "03" => Ok(Self::AccountIdentifier),
            "16" => Ok(Self::TransactionDetail),
            "49" => Ok(Self::AccountTrailer),
            "88" => Ok(Self::Continuation),
            "98" => Ok(Self::GroupTrailer),
            "99" => Ok(Self::FileTrailer),
            other => Err(Bai2Error::UnknownRecordCode(other.to_string())),
        }
    }

    /// Returns the two-character BAI2 record code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::FileHeader => "01",
            Self::GroupHeader => "02",
            Self::AccountIdentifier => "03",
            Self::TransactionDetail => "16",
            Self::AccountTrailer => "49",
            Self::Continuation => "88",
            Self::GroupTrailer => "98",
            Self::FileTrailer => "99",
        }
    }
}

impl fmt::Display for RecordCode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for RecordCode {
    type Err = Bai2Error;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

/// A parsed BAI2 record with raw fields preserved.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RawRecord {
    code: RecordCode,
    fields: Vec<String>,
}

impl RawRecord {
    /// Creates a raw record.
    #[must_use]
    pub const fn new(code: RecordCode, fields: Vec<String>) -> Self {
        Self { code, fields }
    }

    /// Returns the record code.
    #[must_use]
    pub const fn code(&self) -> RecordCode {
        self.code
    }

    /// Returns raw fields after the record code.
    #[must_use]
    pub fn fields(&self) -> &[String] {
        &self.fields
    }

    fn push_fields(&mut self, fields: Vec<String>) {
        self.fields.extend(fields);
    }
}

/// Parses a single slash-terminated BAI2 line.
///
/// # Errors
///
/// Returns [`Bai2Error`] when the line is empty, lacks a slash terminator, or uses an unsupported
/// record code.
pub fn parse_line(line: &str) -> Result<RawRecord, Bai2Error> {
    let line = line.trim();
    if line.is_empty() {
        return Err(Bai2Error::EmptyLine);
    }

    let Some(content) = line.strip_suffix('/') else {
        return Err(Bai2Error::MissingTerminator);
    };

    let mut parts = content.split(',');
    let code = parts.next().ok_or(Bai2Error::MissingRecordCode)?;
    let code = RecordCode::new(code)?;
    let fields = parts.map(|field| field.trim().to_string()).collect();
    Ok(RawRecord::new(code, fields))
}

/// Parses BAI2 lines and folds `88` continuation records into the previous logical record.
///
/// # Errors
///
/// Returns [`Bai2Error::OrphanContinuation`] when a continuation appears before any logical record,
/// plus any parsing error returned by [`parse_line`].
pub fn parse_logical_records(input: &str) -> Result<Vec<RawRecord>, Bai2Error> {
    let mut records: Vec<RawRecord> = Vec::new();

    for line in input.lines().filter(|line| !line.trim().is_empty()) {
        let record = parse_line(line)?;
        if record.code() == RecordCode::Continuation {
            let Some(previous) = records.last_mut() else {
                return Err(Bai2Error::OrphanContinuation);
            };
            previous.push_fields(record.fields);
        } else {
            records.push(record);
        }
    }

    Ok(records)
}

/// BAI2 file header record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileHeaderRecord {
    sender_id: String,
    receiver_id: String,
    creation_date: String,
    creation_time: String,
    file_id: Option<String>,
}

impl FileHeaderRecord {
    /// Returns the sender identifier.
    #[must_use]
    pub fn sender_id(&self) -> &str {
        &self.sender_id
    }

    /// Returns the receiver identifier.
    #[must_use]
    pub fn receiver_id(&self) -> &str {
        &self.receiver_id
    }

    /// Returns the creation date field.
    #[must_use]
    pub fn creation_date(&self) -> &str {
        &self.creation_date
    }

    /// Returns the creation time field.
    #[must_use]
    pub fn creation_time(&self) -> &str {
        &self.creation_time
    }

    /// Returns the optional file identifier.
    #[must_use]
    pub fn file_id(&self) -> Option<&str> {
        self.file_id.as_deref()
    }
}

impl TryFrom<&RawRecord> for FileHeaderRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::FileHeader)?;
        Ok(Self {
            sender_id: required_field(record, 0, "sender_id")?.to_string(),
            receiver_id: required_field(record, 1, "receiver_id")?.to_string(),
            creation_date: required_field(record, 2, "creation_date")?.to_string(),
            creation_time: required_field(record, 3, "creation_time")?.to_string(),
            file_id: optional_field(record, 4),
        })
    }
}

/// BAI2 group header record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GroupHeaderRecord {
    receiver_id: String,
    originator_id: String,
    group_status: String,
    as_of_date: String,
    as_of_time: String,
}

impl TryFrom<&RawRecord> for GroupHeaderRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::GroupHeader)?;
        Ok(Self {
            receiver_id: required_field(record, 0, "receiver_id")?.to_string(),
            originator_id: required_field(record, 1, "originator_id")?.to_string(),
            group_status: required_field(record, 2, "group_status")?.to_string(),
            as_of_date: required_field(record, 3, "as_of_date")?.to_string(),
            as_of_time: required_field(record, 4, "as_of_time")?.to_string(),
        })
    }
}

impl GroupHeaderRecord {
    /// Returns the receiver identifier.
    #[must_use]
    pub fn receiver_id(&self) -> &str {
        &self.receiver_id
    }

    /// Returns the originator identifier.
    #[must_use]
    pub fn originator_id(&self) -> &str {
        &self.originator_id
    }

    /// Returns the group status field.
    #[must_use]
    pub fn group_status(&self) -> &str {
        &self.group_status
    }

    /// Returns the as-of date field.
    #[must_use]
    pub fn as_of_date(&self) -> &str {
        &self.as_of_date
    }

    /// Returns the as-of time field.
    #[must_use]
    pub fn as_of_time(&self) -> &str {
        &self.as_of_time
    }
}

/// BAI2 account identifier record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccountIdentifierRecord {
    customer_account_number: String,
    currency_code: Option<String>,
    summary_fields: Vec<String>,
}

impl TryFrom<&RawRecord> for AccountIdentifierRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::AccountIdentifier)?;
        Ok(Self {
            customer_account_number: required_field(record, 0, "customer_account_number")?
                .to_string(),
            currency_code: optional_field(record, 1),
            summary_fields: record.fields().get(2..).unwrap_or_default().to_vec(),
        })
    }
}

impl AccountIdentifierRecord {
    /// Returns the customer account number.
    #[must_use]
    pub fn customer_account_number(&self) -> &str {
        &self.customer_account_number
    }

    /// Returns the optional currency code field.
    #[must_use]
    pub fn currency_code(&self) -> Option<&str> {
        self.currency_code.as_deref()
    }

    /// Returns preserved summary fields.
    #[must_use]
    pub fn summary_fields(&self) -> &[String] {
        &self.summary_fields
    }
}

/// A raw BAI2 transaction type code.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TransactionTypeCode(String);

impl TransactionTypeCode {
    /// Creates a raw transaction type code.
    ///
    /// # Errors
    ///
    /// Returns [`Bai2Error::MissingField`] when the code is empty.
    pub fn new(value: impl AsRef<str>) -> Result<Self, Bai2Error> {
        let value = value.as_ref().trim();
        if value.is_empty() {
            return Err(Bai2Error::MissingField {
                record: RecordCode::TransactionDetail,
                field: "transaction_type_code",
            });
        }
        Ok(Self(value.to_string()))
    }

    /// Returns the raw transaction type code.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    fn direction(&self) -> Result<TransactionDirection, Bai2Error> {
        match self.0.as_bytes().first().copied() {
            Some(b'1' | b'2' | b'3') => Ok(TransactionDirection::Inflow),
            Some(b'4' | b'5' | b'6') => Ok(TransactionDirection::Outflow),
            _ => Err(Bai2Error::UnknownTransactionDirection(self.0.clone())),
        }
    }
}

/// A raw BAI2 funds type code.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct FundsTypeCode(String);

impl FundsTypeCode {
    /// Creates a raw funds type code.
    ///
    /// # Errors
    ///
    /// Returns [`Bai2Error::MissingField`] when the code is empty.
    pub fn new(value: impl AsRef<str>) -> Result<Self, Bai2Error> {
        let value = value.as_ref().trim();
        if value.is_empty() {
            return Err(Bai2Error::MissingField {
                record: RecordCode::TransactionDetail,
                field: "funds_type_code",
            });
        }
        Ok(Self(value.to_string()))
    }

    /// Returns the raw funds type code.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// BAI2 transaction detail record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TransactionDetailRecord {
    transaction_type: TransactionTypeCode,
    amount: Amount,
    funds_type: Option<FundsTypeCode>,
    bank_reference: Option<String>,
    customer_reference: Option<String>,
    text: Option<String>,
}

impl TryFrom<&RawRecord> for TransactionDetailRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::TransactionDetail)?;
        let transaction_type =
            TransactionTypeCode::new(required_field(record, 0, "transaction_type_code")?)?;
        let amount = parse_amount(required_field(record, 1, "amount")?)?;
        let funds_type = match optional_field(record, 2) {
            Some(value) => Some(FundsTypeCode::new(value)?),
            None => None,
        };
        let text = record.fields().get(5..).and_then(|fields| {
            if fields.is_empty() {
                None
            } else {
                Some(fields.join(","))
            }
        });

        Ok(Self {
            transaction_type,
            amount,
            funds_type,
            bank_reference: optional_field(record, 3),
            customer_reference: optional_field(record, 4),
            text,
        })
    }
}

impl TransactionDetailRecord {
    /// Returns the transaction type code.
    #[must_use]
    pub const fn transaction_type(&self) -> &TransactionTypeCode {
        &self.transaction_type
    }

    /// Returns the transaction amount, interpreted as minor units with scale 2.
    #[must_use]
    pub const fn amount(&self) -> Amount {
        self.amount
    }

    /// Returns the optional funds type code.
    #[must_use]
    pub const fn funds_type(&self) -> Option<&FundsTypeCode> {
        self.funds_type.as_ref()
    }

    /// Returns the optional bank reference.
    #[must_use]
    pub fn bank_reference(&self) -> Option<&str> {
        self.bank_reference.as_deref()
    }

    /// Returns the optional customer reference.
    #[must_use]
    pub fn customer_reference(&self) -> Option<&str> {
        self.customer_reference.as_deref()
    }

    /// Returns the optional transaction text.
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        self.text.as_deref()
    }
}

/// BAI2 continuation record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContinuationRecord {
    fields: Vec<String>,
}

impl TryFrom<&RawRecord> for ContinuationRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::Continuation)?;
        Ok(Self {
            fields: record.fields().to_vec(),
        })
    }
}

impl ContinuationRecord {
    /// Returns continuation fields.
    #[must_use]
    pub fn fields(&self) -> &[String] {
        &self.fields
    }
}

/// BAI2 account trailer record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccountTrailerRecord {
    account_control_total: Option<i128>,
    record_count: Option<usize>,
}

impl TryFrom<&RawRecord> for AccountTrailerRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::AccountTrailer)?;
        Ok(Self {
            account_control_total: optional_i128(record, 0)?,
            record_count: optional_usize(record, 1)?,
        })
    }
}

impl AccountTrailerRecord {
    /// Returns the optional account control total.
    #[must_use]
    pub const fn account_control_total(&self) -> Option<i128> {
        self.account_control_total
    }

    /// Returns the optional record count.
    #[must_use]
    pub const fn record_count(&self) -> Option<usize> {
        self.record_count
    }
}

/// BAI2 group trailer record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GroupTrailerRecord {
    group_control_total: Option<i128>,
    account_count: Option<usize>,
    record_count: Option<usize>,
}

impl TryFrom<&RawRecord> for GroupTrailerRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::GroupTrailer)?;
        Ok(Self {
            group_control_total: optional_i128(record, 0)?,
            account_count: optional_usize(record, 1)?,
            record_count: optional_usize(record, 2)?,
        })
    }
}

impl GroupTrailerRecord {
    /// Returns the optional group control total.
    #[must_use]
    pub const fn group_control_total(&self) -> Option<i128> {
        self.group_control_total
    }

    /// Returns the optional account count.
    #[must_use]
    pub const fn account_count(&self) -> Option<usize> {
        self.account_count
    }

    /// Returns the optional record count.
    #[must_use]
    pub const fn record_count(&self) -> Option<usize> {
        self.record_count
    }
}

/// BAI2 file trailer record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileTrailerRecord {
    file_control_total: Option<i128>,
    group_count: Option<usize>,
    record_count: Option<usize>,
}

impl TryFrom<&RawRecord> for FileTrailerRecord {
    type Error = Bai2Error;

    fn try_from(record: &RawRecord) -> Result<Self, Self::Error> {
        ensure_code(record, RecordCode::FileTrailer)?;
        Ok(Self {
            file_control_total: optional_i128(record, 0)?,
            group_count: optional_usize(record, 1)?,
            record_count: optional_usize(record, 2)?,
        })
    }
}

impl FileTrailerRecord {
    /// Returns the optional file control total.
    #[must_use]
    pub const fn file_control_total(&self) -> Option<i128> {
        self.file_control_total
    }

    /// Returns the optional group count.
    #[must_use]
    pub const fn group_count(&self) -> Option<usize> {
        self.group_count
    }

    /// Returns the optional record count.
    #[must_use]
    pub const fn record_count(&self) -> Option<usize> {
        self.record_count
    }

    /// Validates a parsed logical record count against the trailer record count when present.
    ///
    /// # Errors
    ///
    /// Returns [`Bai2Error::InvalidCount`] when the expected count is present and differs.
    pub const fn validate_record_count(&self, actual: usize) -> Result<(), Bai2Error> {
        match self.record_count {
            Some(expected) if expected != actual => Err(Bai2Error::InvalidCount),
            _ => Ok(()),
        }
    }
}

/// A normalized transaction detail value.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NormalizedTransaction {
    transaction_type: TransactionTypeCode,
    amount: Amount,
    direction: TransactionDirection,
    bank_reference: Option<String>,
    customer_reference: Option<String>,
    text: Option<String>,
}

impl NormalizedTransaction {
    /// Normalizes a BAI2 transaction detail record.
    ///
    /// # Errors
    ///
    /// Returns [`Bai2Error::UnknownTransactionDirection`] when the raw type code cannot be mapped
    /// into a conservative inflow or outflow direction.
    pub fn from_detail(detail: &TransactionDetailRecord) -> Result<Self, Bai2Error> {
        Ok(Self {
            transaction_type: detail.transaction_type.clone(),
            amount: detail.amount,
            direction: detail.transaction_type.direction()?,
            bank_reference: detail.bank_reference.clone(),
            customer_reference: detail.customer_reference.clone(),
            text: detail.text.clone(),
        })
    }

    /// Returns the raw transaction type code.
    #[must_use]
    pub const fn transaction_type(&self) -> &TransactionTypeCode {
        &self.transaction_type
    }

    /// Returns the normalized amount.
    #[must_use]
    pub const fn amount(&self) -> Amount {
        self.amount
    }

    /// Returns the normalized direction.
    #[must_use]
    pub const fn direction(&self) -> TransactionDirection {
        self.direction
    }

    /// Returns the optional bank reference.
    #[must_use]
    pub fn bank_reference(&self) -> Option<&str> {
        self.bank_reference.as_deref()
    }

    /// Returns the optional customer reference.
    #[must_use]
    pub fn customer_reference(&self) -> Option<&str> {
        self.customer_reference.as_deref()
    }

    /// Returns the optional transaction text.
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        self.text.as_deref()
    }
}

/// Errors returned by BAI2 parsing and validation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Bai2Error {
    /// The input line was empty.
    EmptyLine,
    /// A BAI2 line did not end with `/`.
    MissingTerminator,
    /// A record code was missing.
    MissingRecordCode,
    /// The record code is unsupported.
    UnknownRecordCode(String),
    /// A record had an unexpected code.
    UnexpectedRecordCode {
        /// Expected record code.
        expected: RecordCode,
        /// Actual record code.
        actual: RecordCode,
    },
    /// A required field was missing.
    MissingField {
        /// Record code.
        record: RecordCode,
        /// Field name.
        field: &'static str,
    },
    /// An amount field was invalid.
    InvalidAmount,
    /// A count field was invalid or unexpected.
    InvalidCount,
    /// A continuation record appeared before a logical record.
    OrphanContinuation,
    /// A transaction type code could not be mapped into a direction.
    UnknownTransactionDirection(String),
}

impl fmt::Display for Bai2Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyLine => formatter.write_str("BAI2 line cannot be empty"),
            Self::MissingTerminator => formatter.write_str("BAI2 line must end with /"),
            Self::MissingRecordCode => formatter.write_str("BAI2 record code is missing"),
            Self::UnknownRecordCode(code) => {
                write!(formatter, "unsupported BAI2 record code: {code}")
            },
            Self::UnexpectedRecordCode { expected, actual } => write!(
                formatter,
                "expected BAI2 record code {expected}, got {actual}"
            ),
            Self::MissingField { record, field } => {
                write!(formatter, "BAI2 record {record} missing field {field}")
            },
            Self::InvalidAmount => formatter.write_str("BAI2 amount field is invalid"),
            Self::InvalidCount => formatter.write_str("BAI2 count field is invalid"),
            Self::OrphanContinuation => {
                formatter.write_str("BAI2 continuation record has no parent")
            },
            Self::UnknownTransactionDirection(code) => write!(
                formatter,
                "BAI2 transaction type code {code} has unknown direction"
            ),
        }
    }
}

impl Error for Bai2Error {}

fn ensure_code(record: &RawRecord, expected: RecordCode) -> Result<(), Bai2Error> {
    if record.code() == expected {
        Ok(())
    } else {
        Err(Bai2Error::UnexpectedRecordCode {
            expected,
            actual: record.code(),
        })
    }
}

fn required_field<'a>(
    record: &'a RawRecord,
    index: usize,
    field: &'static str,
) -> Result<&'a str, Bai2Error> {
    let value = record
        .fields()
        .get(index)
        .map(String::as_str)
        .unwrap_or_default()
        .trim();
    if value.is_empty() {
        Err(Bai2Error::MissingField {
            record: record.code(),
            field,
        })
    } else {
        Ok(value)
    }
}

fn optional_field(record: &RawRecord, index: usize) -> Option<String> {
    record.fields().get(index).and_then(|value| {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    })
}

fn optional_i128(record: &RawRecord, index: usize) -> Result<Option<i128>, Bai2Error> {
    optional_field(record, index)
        .map(|value| value.parse::<i128>().map_err(|_| Bai2Error::InvalidAmount))
        .transpose()
}

fn optional_usize(record: &RawRecord, index: usize) -> Result<Option<usize>, Bai2Error> {
    optional_field(record, index)
        .map(|value| value.parse::<usize>().map_err(|_| Bai2Error::InvalidCount))
        .transpose()
}

fn parse_amount(value: &str) -> Result<Amount, Bai2Error> {
    let minor_units = value
        .parse::<i128>()
        .map_err(|_| Bai2Error::InvalidAmount)?;
    Amount::from_minor_units(minor_units, 2).map_err(|_| Bai2Error::InvalidAmount)
}

#[cfg(test)]
mod tests {
    use use_transaction::TransactionDirection;

    use super::{
        Bai2Error, FileTrailerRecord, NormalizedTransaction, RawRecord, RecordCode,
        TransactionDetailRecord, parse_line, parse_logical_records,
    };

    #[test]
    fn parses_transaction_detail_line() -> Result<(), Box<dyn std::error::Error>> {
        let record = parse_line("16,475,12345,Z,bank-ref,customer-ref,payment/")?;
        let detail = TransactionDetailRecord::try_from(&record)?;
        let normalized = NormalizedTransaction::from_detail(&detail)?;

        assert_eq!(record.code(), RecordCode::TransactionDetail);
        assert_eq!(detail.amount().minor_units(), 12_345);
        assert_eq!(detail.bank_reference(), Some("bank-ref"));
        assert_eq!(normalized.direction(), TransactionDirection::Outflow);
        Ok(())
    }

    #[test]
    fn folds_continuation_records() -> Result<(), Box<dyn std::error::Error>> {
        let records = parse_logical_records(
            "16,475,12345,Z,bank-ref,customer-ref,first/\n88,second,third/\n",
        )?;
        let detail = TransactionDetailRecord::try_from(&records[0])?;

        assert_eq!(records.len(), 1);
        assert_eq!(detail.text(), Some("first,second,third"));
        Ok(())
    }

    #[test]
    fn rejects_invalid_record_code_and_orphan_continuation() {
        assert_eq!(
            parse_line("77,abc/"),
            Err(Bai2Error::UnknownRecordCode("77".to_string()))
        );
        assert_eq!(
            parse_logical_records("88,orphan/"),
            Err(Bai2Error::OrphanContinuation)
        );
    }

    #[test]
    fn validates_file_trailer_count() -> Result<(), Box<dyn std::error::Error>> {
        let trailer_record = RawRecord::new(
            RecordCode::FileTrailer,
            vec!["0".to_string(), "1".to_string(), "3".to_string()],
        );
        let trailer = FileTrailerRecord::try_from(&trailer_record)?;

        assert_eq!(trailer.validate_record_count(3), Ok(()));
        assert_eq!(
            trailer.validate_record_count(2),
            Err(Bai2Error::InvalidCount)
        );
        Ok(())
    }
}