kontochronik 0.4.0

Long-Term archive for account transactions
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
//! Import adapter for the CSV exports ("CSV-CAMT" and "CSV-MT940")
//! of the Sparkasse / Kreissparkasse online banking.

use anyhow::{Context as _, bail};
use csv::ReaderBuilder;
use rust_decimal::Decimal;
use serde::Deserialize;
use time::Date;

use crate::{
    archive::ArchiveRecord,
    util::{canonical_text, clean_optional, is_zero_placeholder, read_to_utf8},
};

const CSV_DELIMITER: u8 = b';';

const INFO_BOOKED: &str = "Umsatz gebucht";
const INFO_PENDING: &str = "Umsatz vorgemerkt";

/// One row of the Sparkasse CSV-CAMT export.
/// Columns without an archive counterpart (see [`parse_sparkasse`])
/// have no field here and are skipped during deserialization;
/// [`CAMT_HEADERS`] still names them.
#[derive(Debug, Deserialize)]
struct CamtRecord {
    #[serde(rename = "Auftragskonto")]
    account_iban: String,

    #[serde(rename = "Buchungstag", with = "short_german_date")]
    booking_date: Date,

    #[serde(rename = "Valutadatum", with = "short_german_date")]
    value_date: Date,

    #[serde(rename = "Buchungstext")]
    booking_text: String,

    #[serde(rename = "Verwendungszweck")]
    purpose: Option<String>,

    #[serde(rename = "Glaeubiger ID")]
    creditor_id: Option<String>,

    #[serde(rename = "Mandatsreferenz")]
    mandate_reference: Option<String>,

    #[serde(rename = "Beguenstigter/Zahlungspflichtiger")]
    participant_name: Option<String>,

    #[serde(rename = "Kontonummer/IBAN")]
    participant_iban: Option<String>,

    #[serde(rename = "BIC (SWIFT-Code)")]
    participant_bic: Option<String>,

    #[serde(rename = "Betrag", with = "crate::util::german_number")]
    amount: Decimal,

    #[serde(rename = "Waehrung")]
    currency: String,

    #[serde(rename = "Info")]
    info: String,

    // CAMT-52 V8 exports drop this column entirely.
    #[serde(rename = "Kategorie", default)]
    category: Option<String>,
}

impl TryFrom<CamtRecord> for ArchiveRecord {
    type Error = anyhow::Error;

    fn try_from(row: CamtRecord) -> Result<Self, Self::Error> {
        let CamtRecord {
            account_iban,
            booking_date,
            value_date,
            booking_text,
            purpose,
            creditor_id,
            mandate_reference,
            participant_name,
            participant_iban,
            participant_bic,
            amount,
            currency,
            info: _,
            category,
        } = row;
        // Portal annotations are out of scope for the archive;
        if let Some(category) = clean_optional(category) {
            bail!(
                "\"Kategorie\" contains data ({category:?}) - portal annotations are not archived"
            );
        }
        Ok(Self {
            booking_date,
            value_date,
            amount,
            currency: canonical_text(&currency),
            participant_name: clean_optional(participant_name),
            purpose: clean_optional(purpose),
            booking_text: canonical_text(&booking_text),
            // Bookings without a counterparty account (e.g. cash
            // withdrawals) carry an all-zero placeholder instead.
            participant_iban: clean_optional(participant_iban)
                .filter(|iban| !is_zero_placeholder(iban)),
            participant_bic: clean_optional(participant_bic),
            creditor_id: clean_optional(creditor_id),
            mandate_reference: clean_optional(mandate_reference),
            balance_after_booking: None,
            account_iban: account_iban
                .parse()
                .with_context(|| format!("Invalid \"Auftragskonto\" {account_iban:?}"))?,
            account_bic: None,
            account_bank_name: None,
            fingerprint: None,
        })
    }
}

/// Every column the CSV-CAMT export is known to contain.
/// Serves as a tripwire:
/// an unknown column means the bank changed its format, and silently
/// ignoring it could silently ignore data.
const CAMT_HEADERS: [&str; 18] = [
    "Auftragskonto",
    "Buchungstag",
    "Valutadatum",
    "Buchungstext",
    "Verwendungszweck",
    "Glaeubiger ID",
    "Mandatsreferenz",
    "Kundenreferenz (End-to-End)",
    "Sammlerreferenz",
    "Lastschrift Ursprungsbetrag",
    "Auslagenersatz Ruecklastschrift",
    "Beguenstigter/Zahlungspflichtiger",
    "Kontonummer/IBAN",
    "BIC (SWIFT-Code)",
    "Betrag",
    "Waehrung",
    "Info",
    "Kategorie",
];

