datasynth-banking 2.2.0

KYC/AML banking transaction generator for synthetic data - compliance testing and fraud analytics
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
//! Banking transaction model for KYC/AML simulation.

#![allow(clippy::too_many_arguments)]

use chrono::{DateTime, Utc};
use datasynth_core::models::banking::{
    AmlTypology, Direction, LaunderingStage, MerchantCategoryCode, TransactionCategory,
    TransactionChannel,
};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Derive a transaction type string from channel and category.
///
/// Converts `TransactionChannel` and `TransactionCategory` Debug names from
/// CamelCase to SCREAMING_SNAKE_CASE and joins them with an underscore.
/// For example, `CardPresent` + `Shopping` becomes `"CARD_PRESENT_SHOPPING"`.
fn derive_transaction_type(channel: TransactionChannel, category: TransactionCategory) -> String {
    fn to_screaming_snake(name: &str) -> String {
        let mut result = String::with_capacity(name.len() + 4);
        for (i, ch) in name.chars().enumerate() {
            if ch.is_uppercase() && i > 0 {
                result.push('_');
            }
            result.push(ch.to_ascii_uppercase());
        }
        result
    }
    let channel_str = to_screaming_snake(&format!("{channel:?}"));
    let category_str = to_screaming_snake(&format!("{category:?}"));
    format!("{channel_str}_{category_str}")
}

/// A bank transaction with full metadata and ground truth labels.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BankTransaction {
    /// Unique transaction identifier
    pub transaction_id: Uuid,
    /// Account ID
    pub account_id: Uuid,
    /// Timestamp when transaction was initiated
    pub timestamp_initiated: DateTime<Utc>,
    /// Timestamp when transaction was booked
    pub timestamp_booked: DateTime<Utc>,
    /// Timestamp when transaction was settled
    pub timestamp_settled: Option<DateTime<Utc>>,
    /// Transaction amount (always positive)
    #[serde(with = "rust_decimal::serde::str")]
    pub amount: Decimal,
    /// Transaction currency (ISO 4217)
    pub currency: String,
    /// Transaction direction (inbound/outbound)
    pub direction: Direction,
    /// Transaction channel
    pub channel: TransactionChannel,
    /// Transaction category
    pub category: TransactionCategory,
    /// Counterparty reference
    pub counterparty: CounterpartyRef,
    /// Merchant category code (for card transactions)
    pub mcc: Option<MerchantCategoryCode>,
    /// Transaction reference/description
    pub reference: String,
    /// Balance before transaction
    #[serde(with = "rust_decimal::serde::str_option")]
    pub balance_before: Option<Decimal>,
    /// Balance after transaction
    #[serde(with = "rust_decimal::serde::str_option")]
    pub balance_after: Option<Decimal>,
    /// Original currency (if FX conversion)
    pub original_currency: Option<String>,
    /// Original amount (if FX conversion)
    #[serde(with = "rust_decimal::serde::str_option")]
    pub original_amount: Option<Decimal>,
    /// FX rate applied
    #[serde(with = "rust_decimal::serde::str_option")]
    pub fx_rate: Option<Decimal>,
    /// Location (country code)
    pub location_country: Option<String>,
    /// Location (city)
    pub location_city: Option<String>,
    /// Device fingerprint (for online/mobile)
    pub device_id: Option<String>,
    /// IP address (masked for output)
    pub ip_address: Option<String>,
    /// Whether transaction was authorized
    pub is_authorized: bool,
    /// Authorization code
    pub auth_code: Option<String>,
    /// Transaction status
    pub status: TransactionStatus,
    /// Parent transaction ID (for reversals, fees)
    pub parent_transaction_id: Option<Uuid>,

    // Ground truth labels for ML
    /// Whether transaction is suspicious (ground truth)
    pub is_suspicious: bool,
    /// Suspicion reason (AML typology)
    pub suspicion_reason: Option<AmlTypology>,
    /// Money laundering stage
    pub laundering_stage: Option<LaunderingStage>,
    /// Case ID linking suspicious transactions
    pub case_id: Option<String>,
    /// Whether transaction is spoofed (adversarial mode)
    pub is_spoofed: bool,
    /// Spoofing intensity (0.0-1.0)
    pub spoofing_intensity: Option<f64>,
    /// Scenario ID for linked transactions
    pub scenario_id: Option<String>,
    /// Transaction sequence number within scenario
    pub scenario_sequence: Option<u32>,
    /// Derived transaction type (e.g., "CARD_PRESENT_SHOPPING")
    pub transaction_type: String,
}

