fints-rs 0.1.0

Native Rust FinTS 3.0 PinTan client for German online banking
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
//! Bank workflow trait and DKB implementation.
//!
//! Each bank defines its own complete workflow via the `BankOps` trait.
//! The workflows compose typed Dialog transitions from `protocol.rs`.
//!
//! Compile-time safety: workflow methods take typed dialog states.
//! `fetch()` takes `Dialog<Open>` — you can't call it without authentication.

use tracing::{info, warn};

use crate::banks::BankConfig;
use crate::error::{FinTSError, Result};
use crate::protocol::*;
use crate::types::*;

// ═══════════════════════════════════════════════════════════════════════════════
// Workflow result types
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of initiating a connection.
pub struct InitiateResult {
    pub dialog: Dialog<TanPending>,
    pub challenge: TanChallenge,
    pub tan_methods: Vec<TanMethod>,
    pub allowed_security_functions: Vec<SecurityFunction>,
    pub no_tan_required: bool,
    pub params: BankParams,
    pub system_id: SystemId,
}

/// Result when no TAN is required (SCA exemption).
pub struct InitiateNoTanResult {
    pub dialog: Dialog<Open>,
    pub params: BankParams,
    pub system_id: SystemId,
    pub tan_methods: Vec<TanMethod>,
    pub allowed_security_functions: Vec<SecurityFunction>,
}

/// Either we need TAN or we're already authenticated.
pub enum InitiateOutcome {
    NeedTan(InitiateResult),
    Authenticated(InitiateNoTanResult),
}

/// Result of fetching data from an open dialog.
pub struct FetchResult {
    pub balance: Option<AccountBalance>,
    pub transactions: Vec<Transaction>,
    pub holdings: Vec<SecurityHolding>,
}

/// Options controlling what data to fetch in a single authenticated dialog.
#[derive(Debug, Clone, Default)]
pub struct FetchOpts {
    /// Fetch balance (HKSAL). Default: true.
    pub balance: bool,
    /// Fetch transactions (HKKAZ). Default: true.
    pub transactions: bool,
    /// Fetch securities holdings (HKWPD). Default: true.
    pub holdings: bool,
    /// Days of transaction history to fetch. Default: 90.
    pub days: u32,
}