/// One row of the Sparkasse CSV-MT940 export.
/// Despite the legacy column names, "Kontonummer" and "BLZ" carry
/// IBAN and BIC. The dates stay raw strings here because pending rows
/// leave them empty; they are parsed once the row is known to be booked.
#[derive(Debug, Deserialize)]
struct Mt940Record {
    #[serde(rename = "Auftragskonto")]
    account_iban: String,

    #[serde(rename = "Buchungstag")]
    booking_date: String,

    #[serde(rename = "Valutadatum")]
    value_date: String,

    #[serde(rename = "Buchungstext")]
    booking_text: String,

    #[serde(rename = "Verwendungszweck")]
    purpose: Option<String>,

    #[serde(rename = "Beguenstigter/Zahlungspflichtiger")]
    participant_name: Option<String>,

    #[serde(rename = "Kontonummer")]
    participant_iban: Option<String>,

    #[serde(rename = "BLZ")]
    participant_bic: Option<String>,

    #[serde(rename = "Betrag", with = "crate::util::german_number")]
    amount: Decimal,

    #[serde(rename = "Waehrung")]
    currency: String,

    #[serde(rename = "Info")]
    info: String,
}

impl TryFrom<Mt940Record> for ArchiveRecord {
    type Error = anyhow::Error;

    fn try_from(row: Mt940Record) -> Result<Self, Self::Error> {
        let Mt940Record {
            account_iban,
            booking_date,
            value_date,
            booking_text,
            purpose,
            participant_name,
            participant_iban,
            participant_bic,
            amount,
            currency,
            info: _,
        } = row;
        let booking_date = short_german_date::parse(&booking_date)
            .with_context(|| format!("Invalid \"Buchungstag\" {booking_date:?}"))?;
        let value_date = short_german_date::parse(&value_date)
            .with_context(|| format!("Invalid \"Valutadatum\" {value_date:?}"))?;
        Ok(Self {
            booking_date,
            value_date,
            amount,
            currency: canonical_text(&currency),
            participant_name: clean_optional(participant_name),
            purpose: clean_optional(purpose),
            booking_text: canonical_text(&booking_text),
            participant_iban: clean_optional(participant_iban),
            participant_bic: clean_optional(participant_bic),
            creditor_id: None,
            mandate_reference: None,
            balance_after_booking: None,
            account_iban: account_iban
                .parse()
                .with_context(|| format!("Invalid \"Auftragskonto\" {account_iban:?}"))?,
            account_bic: None,
            account_bank_name: None,
            fingerprint: None,
        })
    }
}

/// Every column the CSV-MT940 export is known to contain.
/// Serves as a tripwire like [`CAMT_HEADERS`].
const MT940_HEADERS: [&str; 11] = [
    "Auftragskonto",
    "Buchungstag",
    "Valutadatum",
    "Buchungstext",
    "Verwendungszweck",
    "Beguenstigter/Zahlungspflichtiger",
    "Kontonummer",
    "BLZ",
    "Betrag",
    "Waehrung",
    "Info",
];

/// The two CSV variants the Sparkasse online banking exports.
enum Variant {
    Camt,
    Mt940,
}

/// Parses a CSV export of the Sparkasse / Kreissparkasse online
/// banking into archive records.
/// The export variant (CSV-CAMT with or without the "Kategorie"
/// column, e.g. CAMT-52 V8, or CSV-MT940) is detected by its
/// header line.
///
/// Prefer the CSV-CAMT export: CSV-MT940 carries neither creditor id
/// nor mandate reference and packs SEPA tags into the purpose text,
/// so its archived entries hold less detail.
pub fn parse_sparkasse(bytes: &[u8]) -> anyhow::Result<Vec<ArchiveRecord>> {
    let text = read_to_utf8(bytes)?;
    let mut rdr = ReaderBuilder::new()
        .delimiter(CSV_DELIMITER)
        .from_reader(text.as_bytes());
    let headers = rdr.headers()?.clone();
    match detect_variant(&headers)? {
        Variant::Camt => booked_records(rdr.deserialize(), |row: &CamtRecord| row.info.as_str()),
        Variant::Mt940 => {
            log::info!(
                "Detected the CSV-MT940 variant - prefer the CSV-CAMT export \
                 when available, it carries more detail"
            );
            booked_records(rdr.deserialize(), |row: &Mt940Record| row.info.as_str())
        }
    }
}