impl BankTransaction {
    /// Create a new transaction.
    pub fn new(
        transaction_id: Uuid,
        account_id: Uuid,
        amount: Decimal,
        currency: &str,
        direction: Direction,
        channel: TransactionChannel,
        category: TransactionCategory,
        counterparty: CounterpartyRef,
        reference: &str,
        timestamp: DateTime<Utc>,
    ) -> Self {
        let transaction_type = derive_transaction_type(channel, category);
        Self {
            transaction_id,
            account_id,
            timestamp_initiated: timestamp,
            timestamp_booked: timestamp,
            timestamp_settled: None,
            amount,
            currency: currency.to_string(),
            direction,
            channel,
            category,
            counterparty,
            mcc: None,
            reference: reference.to_string(),
            balance_before: None,
            balance_after: None,
            original_currency: None,
            original_amount: None,
            fx_rate: None,
            location_country: None,
            location_city: None,
            device_id: None,
            ip_address: None,
            is_authorized: true,
            auth_code: None,
            status: TransactionStatus::Completed,
            parent_transaction_id: None,
            is_suspicious: false,
            suspicion_reason: None,
            laundering_stage: None,
            case_id: None,
            is_spoofed: false,
            spoofing_intensity: None,
            scenario_id: None,
            scenario_sequence: None,
            transaction_type,
        }
    }

    /// Mark as suspicious.
    pub fn mark_suspicious(mut self, reason: AmlTypology, case_id: &str) -> Self {
        self.is_suspicious = true;
        self.suspicion_reason = Some(reason);
        self.case_id = Some(case_id.to_string());
        self
    }

    /// Set laundering stage.
    pub fn with_laundering_stage(mut self, stage: LaunderingStage) -> Self {
        self.laundering_stage = Some(stage);
        self
    }

    /// Mark as spoofed.
    pub fn mark_spoofed(mut self, intensity: f64) -> Self {
        self.is_spoofed = true;
        self.spoofing_intensity = Some(intensity);
        self
    }

    /// Set scenario information.
    pub fn with_scenario(mut self, scenario_id: &str, sequence: u32) -> Self {
        self.scenario_id = Some(scenario_id.to_string());
        self.scenario_sequence = Some(sequence);
        self
    }

    /// Set MCC.
    pub fn with_mcc(mut self, mcc: MerchantCategoryCode) -> Self {
        self.mcc = Some(mcc);
        self
    }

    /// Set location.
    pub fn with_location(mut self, country: &str, city: Option<&str>) -> Self {
        self.location_country = Some(country.to_string());
        self.location_city = city.map(std::string::ToString::to_string);
        self
    }

    /// Set FX conversion.
    pub fn with_fx_conversion(
        mut self,
        original_currency: &str,
        original_amount: Decimal,
        rate: Decimal,
    ) -> Self {
        self.original_currency = Some(original_currency.to_string());
        self.original_amount = Some(original_amount);
        self.fx_rate = Some(rate);
        self
    }

    /// Set balance information.
    pub fn with_balance(mut self, before: Decimal, after: Decimal) -> Self {
        self.balance_before = Some(before);
        self.balance_after = Some(after);
        self
    }

    /// Calculate risk score for the transaction.
    pub fn calculate_risk_score(&self) -> u8 {
        let mut score = 0.0;

        // Channel risk
        score += self.channel.risk_weight() * 10.0;

        // Category risk
        score += self.category.risk_weight() * 10.0;

        // Amount risk (log scale)
        let amount_f64: f64 = self.amount.try_into().unwrap_or(0.0);
        if amount_f64 > 10_000.0 {
            score += ((amount_f64 / 10_000.0).ln() * 5.0).min(20.0);
        }

        // MCC risk
        if let Some(mcc) = self.mcc {
            score += mcc.risk_weight() * 5.0;
        }

        // Cross-border risk
        if self.original_currency.is_some() {
            score += 10.0;
        }

        // Ground truth (if available, would dominate)
        if self.is_suspicious {
            score += 50.0;
        }

        score.min(100.0) as u8
    }

    /// Check if this is a cash transaction.
    pub fn is_cash(&self) -> bool {
        matches!(
            self.channel,
            TransactionChannel::Cash | TransactionChannel::Atm
        )
    }