impl FetchOpts {
    /// Fetch everything: balance, transactions, and holdings.
    pub fn all(days: u32) -> Self {
        Self { balance: true, transactions: true, holdings: true, days }
    }
    /// Fetch only balance (single request, fast).
    pub fn balance_only() -> Self {
        Self { balance: true, transactions: false, holdings: false, days: 0 }
    }
    /// Skip holdings (for accounts without a depot).
    pub fn no_holdings(days: u32) -> Self {
        Self { balance: true, transactions: true, holdings: false, days }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// BankOps trait
// ═══════════════════════════════════════════════════════════════════════════════

/// Each bank implements its own workflow as typed Dialog transitions.
///
/// `fetch()` takes `&mut Dialog<Open>` and `&Account` — compile-time proof that:
/// 1. Authentication has been completed (Dialog<Open>)
/// 2. Account has valid IBAN + BIC (Account)
pub trait BankOps: Send + Sync {
    fn config(&self) -> &BankConfig;

    /// Phase 1: sync + init, return TAN challenge or authenticated dialog.
    fn initiate(
        &self,
        username: &UserId,
        pin: &Pin,
        product_id: &ProductId,
        system_id: Option<&SystemId>,
        target_iban: Option<&Iban>,
        target_bic: Option<&Bic>,
    ) -> impl std::future::Future<Output = Result<InitiateOutcome>> + Send;

    /// Phase 2: fetch balance + transactions from an open dialog.
    /// Takes `&Account` — IBAN and BIC are guaranteed present.
    fn fetch(
        &self,
        dialog: &mut Dialog<Open>,
        account: &Account,
        days: u32,
    ) -> impl std::future::Future<Output = Result<FetchResult>> + Send;

    /// Fetch securities holdings from an open dialog.
    /// Takes `&Account` — IBAN and BIC are guaranteed present.
    /// Returns an empty Vec if the bank does not support depot queries.
    fn fetch_holdings(
        &self,
        dialog: &mut Dialog<Open>,
        account: &Account,
    ) -> impl std::future::Future<Output = Result<Vec<SecurityHolding>>> + Send;
}

// ═══════════════════════════════════════════════════════════════════════════════
// DKB implementation
// ═══════════════════════════════════════════════════════════════════════════════

/// DKB (Deutsche Kreditbank) FinTS workflow.
///
/// DKB message flow per spec + empirical discovery:
/// ```text
///   Sync dialog:
///     Msg 1: HKIDN + HKVVB + HKSYN   → BPD, system_id
///     Msg 2: HKEND
///
///   Business dialog:
///     Msg 1: HKIDN + HKVVB + HKTAN:4(ref=HKIDN)  → InitResult
///       → TanRequired: push sent (3955)
///       → Opened: SCA exemption (3076)
///     Msg 2: HKTAN:S(task_ref)                     → PollResult
///       → Confirmed: 0020
///       → Pending: 3955/3956
///     Msg 3: HKSAL [+ HKTAN:4(ref=HKSAL)]         → SendResult
///       → Success: balance data (HISAL)
///       → NeedTan: additional TAN for balance
///     Msg 4: HKKAZ [+ HKTAN:4(ref=HKKAZ)]         → SendResult
///       → Success: transaction data (HIKAZ)
///       → Touchdown: more data, fetch again
///     Msg 5: HKEND
/// ```
pub struct Dkb {
    bank: BankConfig,
}

impl Dkb {
    pub fn new() -> Self {
        Self {
            bank: crate::banks::bank_by_blz("12030000")
                .expect("DKB (BLZ 12030000) must be in bank registry"),
        }
    }

    fn new_dialog(&self, username: &UserId, pin: &Pin, product_id: &ProductId) -> Result<Dialog<New>> {
        Dialog::new(
            self.bank.url.as_str(),
            &self.bank.blz,
            username,
            pin,
            product_id,
        )
    }
}

impl BankOps for Dkb {
    fn config(&self) -> &BankConfig { &self.bank }

    async fn initiate(
        &self,
        username: &UserId,
        pin: &Pin,
        product_id: &ProductId,
        system_id: Option<&SystemId>,
        _target_iban: Option<&Iban>,
        _target_bic: Option<&Bic>,
    ) -> Result<InitiateOutcome> {
        // ── Phase 1: Sync dialog (get system_id + BPD) ──
        let mut sync_dialog = self.new_dialog(username, pin, product_id)?;
        if let Some(sid) = system_id {
            sync_dialog = sync_dialog.with_system_id(sid);
        }
        let (synced, _resp) = sync_dialog.sync().await?;
        let (sync_params, sys_id) = synced.end().await?;

        let sys_id = if sys_id.is_assigned() {
            sys_id
        } else {
            system_id.cloned().unwrap_or_else(SystemId::unassigned)
        };

        // ── Phase 2: Normal dialog init (triggers TAN or opens directly) ──
        let dialog = self.new_dialog(username, pin, product_id)?
            .with_system_id(&sys_id)
            .with_params(&sync_params);

        let init_result = dialog.init().await?;

        match init_result {
            InitResult::TanRequired(tan_pending, challenge, _resp) => {
                info!("[DKB] TAN required: decoupled={}, task_ref='{}'",
                    challenge.decoupled, challenge.task_reference);
                Ok(InitiateOutcome::NeedTan(InitiateResult {
                    params: tan_pending.bank_params().clone(),
                    system_id: tan_pending.system_id().clone(),
                    dialog: tan_pending,
                    challenge,
                    tan_methods: sync_params.tan_methods.clone(),
                    allowed_security_functions: sync_params.allowed_security_functions.clone(),
                    no_tan_required: false,
                }))
            }
            InitResult::Opened(open, _resp) => {
                info!("[DKB] Opened directly (SCA exemption)");
                Ok(InitiateOutcome::Authenticated(InitiateNoTanResult {
                    params: open.bank_params().clone(),
                    system_id: open.system_id().clone(),
                    dialog: open,
                    tan_methods: sync_params.tan_methods.clone(),
                    allowed_security_functions: sync_params.allowed_security_functions.clone(),
                }))
            }
        }
    }

    async fn fetch(
        &self,
        dialog: &mut Dialog<Open>,
        account: &Account,
        days: u32,
    ) -> Result<FetchResult> {
        info!("[DKB] Fetching IBAN={}, BIC={}", account.iban(), account.bic());

        // ── Balance (HKSAL) ──
        let balance = match dialog.balance(account).await {
            Ok(BalanceResult::Success(b)) => {
                info!("[DKB] Balance: {}", b.amount);
                Some(b)
            }
            Ok(BalanceResult::NeedTan(_)) => {
                warn!("[DKB] Balance requires additional TAN — skipping");
                None
            }
            Ok(BalanceResult::Empty) => {
                warn!("[DKB] No balance data in response");
                None
            }
            Err(e) => {
                warn!("[DKB] Balance failed: {}", e);
                None
            }
        };

        // ── Transactions (HKKAZ) with pagination ──
        let end_date = chrono::Utc::now().date_naive();
        let start_date = end_date - chrono::Duration::days(days as i64);
        info!("[DKB] Transactions {} to {}", start_date, end_date);

        let mut all_booked = Mt940Data::new();
        let mut all_pending = Mt940Data::new();
        let mut touchdown: Option<TouchdownPoint> = None;

        loop {
            let result = dialog.transactions(
                account, start_date, end_date, touchdown.as_ref(),
            ).await?;

            match result {
                TransactionResult::NeedTan(_) => {
                    return Err(FinTSError::Dialog(
                        "DKB erfordert für Transaktionen eine weitere TAN-Freigabe.".into()
                    ));
                }
                TransactionResult::Success(page) => {
                    if !page.booked.is_empty() { all_booked.extend(page.booked.0); }
                    if !page.pending.is_empty() { all_pending.extend(page.pending.0); }
                    touchdown = page.touchdown;
                    if touchdown.is_none() { break; }
                    info!("[DKB] Touchdown: more data...");
                }
            }
        }

        let mut transactions = parse_mt940(all_booked.as_bytes(), TransactionStatus::Booked)?;
        if !all_pending.is_empty() {
            transactions.extend(parse_mt940(all_pending.as_bytes(), TransactionStatus::Pending)?);
        }
        info!("[DKB] {} transactions", transactions.len());

        // ── Holdings (HKWPD) — best-effort, non-fatal ──
        let holdings = match self.fetch_holdings(dialog, account).await {
            Ok(h) => {
                info!("[DKB] {} holdings", h.len());
                h
            }
            Err(e) => {
                warn!("[DKB] Holdings fetch failed (non-fatal): {}", e);
                Vec::new()
            }
        };

        Ok(FetchResult { balance, transactions, holdings })
    }

    async fn fetch_holdings(
        &self,
        dialog: &mut Dialog<Open>,
        account: &Account,
    ) -> Result<Vec<SecurityHolding>> {
        info!("[DKB] Fetching holdings IBAN={}, BIC={}", account.iban(), account.bic());

        let mut all_holdings = Vec::new();
        let mut touchdown: Option<TouchdownPoint> = None;

        loop {
            let result = dialog.holdings(
                account, None, touchdown.as_ref(),
            ).await?;

            match result {
                HoldingsResult::NeedTan(_) => {
                    warn!("[DKB] Holdings requires additional TAN — skipping");
                    return Ok(all_holdings);
                }
                HoldingsResult::Empty => {
                    info!("[DKB] No holdings data (depot may be empty or not supported)");
                    break;
                }
                HoldingsResult::Success(page) => {
                    info!("[DKB] Got {} holdings", page.holdings.len());
                    all_holdings.extend(page.holdings);
                    touchdown = page.touchdown;
                    if touchdown.is_none() { break; }
                    info!("[DKB] Holdings touchdown: more data...");
                }
            }
        }

        info!("[DKB] Total: {} holdings", all_holdings.len());
        Ok(all_holdings)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Bank registry
// ═══════════════════════════════════════════════════════════════════════════════

// ═══════════════════════════════════════════════════════════════════════════════
// Generic bank — any FinTS endpoint (used for custom/unknown banks)
// ═══════════════════════════════════════════════════════════════════════════════

/// A generic FinTS bank implementation that works with any BankConfig.
/// Used when the bank ID is not in the registry (e.g. custom URL + BLZ).
pub struct GenericBank {
    bank: BankConfig,
}

impl GenericBank {
    pub fn new(config: BankConfig) -> Self {
        Self { bank: config }
    }

    fn new_dialog(&self, username: &UserId, pin: &Pin, product_id: &ProductId) -> Result<Dialog<New>> {
        Dialog::new(self.bank.url.as_str(), &self.bank.blz, username, pin, product_id)
    }
}

impl BankOps for GenericBank {
    fn config(&self) -> &BankConfig { &self.bank }

    async fn initiate(
        &self,
        username: &UserId,
        pin: &Pin,
        product_id: &ProductId,
        system_id: Option<&SystemId>,
        _target_iban: Option<&Iban>,
        _target_bic: Option<&Bic>,
    ) -> Result<InitiateOutcome> {
        let mut sync_dialog = self.new_dialog(username, pin, product_id)?;
        if let Some(sid) = system_id {
            sync_dialog = sync_dialog.with_system_id(sid);
        }
        let (synced, _) = sync_dialog.sync().await?;
        let (sync_params, sys_id) = synced.end().await?;

        let sys_id = if sys_id.is_assigned() { sys_id }
            else { system_id.cloned().unwrap_or_else(SystemId::unassigned) };

        let dialog = self.new_dialog(username, pin, product_id)?
            .with_system_id(&sys_id)
            .with_params(&sync_params);

        let init_result = dialog.init().await?;

        match init_result {
            InitResult::TanRequired(tan_pending, challenge, _) => {
                let challenge = crate::protocol::TanChallenge {
                    decoupled: challenge.decoupled || tan_pending.bank_params().is_decoupled(),
                    ..challenge
                };
                Ok(InitiateOutcome::NeedTan(InitiateResult {
                    params: tan_pending.bank_params().clone(),
                    system_id: tan_pending.system_id().clone(),
                    dialog: tan_pending, challenge,
                    tan_methods: sync_params.tan_methods.clone(),
                    allowed_security_functions: sync_params.allowed_security_functions.clone(),
                    no_tan_required: false,
                }))
            }
            InitResult::Opened(open, _) => {
                Ok(InitiateOutcome::Authenticated(InitiateNoTanResult {
                    params: open.bank_params().clone(),
                    system_id: open.system_id().clone(),
                    dialog: open,
                    tan_methods: sync_params.tan_methods.clone(),
                    allowed_security_functions: sync_params.allowed_security_functions.clone(),
                }))
            }
        }
    }

    async fn fetch(&self, dialog: &mut Dialog<Open>, account: &Account, days: u32) -> Result<FetchResult> {
        // Reuse DKB fetch logic (it's generic enough — just uses typed Dialog<Open> methods)
        Dkb::new().fetch(dialog, account, days).await
    }

    async fn fetch_holdings(&self, dialog: &mut Dialog<Open>, account: &Account) -> Result<Vec<SecurityHolding>> {
        Dkb::new().fetch_holdings(dialog, account).await
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Bank registry
// ═══════════════════════════════════════════════════════════════════════════════

/// Enum dispatch for bank implementations — zero-cost, no dynamic dispatch.
///
/// New banks are added here as enum variants. This avoids `Box<dyn BankOps>`
/// which is incompatible with native async fn in traits.
pub enum AnyBank {
    Dkb(Dkb),
    Generic(GenericBank),
}

impl AnyBank {
    pub fn config(&self) -> &BankConfig {
        match self {
            AnyBank::Dkb(b) => b.config(),
            AnyBank::Generic(b) => b.config(),
        }
    }

    pub async fn initiate(
        &self,
        username: &UserId,
        pin: &Pin,
        product_id: &ProductId,
        system_id: Option<&SystemId>,
        target_iban: Option<&Iban>,
        target_bic: Option<&Bic>,
    ) -> Result<InitiateOutcome> {
        match self {
            AnyBank::Dkb(b) => b.initiate(username, pin, product_id, system_id, target_iban, target_bic).await,
            AnyBank::Generic(b) => b.initiate(username, pin, product_id, system_id, target_iban, target_bic).await,
        }
    }

    pub async fn fetch(
        &self,
        dialog: &mut Dialog<Open>,
        account: &Account,
        days: u32,
    ) -> Result<FetchResult> {
        match self {
            AnyBank::Dkb(b) => b.fetch(dialog, account, days).await,
            AnyBank::Generic(b) => b.fetch(dialog, account, days).await,
        }
    }

    pub async fn fetch_holdings(
        &self,
        dialog: &mut Dialog<Open>,
        account: &Account,
    ) -> Result<Vec<SecurityHolding>> {
        match self {
            AnyBank::Dkb(b) => b.fetch_holdings(dialog, account).await,
            AnyBank::Generic(b) => b.fetch_holdings(dialog, account).await,
        }
    }

    /// Fetch data with fine-grained control via `FetchOpts`.
    /// This gives callers a single authenticated dialog for all operations.
    pub async fn fetch_with_opts(
        &self,
        dialog: &mut Dialog<Open>,
        account: &Account,
        opts: &FetchOpts,
    ) -> Result<FetchResult> {
        use tracing::warn;
        use crate::protocol::{BalanceResult, TransactionResult, HoldingsResult};
        use crate::types::{Mt940Data, TransactionStatus, TouchdownPoint};

        // ── Balance ──
        let balance = if opts.balance {
            match dialog.balance(account).await {
                Ok(BalanceResult::Success(b)) => Some(b),
                Ok(BalanceResult::NeedTan(_)) => { warn!("Balance requires TAN — skipping"); None }
                Ok(BalanceResult::Empty) => None,
                Err(e) => { warn!("Balance failed: {}", e); None }
            }
        } else {
            None
        };

        // ── Transactions ──
        let transactions = if opts.transactions {
            let end_date = chrono::Utc::now().date_naive();
            let start_date = end_date - chrono::Duration::days(opts.days.max(1) as i64);
            let mut all_booked = Mt940Data::new();
            let mut all_pending = Mt940Data::new();
            let mut td: Option<TouchdownPoint> = None;
            loop {
                match dialog.transactions(account, start_date, end_date, td.as_ref()).await? {
                    TransactionResult::NeedTan(_) => break,
                    TransactionResult::Success(page) => {
                        if !page.booked.is_empty() { all_booked.extend(page.booked.0); }
                        if !page.pending.is_empty() { all_pending.extend(page.pending.0); }
                        td = page.touchdown;
                        if td.is_none() { break; }
                    }
                }
            }
            let mut txns = parse_mt940(all_booked.as_bytes(), TransactionStatus::Booked)
                .unwrap_or_default();
            if !all_pending.is_empty() {
                txns.extend(parse_mt940(all_pending.as_bytes(), TransactionStatus::Pending)
                    .unwrap_or_default());
            }
            txns
        } else {
            Vec::new()
        };

        // ── Holdings ──
        let holdings = if opts.holdings {
            match self.fetch_holdings(dialog, account).await {
                Ok(h) => h,
                Err(e) => { warn!("Holdings fetch failed: {}", e); Vec::new() }
            }
        } else {
            Vec::new()
        };

        Ok(FetchResult { balance, transactions, holdings })
    }
}

/// Look up a bank implementation by its BLZ (Bankleitzahl).
///
/// The BLZ is the canonical bank identifier — banks are dispatched based on it.
/// BLZ `12030000` → DKB implementation; all others → GenericBank.
pub fn bank_ops(blz: &str) -> Result<AnyBank> {
    let config = crate::banks::bank_by_blz(blz)
        .ok_or_else(|| FinTSError::Dialog(format!("Unknown BLZ: {}", blz)))?;
    match blz {
        "12030000" => Ok(AnyBank::Dkb(Dkb::new())),
        _ => Ok(AnyBank::Generic(GenericBank::new(config))),
    }
}

/// Create a bank implementation from a custom BankConfig (for non-registry banks).
pub fn bank_ops_with_config(config: BankConfig) -> AnyBank {
    AnyBank::Generic(GenericBank::new(config))
}

// ═══════════════════════════════════════════════════════════════════════════════
// MT940 parsing
// ═══════════════════════════════════════════════════════════════════════════════

fn parse_mt940(data: &[u8], status: TransactionStatus) -> Result<Vec<Transaction>> {
    if data.is_empty() { return Ok(Vec::new()); }

    let (cow, _, had_errors) = encoding_rs::WINDOWS_1252.decode(data);
    if had_errors { warn!("MT940 encoding errors"); }
    let mt940_text = cow.into_owned();

    let cleaned: String = mt940_text.lines()
        .filter(|l| { let t = l.trim(); !t.is_empty() && t != "-" && t != "--" })
        .collect::<Vec<_>>().join("\r\n") + "\r\n";

    let sanitized = mt940::sanitizers::to_swift_charset(&cleaned);
    let messages = mt940::parse_mt940(&sanitized)
        .map_err(|e| FinTSError::Mt940(format!("MT940 parse error: {}", e)))?;

    let mut transactions = Vec::new();
    for msg in messages {
        for line in msg.statement_lines {
            let is_debit = matches!(line.ext_debit_credit_indicator, mt940::ExtDebitOrCredit::Debit);
            let amount = if is_debit { -line.amount } else { line.amount };

            let (applicant_name, applicant_iban, applicant_bic, purpose, posting_text) =
                match &line.information_to_account_owner {
                    Some(mt940::InformationToAccountOwner::Structured {
                        applicant_name, applicant_iban, applicant_bin, purpose, posting_text, ..
                    }) => (applicant_name.clone(), applicant_iban.clone(), applicant_bin.clone(), purpose.clone(), posting_text.clone()),
                    Some(mt940::InformationToAccountOwner::Plain(text)) => (None, None, None, Some(text.clone()), None),
                    None => (None, None, None, None, None),
                };

            let raw = serde_json::json!({
                "date": line.value_date.to_string(),
                "entry_date": line.entry_date.map(|d| d.to_string()),
                "amount": amount.to_string(),
                "currency": msg.opening_balance.iso_currency_code,
                "customer_ref": line.customer_ref,
                "bank_ref": line.bank_ref,
                "applicant_name": applicant_name,
                "applicant_iban": applicant_iban,
                "applicant_bic": applicant_bic,
                "purpose": purpose,
                "posting_text": posting_text,
            });

            transactions.push(Transaction {
                date: line.value_date, valuta_date: line.entry_date,
                amount,
                currency: Currency::new(&msg.opening_balance.iso_currency_code),
                applicant_name,
                applicant_iban: applicant_iban.map(|s| Iban::new(s)),
                applicant_bic: applicant_bic.map(|s| Bic::new(s)),
                purpose, posting_text,
                reference: Some(line.customer_ref.clone()),
                raw, status: status.clone(),
            });
        }
    }
    Ok(transactions)
}