/// The variants differ in their participant columns:
/// CSV-CAMT names them "Kontonummer/IBAN" and "BIC (SWIFT-Code)",
/// CSV-MT940 "Kontonummer" and "BLZ".
/// Rejects files with columns this adapter doesn't know.
fn detect_variant(headers: &csv::StringRecord) -> anyhow::Result<Variant> {
    let headers: Vec<&str> = headers.iter().map(str::trim).collect();
    let (variant, known): (Variant, &[&str]) = if headers.contains(&"Kontonummer/IBAN") {
        (Variant::Camt, &CAMT_HEADERS)
    } else {
        (Variant::Mt940, &MT940_HEADERS)
    };
    for header in headers {
        if !known.contains(&header) {
            bail!(
                "Sparkasse export contains unknown column {header:?} - \
                 the import adapter must be updated before this data can be archived"
            );
        }
    }
    Ok(variant)
}

/// Converts the booked rows and skips the pending ones
/// ("Umsatz vorgemerkt"), which are not part of the ledger yet.
fn booked_records<R>(
    rows: impl Iterator<Item = csv::Result<R>>,
    info: impl Fn(&R) -> &str,
) -> anyhow::Result<Vec<ArchiveRecord>>
where
    ArchiveRecord: TryFrom<R, Error = anyhow::Error>,
{
    let mut pending = 0;
    let mut records = vec![];
    for row in rows {
        let row = row?;
        match info(&row).trim() {
            INFO_BOOKED => records.push(ArchiveRecord::try_from(row)?),
            INFO_PENDING => pending += 1,
            other => bail!(
                "Sparkasse export contains unknown \"Info\" value {other:?} - \
                 the import adapter must be updated before this data can be archived"
            ),
        }
    }
    if pending > 0 {
        log::info!("Skipped {pending} pending entries (\"{INFO_PENDING}\")");
    }
    Ok(records)
}

mod short_german_date {
    //! `TT.MM.JJ`: two-digit years become `20JJ` (no Sparkasse CSV
    //! export predates 2000); four-digit years pass unchanged.

    use serde::{Deserialize, Deserializer};
    use time::{Date, format_description::FormatItem, macros::format_description};