    /// Check if this is a cross-border transaction.
    pub fn is_cross_border(&self) -> bool {
        self.original_currency.is_some() || matches!(self.channel, TransactionChannel::Swift)
    }
}

/// Reference to a counterparty.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CounterpartyRef {
    /// Counterparty type
    pub counterparty_type: CounterpartyType,
    /// Counterparty ID (if known)
    pub counterparty_id: Option<Uuid>,
    /// Counterparty name
    pub name: String,
    /// Account identifier (masked)
    pub account_identifier: Option<String>,
    /// Bank identifier (BIC/SWIFT)
    pub bank_identifier: Option<String>,
    /// Country (ISO 3166-1 alpha-2)
    pub country: Option<String>,
}

impl CounterpartyRef {
    /// Create a merchant counterparty.
    pub fn merchant(id: Uuid, name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Merchant,
            counterparty_id: Some(id),
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create an employer counterparty.
    pub fn employer(id: Uuid, name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Employer,
            counterparty_id: Some(id),
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create a peer-to-peer counterparty.
    pub fn peer(name: &str, account: Option<&str>) -> Self {
        Self {
            counterparty_type: CounterpartyType::Peer,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: account.map(std::string::ToString::to_string),
            bank_identifier: None,
            country: None,
        }
    }

    /// Create an ATM counterparty.
    pub fn atm(location: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Atm,
            counterparty_id: None,
            name: format!("ATM - {location}"),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create a self-transfer counterparty.
    pub fn self_account(account_id: Uuid, account_name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::SelfAccount,
            counterparty_id: Some(account_id),
            name: account_name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create an unknown counterparty.
    pub fn unknown(name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Unknown,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create a person/individual counterparty.
    pub fn person(name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Peer,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create a business counterparty.
    pub fn business(name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Unknown,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create an international counterparty.
    pub fn international(name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::FinancialInstitution,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: Some("XX".to_string()), // Unknown foreign country
        }
    }

    /// Create a crypto exchange counterparty.
    pub fn crypto_exchange(name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::CryptoExchange,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create a service provider counterparty.
    pub fn service(name: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Unknown,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }

    /// Create a merchant counterparty by name only.
    pub fn merchant_by_name(name: &str, _mcc: &str) -> Self {
        Self {
            counterparty_type: CounterpartyType::Merchant,
            counterparty_id: None,
            name: name.to_string(),
            account_identifier: None,
            bank_identifier: None,
            country: None,
        }
    }
}

/// Type of counterparty.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CounterpartyType {
    /// Merchant / retailer
    Merchant,
    /// Employer (salary source)
    Employer,
    /// Utility company
    Utility,
    /// Government agency
    Government,
    /// Financial institution
    FinancialInstitution,
    /// Peer (another individual)
    Peer,
    /// ATM
    Atm,
    /// Own account (transfer)
    SelfAccount,
    /// Investment platform
    Investment,
    /// Cryptocurrency exchange
    CryptoExchange,
    /// Unknown
    Unknown,
}

impl CounterpartyType {
    /// Risk weight for AML scoring.
    pub fn risk_weight(&self) -> f64 {
        match self {
            Self::Merchant => 1.0,
            Self::Employer => 0.5,
            Self::Utility | Self::Government => 0.3,
            Self::FinancialInstitution => 1.2,
            Self::Peer => 1.5,
            Self::Atm => 1.3,
            Self::SelfAccount => 0.8,
            Self::Investment => 1.2,
            Self::CryptoExchange => 2.0,
            Self::Unknown => 1.8,
        }
    }
}

/// Transaction status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TransactionStatus {
    /// Pending authorization
    Pending,
    /// Authorized but not settled
    Authorized,
    /// Completed/settled
    #[default]
    Completed,
    /// Failed
    Failed,
    /// Declined
    Declined,
    /// Reversed
    Reversed,
    /// Disputed
    Disputed,
    /// On hold for review
    OnHold,
}

impl TransactionStatus {
    /// Whether the transaction is finalized.
    pub fn is_final(&self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Failed | Self::Declined | Self::Reversed
        )
    }
}

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

    #[test]
    fn test_transaction_creation() {
        let txn = BankTransaction::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            Decimal::from(100),
            "USD",
            Direction::Outbound,
            TransactionChannel::CardPresent,
            TransactionCategory::Shopping,
            CounterpartyRef::merchant(Uuid::new_v4(), "Test Store"),
            "Purchase at Test Store",
            Utc::now(),
        );

        assert!(!txn.is_suspicious);
        assert!(!txn.is_cross_border());
        assert!(!txn.transaction_type.is_empty());
    }

    #[test]
    fn test_suspicious_transaction() {
        let txn = BankTransaction::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            Decimal::from(9500),
            "USD",
            Direction::Inbound,
            TransactionChannel::Cash,
            TransactionCategory::CashDeposit,
            CounterpartyRef::atm("Main Branch"),
            "Cash deposit",
            Utc::now(),
        )
        .mark_suspicious(AmlTypology::Structuring, "CASE-001");

        assert!(txn.is_suspicious);
        assert_eq!(txn.suspicion_reason, Some(AmlTypology::Structuring));
    }

    #[test]
    fn test_risk_score() {
        let low_risk = BankTransaction::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            Decimal::from(50),
            "USD",
            Direction::Outbound,
            TransactionChannel::CardPresent,
            TransactionCategory::Groceries,
            CounterpartyRef::merchant(Uuid::new_v4(), "Grocery Store"),
            "Groceries",
            Utc::now(),
        );

        let high_risk = BankTransaction::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            Decimal::from(50000),
            "USD",
            Direction::Outbound,
            TransactionChannel::Wire,
            TransactionCategory::InternationalTransfer,
            CounterpartyRef::unknown("Unknown Recipient"),
            "Wire transfer",
            Utc::now(),
        );

