mx20022-translate 0.3.0

Bidirectional SWIFT MT↔ISO 20022 MX translation: MT103↔pacs.008, MT202↔pacs.009, MT940↔camt.053
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
//! Translation from MT940 Customer Statement Message to camt.053.001.11.

use mx20022_model::common::ChoiceWrapper;
use mx20022_model::generated::camt::camt_053_001_11 as camt053;

use crate::mappings::error::{TranslationError, TranslationResult, TranslationWarnings};
use crate::mt::fields::mt940::{Balance, Mt940, StatementLine};

/// Translate an `Mt940` into a `camt.053.001.11` `Document`.
///
/// # Errors
///
/// Returns [`TranslationError`] when a mandatory field cannot be mapped.
pub fn mt940_to_camt053(
    mt940: &Mt940,
    msg_id: &str,
    creation_time: &str,
) -> Result<TranslationResult<camt053::Document>, TranslationError> {
    let mut warnings = TranslationWarnings::default();

    // ------------------------------------------------------------------
    // GroupHeader81
    // ------------------------------------------------------------------
    let grp_hdr = camt053::GroupHeader81::builder()
        .msg_id(camt053::Max35Text(msg_id.to_string()))
        .cre_dt_tm(camt053::ISODateTime(creation_time.to_string()))
        .build()?;

    // ------------------------------------------------------------------
    // Account identification (:25:)
    // ------------------------------------------------------------------
    let acct_id = build_account_id(&mt940.account_id);
    let acct = camt053::CashAccount41 {
        id: Some(acct_id),
        tp: None,
        ccy: None,
        nm: None,
        prxy: None,
        ownr: None,
        svcr: None,
    };

    // ------------------------------------------------------------------
    // Statement ID (:20:) and sequence number (:28C:)
    // ------------------------------------------------------------------
    let stmt_id = camt053::Max35Text(mt940.transaction_reference.clone());

    // Try to parse the statement number from :28C: (format: NNN/NNN)
    let elctrnc_seq_nb: Option<camt053::Number> = parse_statement_number(&mt940.statement_number);

    // ------------------------------------------------------------------
    // Balances (:60F/M: opening, :62F/M: closing, :64: closing available)
    // ------------------------------------------------------------------
    let mut bal_vec: Vec<camt053::CashBalance8> = Vec::new();

    // Opening balance type: OPBD (final) or ITBD (intermediate)
    let opening_type_code = if mt940.opening_balance.balance_type == 'F' {
        "OPBD"
    } else {
        "ITBD"
    };
    bal_vec.push(build_balance(&mt940.opening_balance, opening_type_code)?);

    // Closing balance type: CLBD (final) or ITCL (intermediate)
    let closing_type_code = if mt940.closing_balance.balance_type == 'F' {
        "CLBD"
    } else {
        "ITCL"
    };
    bal_vec.push(build_balance(&mt940.closing_balance, closing_type_code)?);

    // Closing available balance (:64:)
    if let Some(ca) = &mt940.closing_available {
        bal_vec.push(build_balance(ca, "CLAV")?);
    }

    // Forward available balances (:65:)
    for fa in &mt940.forward_available {
        bal_vec.push(build_balance(fa, "FWAV")?);
    }

    // ------------------------------------------------------------------
    // Statement entries (:61: + :86:)
    //
    // MT940 statements are single-currency: the currency lives on :60F:
    // (opening balance), not on each :61: line. camt.053's ReportEntry
    // requires a currency on the entry amount, so inherit it from the
    // opening balance.
    // ------------------------------------------------------------------
    let stmt_currency = mt940.opening_balance.currency.as_str();
    let mut ntry_vec: Vec<camt053::ReportEntry13> = Vec::new();
    for sl in &mt940.statement_lines {
        match build_entry(sl, stmt_currency) {
            Ok(entry) => ntry_vec.push(entry),
            Err(e) => {
                warnings.add(":61:", format!("skipped statement line: {e}"));
            }
        }
    }

    // ------------------------------------------------------------------
    // AccountStatement12
    // ------------------------------------------------------------------
    let stmt = camt053::AccountStatement12 {
        id: stmt_id,
        stmt_pgntn: None,
        elctrnc_seq_nb,
        rptg_seq: None,
        lgl_seq_nb: None,
        cre_dt_tm: None,
        fr_to_dt: None,
        cpy_dplct_ind: None,
        rptg_src: None,
        acct,
        rltd_acct: None,
        intrst: vec![],
        bal: bal_vec,
        txs_summry: None,
        ntry: ntry_vec,
        addtl_stmt_inf: None,
    };

    let bk_to_cstmr_stmt = camt053::BankToCustomerStatementV11 {
        grp_hdr,
        stmt: vec![stmt],
        splmtry_data: vec![],
    };

    let doc = camt053::Document { bk_to_cstmr_stmt };

    Ok(TranslationResult {
        message: doc,
        warnings,
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Build an `AccountIdentification4Choice` wrapped in a `ChoiceWrapper` from
/// the raw MT940 `:25:` account ID string.
fn build_account_id(account_id: &str) -> ChoiceWrapper<camt053::AccountIdentification4Choice> {
    let trimmed = account_id.trim();
    // Check if it looks like an IBAN (country code prefix, >= 15 chars)
    if is_iban_like(trimmed) {
        ChoiceWrapper::new(camt053::AccountIdentification4Choice::IBAN(
            camt053::IBAN2007Identifier(trimmed.to_string()),
        ))
    } else {
        ChoiceWrapper::new(camt053::AccountIdentification4Choice::Othr(
            camt053::GenericAccountIdentification1 {
                id: camt053::Max34Text(trimmed.to_string()),
                schme_nm: None,
                issr: None,
            },
        ))
    }
}

/// Heuristic IBAN check: two uppercase letters followed by digits, length 15-34.
fn is_iban_like(s: &str) -> bool {
    let chars: Vec<char> = s.chars().collect();
    chars.len() >= 15
        && chars.len() <= 34
        && chars[0].is_ascii_uppercase()
        && chars[1].is_ascii_uppercase()
        && chars[2..].iter().all(char::is_ascii_alphanumeric)
}

/// Parse the statement / sequence number from the `:28C:` value.
///
/// Format: `NNN/NNN` — returns the first number.
fn parse_statement_number(s: &str) -> Option<camt053::Number> {
    let first = s.split('/').next().unwrap_or("").trim();
    if first.chars().all(|c| c.is_ascii_digit()) && !first.is_empty() {
        Some(camt053::Number(first.to_string()))
    } else {
        None
    }
}

/// Convert an MT `Balance` struct into a `camt.053` `CashBalance8`.
///
/// `balance_type_code` must be an ISO 20022 External Balance Type code
/// (`OPBD`, `CLBD`, `ITBD`, `ITCL`, `CLAV`, `FWAV`).
fn build_balance(
    bal: &Balance,
    balance_type_code: &str,
) -> Result<camt053::CashBalance8, TranslationError> {
    let cdt_dbt_ind = match bal.dc_indicator {
        'C' => camt053::CreditDebitCode::Crdt,
        'D' => camt053::CreditDebitCode::Dbit,
        other => {
            return Err(TranslationError::InvalidFieldValue {
                field: "balance.dc_indicator".into(),
                detail: format!("expected C or D, got '{other}'"),
            });
        }
    };

    let amt = camt053::ActiveOrHistoricCurrencyAndAmount {
        value: camt053::ActiveOrHistoricCurrencyAndAmountSimpleType(bal.amount.clone()),
        ccy: camt053::ActiveOrHistoricCurrencyCode(bal.currency.clone()),
    };

    let bal_type = camt053::BalanceType13 {
        cd_or_prtry: ChoiceWrapper::new(camt053::BalanceType10Choice::Cd(
            camt053::ExternalBalanceType1Code(balance_type_code.to_string()),
        )),
        sub_tp: None,
    };

    let dt = ChoiceWrapper::new(camt053::DateAndDateTime2Choice::Dt(camt053::ISODate(
        bal.date.clone(),
    )));

    camt053::CashBalance8::builder()
        .tp(bal_type)
        .amt(amt)
        .cdt_dbt_ind(cdt_dbt_ind)
        .dt(dt)
        .build()
        .map_err(TranslationError::Builder)
}

/// Build a `ReportEntry13` from a `StatementLine`.
///
/// `stmt_currency` is the ISO 4217 currency that applies to the whole
/// MT940 statement (taken from the `:60F:` opening balance). Returns
/// [`TranslationError::MissingField`] when it is empty, since
/// camt.053's `ReportEntry/Amt/@Ccy` is mandatory.
fn build_entry(
    sl: &StatementLine,
    stmt_currency: &str,
) -> Result<camt053::ReportEntry13, TranslationError> {
    if stmt_currency.is_empty() {
        return Err(TranslationError::MissingField {
            field: "Bal[OPBD]/Amt/@Ccy".into(),
            context: "mt940_to_camt053 entry currency".into(),
        });
    }

    let is_credit = sl.dc_mark == "C" || sl.dc_mark == "RC";
    let cdt_dbt_ind = if is_credit {
        camt053::CreditDebitCode::Crdt
    } else {
        camt053::CreditDebitCode::Dbit
    };

    let amt = camt053::ActiveOrHistoricCurrencyAndAmount {
        value: camt053::ActiveOrHistoricCurrencyAndAmountSimpleType(sl.amount.clone()),
        ccy: camt053::ActiveOrHistoricCurrencyCode(stmt_currency.to_string()),
    };

    let val_dt = ChoiceWrapper::new(camt053::DateAndDateTime2Choice::Dt(camt053::ISODate(
        sl.value_date.clone(),
    )));

    let sts = ChoiceWrapper::new(camt053::EntryStatus1Choice::Cd(
        camt053::ExternalEntryStatus1Code("BOOK".to_string()),
    ));

    // Use the transaction type code as a proprietary bank transaction code.
    let bk_tx_cd = camt053::BankTransactionCodeStructure4 {
        domn: None,
        prtry: Some(camt053::ProprietaryBankTransactionCodeStructure1 {
            cd: camt053::Max35Text(sl.transaction_type.clone()),
            issr: None,
        }),
    };

    let mut builder = camt053::ReportEntry13::builder()
        .ntry_ref(camt053::Max35Text(sl.reference.clone()))
        .amt(amt)
        .cdt_dbt_ind(cdt_dbt_ind)
        .sts(sts)
        .val_dt(val_dt)
        .bk_tx_cd(bk_tx_cd);

    if let Some(info) = &sl.information {
        builder = builder.addtl_ntry_inf(camt053::Max500Text(info.clone()));
    }

    builder.build().map_err(TranslationError::Builder)
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mt::fields::mt940::parse_mt940;
    use crate::mt::parser::parse;

    const MT940_RAW: &str = "\
{1:F01BANKBEBBAXXX0000000000}\
{2:O9401200230615BANKBEBBAXXX00000000002306151200N}\
{3:{108:MT940REF}}\
{4:
:20:STMT-REF-001
:25:NL91ABNA0417164300
:28C:1/1
:60F:C230614EUR10000,00
:61:2306150615DN1000,50NTRFREF103-001//INSTREF001
:86:Payment to supplier
:62F:C230615EUR8999,50
-}{5:{CHK:GHI12345678}}";

    #[test]
    fn test_mt940_to_camt053_basic() {
        let msg = parse(MT940_RAW).unwrap();
        let mt940 = parse_mt940(&msg.block4).unwrap();
        let result = mt940_to_camt053(&mt940, "MSG001", "2023-06-15T10:00:00").unwrap();
        let doc = &result.message;

        let stmt = &doc.bk_to_cstmr_stmt.stmt[0];
        assert_eq!(stmt.id.0, "STMT-REF-001");
    }

    #[test]
    fn test_mt940_to_camt053_balances() {
        let msg = parse(MT940_RAW).unwrap();
        let mt940 = parse_mt940(&msg.block4).unwrap();
        let result = mt940_to_camt053(&mt940, "MSG001", "2023-06-15T10:00:00").unwrap();
        let stmt = &result.message.bk_to_cstmr_stmt.stmt[0];

        // Opening + closing = 2 balances
        assert!(stmt.bal.len() >= 2);
        // Opening balance: credit, 10000.00
        let ob = &stmt.bal[0];
        assert!(matches!(ob.cdt_dbt_ind, camt053::CreditDebitCode::Crdt));
        assert_eq!(ob.amt.value.0, "10000.00");
    }

    #[test]
    fn test_mt940_to_camt053_entries() {
        let msg = parse(MT940_RAW).unwrap();
        let mt940 = parse_mt940(&msg.block4).unwrap();
        let result = mt940_to_camt053(&mt940, "MSG001", "2023-06-15T10:00:00").unwrap();
        let stmt = &result.message.bk_to_cstmr_stmt.stmt[0];

        assert_eq!(stmt.ntry.len(), 1);
        let entry = &stmt.ntry[0];
        assert!(matches!(entry.cdt_dbt_ind, camt053::CreditDebitCode::Dbit));
        assert_eq!(entry.amt.value.0, "1000.50");
        assert_eq!(
            entry.addtl_ntry_inf.as_ref().map(|s| s.0.as_str()),
            Some("Payment to supplier")
        );
    }

    #[test]
    fn test_mt940_to_camt053_iban_account() {
        let msg = parse(MT940_RAW).unwrap();
        let mt940 = parse_mt940(&msg.block4).unwrap();
        let result = mt940_to_camt053(&mt940, "MSG001", "2023-06-15T10:00:00").unwrap();
        let stmt = &result.message.bk_to_cstmr_stmt.stmt[0];
        if let Some(ChoiceWrapper {
            inner: camt053::AccountIdentification4Choice::IBAN(iban),
        }) = &stmt.acct.id
        {
            assert_eq!(iban.0, "NL91ABNA0417164300");
        } else {
            panic!("expected IBAN account identification");
        }
    }

    #[test]
    fn test_mt940_to_camt053_entry_currency_inherited_from_opening_balance() {
        let msg = parse(MT940_RAW).unwrap();
        let mt940 = parse_mt940(&msg.block4).unwrap();
        let result = mt940_to_camt053(&mt940, "MSG001", "2023-06-15T10:00:00").unwrap();
        let stmt = &result.message.bk_to_cstmr_stmt.stmt[0];

        assert!(!stmt.ntry.is_empty(), "statement must have entries");
        for (i, entry) in stmt.ntry.iter().enumerate() {
            assert_eq!(
                entry.amt.ccy.0, "EUR",
                "entry {i} ccy must inherit from :60F: ({}), got {:?}",
                mt940.opening_balance.currency, entry.amt.ccy.0
            );
        }
    }

    #[test]
    fn test_mt940_to_camt053_empty_opening_currency_errors() {
        let msg = parse(MT940_RAW).unwrap();
        let mut mt940 = parse_mt940(&msg.block4).unwrap();
        // Simulate a degenerate parser output where the opening balance
        // has no currency. The translator should refuse rather than emit
        // a schema-invalid empty Ccy on each entry.
        mt940.opening_balance.currency.clear();

        let result = mt940_to_camt053(&mt940, "MSG001", "2023-06-15T10:00:00").unwrap();
        // The opening balance itself is built first (with an empty Ccy
        // on the balance amount, which is a separate issue not in scope
        // here); the entry-build path is what should refuse and warn.
        let stmt = &result.message.bk_to_cstmr_stmt.stmt[0];
        assert!(
            stmt.ntry.is_empty(),
            "all entries should have been rejected; got {} entries",
            stmt.ntry.len()
        );
        assert!(
            result
                .warnings
                .warnings
                .iter()
                .any(|w| w.field == ":61:" && w.message.contains("Bal[OPBD]/Amt/@Ccy")),
            "expected a :61: warning citing the missing opening-balance currency, got: {:?}",
            result.warnings.warnings
        );
    }
}