    const DATE_FMT: &[FormatItem<'static>] = format_description!("[day].[month].[year]");

    pub fn parse(s: &str) -> Result<Date, time::error::Parse> {
        let s = s.trim();
        let expanded = match s.rsplit_once('.') {
            Some((day_month, year)) if year.len() == 2 => format!("{day_month}.20{year}"),
            _ => s.to_owned(),
        };
        Date::parse(&expanded, DATE_FMT)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Date, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        parse(&s).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        path::{Path, PathBuf},
    };

    use super::*;

    use crate::{GapPolicy, ImportSummary, VerifySummary, import, read_archive, verify_archive};

    const CAMT_HEADER: &str = "Auftragskonto;Buchungstag;Valutadatum;\
        Buchungstext;Verwendungszweck;Glaeubiger ID;Mandatsreferenz;\
        Kundenreferenz (End-to-End);Sammlerreferenz;\
        Lastschrift Ursprungsbetrag;Auslagenersatz Ruecklastschrift;\
        Beguenstigter/Zahlungspflichtiger;Kontonummer/IBAN;BIC (SWIFT-Code);\
        Betrag;Waehrung;Info;Kategorie";

    const SALARY: &str = "DE44500105175407324931;01.01.26;01.01.26;\
        GUTSCHR. UEBERWEISUNG;Gehalt Januar;;;NOTPROVIDED;;;;ACME GmbH;\
        DE02300209000106531065;CMCIDEDD;1000,00;EUR;Umsatz gebucht;";

    const BAKERY: &str = "DE44500105175407324931;02.01.26;02.01.26;\
        KARTENZAHLUNG;2026-01-01T10:52 Debitk.1 2029-12 ;;;68000123();;;;\
        Bäckerei Müller;DE02120300000000202051;BYLADEM1001;-3,50;EUR;\
        Umsatz gebucht;";

    const POWER: &str = "DE44500105175407324931;03.01.26;03.01.26;\
        FOLGELASTSCHRIFT;Strom Abschlag;DE98ZZZ09999999999;M-001;;;;;\
        Stadtwerke;DE02500105170137075030;INGDDEFF;-45,00;EUR;\
        Umsatz gebucht;";

    const PENDING: &str = "DE44500105175407324931;04.01.26;05.01.26;\
        SEPA-ELV-LASTSCHRIFT;Tanken;DE98ZZZ09999999999;M-002;;;;;\
        Tankstelle;DE02100100100006820101;PBNKDEFF;-50,00;EUR;\
        Umsatz vorgemerkt;";

    const MT940_HEADER: &str = "Auftragskonto;Buchungstag;Valutadatum;\
        Buchungstext;Verwendungszweck;Beguenstigter/Zahlungspflichtiger;\
        Kontonummer;BLZ;Betrag;Waehrung;Info";

    /// The same booking as [`SALARY`], exported in the MT940 variant.
    const MT940_SALARY: &str = "DE44500105175407324931;01.01.26;01.01.26;\
        GUTSCHR. UEBERWEISUNG;Gehalt Januar;ACME GmbH;\
        DE02300209000106531065;CMCIDEDD;1000,00;EUR;Umsatz gebucht";

    /// Pending entries leave the date columns empty in this variant.
    const MT940_PENDING: &str = "DE44500105175407324931;;;\
        SEPA-ELV-LASTSCHRIFT;Tanken;Tankstelle;\
        DE02100100100006820101;PBNKDEFF;-50,00;EUR;Umsatz vorgemerkt";

    fn export_file(dir: &Path, name: &str, header: &str, rows: &[&str]) -> PathBuf {
        let mut content = header.to_owned();
        for row in rows {
            content.push('\n');
            content.push_str(row);
        }
        content.push('\n');
        let path = dir.join(name);
        fs::write(&path, content).unwrap();
        path
    }

    fn camt_file(dir: &Path, name: &str, rows: &[&str]) -> PathBuf {
        export_file(dir, name, CAMT_HEADER, rows)
    }

    fn mt940_file(dir: &Path, name: &str, rows: &[&str]) -> PathBuf {
        export_file(dir, name, MT940_HEADER, rows)
    }

    #[test]
    fn archives_only_what_the_bank_delivered() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = camt_file(dir.path(), "export.csv", &[POWER, BAKERY, SALARY]);

        let summary = import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(
            summary,
            ImportSummary {
                imported: 3,
                duplicates: 0,
                total: 3
            }
        );

        let records = read_archive(&archive_path).unwrap();
        let dates: Vec<String> = records
            .iter()
            .map(|record| record.booking_date.to_string())
            .collect();
        assert_eq!(dates, ["2026-01-03", "2026-01-02", "2026-01-01"]);
        assert!(
            records
                .iter()
                .all(|record| record.balance_after_booking.is_none())
        );
        assert!(
            records.iter().all(|record| {
                record.account_bic.is_none() && record.account_bank_name.is_none()
            })
        );
        assert_eq!(
            records[0].creditor_id.as_deref(),
            Some("DE98ZZZ09999999999")
        );
        assert_eq!(
            records[1].participant_name.as_deref(),
            Some("Bäckerei Müller")
        );
        assert_eq!(records[2].amount.to_string(), "1000.00");

        let summary = verify_archive(&archive_path).unwrap();
        assert_eq!(
            summary,
            VerifySummary {
                total: 3,
                missing_fingerprints: 0,
                missing_balances: 3
            }
        );
    }

    #[test]
    fn pending_entries_are_skipped() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = camt_file(dir.path(), "export.csv", &[PENDING, POWER, BAKERY, SALARY]);

        let summary = import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(summary.imported, 3);