        assert!(high_risk.calculate_risk_score() > low_risk.calculate_risk_score());
    }

    #[test]
    fn test_transaction_type_derivation() {
        let txn = BankTransaction::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            Decimal::from(100),
            "USD",
            Direction::Outbound,
            TransactionChannel::CardPresent,
            TransactionCategory::Shopping,
            CounterpartyRef::merchant(Uuid::new_v4(), "Test Store"),
            "Purchase",
            Utc::now(),
        );
        assert_eq!(txn.transaction_type, "CARD_PRESENT_SHOPPING");

        let txn2 = BankTransaction::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            Decimal::from(500),
            "USD",
            Direction::Outbound,
            TransactionChannel::Wire,
            TransactionCategory::InternationalTransfer,
            CounterpartyRef::unknown("Recipient"),
            "Wire transfer",
            Utc::now(),
        );
        assert_eq!(txn2.transaction_type, "WIRE_INTERNATIONAL_TRANSFER");

        let txn3 = BankTransaction::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            Decimal::from(200),
            "USD",
            Direction::Outbound,
            TransactionChannel::Atm,
            TransactionCategory::AtmWithdrawal,
            CounterpartyRef::atm("Branch"),
            "ATM",
            Utc::now(),
        );
        assert_eq!(txn3.transaction_type, "ATM_ATM_WITHDRAWAL");
    }

    #[test]
    fn test_transaction_type_all_channels_non_empty() {
        // Ensure transaction_type is never empty for any channel/category combo
        let channels = [
            TransactionChannel::CardPresent,
            TransactionChannel::CardNotPresent,
            TransactionChannel::Atm,
            TransactionChannel::Ach,
            TransactionChannel::Wire,
            TransactionChannel::InternalTransfer,
            TransactionChannel::Mobile,
            TransactionChannel::Online,
            TransactionChannel::Branch,
            TransactionChannel::Cash,
            TransactionChannel::Check,
            TransactionChannel::RealTimePayment,
            TransactionChannel::Swift,
            TransactionChannel::PeerToPeer,
        ];

        for channel in channels {
            let txn = BankTransaction::new(
                Uuid::new_v4(),
                Uuid::new_v4(),
                Decimal::from(100),
                "USD",
                Direction::Outbound,
                channel,
                TransactionCategory::Other,
                CounterpartyRef::unknown("Test"),
                "Test",
                Utc::now(),
            );
            assert!(
                !txn.transaction_type.is_empty(),
                "transaction_type was empty for channel {:?}",
                channel
            );
            // Should be SCREAMING_SNAKE_CASE: only uppercase letters, digits, underscores
            assert!(
                txn.transaction_type
                    .chars()
                    .all(|c| c.is_ascii_uppercase() || c == '_' || c.is_ascii_digit()),
                "transaction_type '{}' is not SCREAMING_SNAKE_CASE for channel {:?}",
                txn.transaction_type,
                channel
            );
        }
    }
}