        let records = read_archive(&archive_path).unwrap();
        assert!(
            records
                .iter()
                .all(|record| record.purpose.as_deref() != Some("Tanken"))
        );
    }

    #[test]
    fn merges_overlapping_exports() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let first = camt_file(dir.path(), "export1.csv", &[BAKERY, SALARY]);
        let second = camt_file(dir.path(), "export2.csv", &[POWER, BAKERY]);

        import(parse_sparkasse, &first, &archive_path, GapPolicy::Reject).unwrap();
        let summary = import(parse_sparkasse, &second, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(
            summary,
            ImportSummary {
                imported: 1,
                duplicates: 1,
                total: 3
            }
        );

        verify_archive(&archive_path).unwrap();
    }

    #[test]
    fn a_file_without_overlap_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let first = camt_file(dir.path(), "export1.csv", &[SALARY]);
        let second = camt_file(dir.path(), "export2.csv", &[POWER]);

        import(parse_sparkasse, &first, &archive_path, GapPolicy::Reject).unwrap();
        let before = fs::read(&archive_path).unwrap();

        let error = import(parse_sparkasse, &second, &archive_path, GapPolicy::Reject).unwrap_err();
        assert!(format!("{error:#}").contains("does not overlap"));
        assert_eq!(fs::read(&archive_path).unwrap(), before);

        let summary = import(parse_sparkasse, &second, &archive_path, GapPolicy::Accept).unwrap();
        assert_eq!(summary.imported, 1);
    }

    #[test]
    fn oldest_first_files_are_flipped() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = camt_file(dir.path(), "export.csv", &[SALARY, BAKERY, POWER]);

        import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap();

        let records = read_archive(&archive_path).unwrap();
        let dates: Vec<String> = records
            .iter()
            .map(|record| record.booking_date.to_string())
            .collect();
        assert_eq!(dates, ["2026-01-03", "2026-01-02", "2026-01-01"]);
    }

    #[test]
    fn four_digit_years_are_accepted() {
        let with_full_year: &str = &SALARY.replace("01.01.26", "01.01.2026");
        assert_ne!(with_full_year, SALARY);
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = camt_file(dir.path(), "export.csv", &[with_full_year]);

        import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap();

        let records = read_archive(&archive_path).unwrap();
        assert_eq!(records[0].booking_date.to_string(), "2026-01-01");
    }

    #[test]
    fn rejects_unknown_info_values() {
        let cancelled: &str = &SALARY.replace("Umsatz gebucht", "Umsatz storniert");
        assert_ne!(cancelled, SALARY);
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = camt_file(dir.path(), "export.csv", &[cancelled]);

        let error = import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap_err();
        assert!(format!("{error:#}").contains("Umsatz storniert"));
    }

    #[test]
    fn rejects_filled_portal_annotations() {
        let categorized: &str = &SALARY.replace("Umsatz gebucht;", "Umsatz gebucht;Einkommen");
        assert_ne!(categorized, SALARY);
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = camt_file(dir.path(), "export.csv", &[categorized]);

        let error = import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap_err();
        assert!(format!("{error:#}").contains("Kategorie"));
    }

    #[test]
    fn rejects_unknown_export_columns() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let path = dir.path().join("export.csv");
        fs::write(&path, format!("{CAMT_HEADER};Neue Spalte\n{SALARY};x\n")).unwrap();

        let error = import(parse_sparkasse, &path, &archive_path, GapPolicy::Reject).unwrap_err();
        assert!(format!("{error:#}").contains("Neue Spalte"));
    }

    #[test]
    fn mt940_variant_is_detected_and_imported() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = mt940_file(dir.path(), "export.csv", &[MT940_SALARY]);

        let summary = import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(summary.imported, 1);

        let records = read_archive(&archive_path).unwrap();
        assert_eq!(records[0].booking_date.to_string(), "2026-01-01");
        assert_eq!(
            records[0].participant_iban.as_deref(),
            Some("DE02300209000106531065")
        );
        assert_eq!(records[0].participant_bic.as_deref(), Some("CMCIDEDD"));
        assert_eq!(records[0].creditor_id, None);
        assert!(records[0].balance_after_booking.is_none());
    }

    #[test]
    fn mt940_pending_entries_without_dates_are_skipped() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let export = mt940_file(dir.path(), "export.csv", &[MT940_PENDING, MT940_SALARY]);

        let summary = import(parse_sparkasse, &export, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(summary.imported, 1);
    }

    #[test]
    fn the_variants_deduplicate_each_others_bookings() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let camt = camt_file(dir.path(), "camt.csv", &[SALARY]);
        let mt940 = mt940_file(dir.path(), "mt940.csv", &[MT940_SALARY]);

        import(parse_sparkasse, &camt, &archive_path, GapPolicy::Reject).unwrap();
        let summary = import(parse_sparkasse, &mt940, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(
            summary,
            ImportSummary {
                imported: 0,
                duplicates: 1,
                total: 1
            }
        );
    }

    #[test]
    fn camt_v8_without_kategorie_column_is_imported() {
        let v8_header = CAMT_HEADER.replace(";Kategorie", "");
        assert_ne!(v8_header, CAMT_HEADER);
        let v8_row = SALARY.strip_suffix(';').unwrap();
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let path = dir.path().join("export.csv");
        fs::write(&path, format!("{v8_header}\n{v8_row}\n")).unwrap();

        let summary = import(parse_sparkasse, &path, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(summary.imported, 1);
    }

    /// The formats render the purpose of the same booking differently
    /// (SEPA tags, punctuation), so it is not part of the fingerprint;
    /// the booking must still be recognized as a duplicate.
    #[test]
    fn differently_rendered_purposes_deduplicate() {
        let tagged: &str = &MT940_SALARY.replace("Gehalt Januar", "SVWZ+Gehalt  Januar");
        assert_ne!(tagged, MT940_SALARY);
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let camt = camt_file(dir.path(), "camt.csv", &[SALARY]);
        let mt940 = mt940_file(dir.path(), "mt940.csv", &[tagged]);

        import(parse_sparkasse, &camt, &archive_path, GapPolicy::Reject).unwrap();
        let summary = import(parse_sparkasse, &mt940, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(
            summary,
            ImportSummary {
                imported: 0,
                duplicates: 1,
                total: 1
            }
        );
    }

    /// A cash withdrawal has no counterparty account: MT940 leaves the
    /// column empty, CAMT renders the placeholder "0" (and a BLZ in the
    /// BIC column).
    #[test]
    fn missing_counterparty_renderings_deduplicate() {
        let mt940_row = "DE44500105175407324931;28.04.26;28.04.26;\
            BARGELDAUSZAHLUNG;28.04;GA NR00002253;;60050020;-30;EUR;Umsatz gebucht";
        let camt_row = "DE44500105175407324931;28.04.26;28.04.26;\
            BARGELDAUSZAHLUNG;Baz;;;;;;;GA NR00002253;0000000000;60050020;-30;EUR;Umsatz gebucht;";
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let camt = camt_file(dir.path(), "camt.csv", &[camt_row]);
        let mt940 = mt940_file(dir.path(), "mt940.csv", &[mt940_row]);

        import(parse_sparkasse, &camt, &archive_path, GapPolicy::Reject).unwrap();
        let records = read_archive(&archive_path).unwrap();
        assert_eq!(records[0].participant_iban, None);

        let summary = import(parse_sparkasse, &mt940, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(
            summary,
            ImportSummary {
                imported: 0,
                duplicates: 1,
                total: 1
            }
        );
    }

    /// Bank-internal bookings (here the yearly account settlement):
    /// the CAMT export names the own account number as counterparty,
    /// MT940 names nothing - one more reason the counterparty is not
    /// part of the fingerprint.
    #[test]
    fn bank_internal_bookings_deduplicate() {
        let mt940_row = "DE44500105175407324931;01.07.26;30.06.26;\
            ABSCHLUSS;Abrechnung 30.06.2026siehe Anlage;;;60050010;0,00;EUR;Umsatz gebucht";
        let camt_row = "DE44500105175407324931;01.07.26;30.06.26;\
            ABSCHLUSS;Abrechnung 30.06.2026 siehe Anlage ;;;;;;;;0100433182;60050010;0,00;EUR;\
            Umsatz gebucht;";
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let camt = camt_file(dir.path(), "camt.csv", &[camt_row]);
        let mt940 = mt940_file(dir.path(), "mt940.csv", &[mt940_row]);

        import(parse_sparkasse, &camt, &archive_path, GapPolicy::Reject).unwrap();
        let summary = import(parse_sparkasse, &mt940, &archive_path, GapPolicy::Reject).unwrap();
        assert_eq!(
            summary,
            ImportSummary {
                imported: 0,
                duplicates: 1,
                total: 1
            }
        );
    }

    #[test]
    fn mt940_rejects_unknown_export_columns() {
        let dir = tempfile::tempdir().unwrap();
        let archive_path = dir.path().join("archive.csv");
        let path = dir.path().join("export.csv");
        fs::write(
            &path,
            format!("{MT940_HEADER};Neue Spalte\n{MT940_SALARY};x\n"),
        )
        .unwrap();

        let error = import(parse_sparkasse, &path, &archive_path, GapPolicy::Reject).unwrap_err();
        assert!(format!("{error:#}").contains("Neue Spalte"));
    }
}