swift-mt-message 3.1.5

A fast, type-safe Rust implementation of SWIFT MT message parsing with comprehensive field support, derive macros, and validation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! # Error Handling
//!
//! Comprehensive error types for SWIFT MT message parsing and validation.
//!
//! ## Error Types
//! - **ParseError**: Message parsing and field extraction failures
//! - **ValidationError**: Field format and business rule violations
//! - **SwiftValidationError**: SWIFT network validation (1,335 error codes: T/C/D/E/G series)
//!
//! ## Example
//! ```rust
//! use swift_mt_message::parser::SwiftParser;
//! use swift_mt_message::ParseError;
//!
//! # let msg = "{1:F01BANKDEFF...}{2:I103...}{4:-}";
//! match SwiftParser::parse_auto(msg) {
//!     Ok(message) => println!("Success"),
//!     Err(ParseError::InvalidFieldFormat(err)) => {
//!         eprintln!("Field {}: {}", err.field_tag, err.component_name);
//!     },
//!     Err(other) => eprintln!("{}", other),
//! }
//! ```

use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt::{self, Display, Formatter};
use thiserror::Error;

/// Result type alias for the library
///
/// Standard Result type used throughout the library for consistent error handling.
/// All fallible operations return `Result<T>` where T is the success type.
pub type Result<T> = std::result::Result<T, ParseError>;

/// Enhanced result type for SWIFT validation operations
pub type SwiftValidationResult<T> = std::result::Result<T, SwiftValidationError>;

/// Collection of parsing errors for comprehensive error reporting
#[derive(Debug, Serialize, Deserialize)]
pub struct ParseErrorCollection {
    /// All parsing errors encountered
    pub errors: Vec<ParseError>,
    /// Partial parse result if available (not cloneable due to dyn Any)
    #[serde(skip)]
    pub partial_result: Option<Box<dyn Any>>,
}

/// Result of parsing a field with potential error
#[derive(Debug, Clone)]
pub struct FieldParseResult<T> {
    /// Successfully parsed value (if any)
    pub value: Option<T>,
    /// Error encountered during parsing (if any)
    pub error: Option<ParseError>,
}

/// Result type for parse operations with error collection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ParseResult<T> {
    /// Parsing succeeded without errors
    Success(T),
    /// Parsing succeeded with non-critical errors
    PartialSuccess(T, Vec<ParseError>),
    /// Parsing failed with critical errors
    Failure(Vec<ParseError>),
}

/// Parser configuration options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParserConfig {
    /// If true, stop at first error (default: false)
    pub fail_fast: bool,
    /// If true, validate optional fields (default: true)
    pub validate_optional_fields: bool,
    /// If true, collect all errors even for non-critical issues (default: true)
    pub collect_all_errors: bool,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            fail_fast: false,
            validate_optional_fields: true,
            collect_all_errors: true,
        }
    }
}

impl Display for ParseErrorCollection {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        writeln!(f, "Found {} parsing errors:", self.errors.len())?;
        for (idx, error) in self.errors.iter().enumerate() {
            writeln!(f, "\n{}. {}", idx + 1, error)?;
        }
        Ok(())
    }
}

impl std::error::Error for ParseErrorCollection {}

/// Details for invalid field format errors
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvalidFieldFormatError {
    /// SWIFT field tag (e.g., "50K", "32A")
    pub field_tag: String,
    /// Component name within the field (e.g., "currency", "amount")
    pub component_name: String,
    /// The actual value that failed to parse
    pub value: String,
    /// Expected format specification
    pub format_spec: String,
    /// Position in the original message
    pub position: Option<usize>,
    /// Inner parsing error (simplified for serialization)
    pub inner_error: String,
}

/// Main error type for parsing operations
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
pub enum ParseError {
    #[error("Wrong message type: expected {expected}, got {actual}")]
    WrongMessageType { expected: String, actual: String },

    #[error("Unsupported message type: {message_type}")]
    UnsupportedMessageType { message_type: String },

    #[error("Field validation failed: {errors:?}")]
    ValidationFailed { errors: Vec<ValidationError> },

    #[error("IO error: {message}")]
    IoError { message: String },

    #[error(transparent)]
    SwiftValidation(Box<SwiftValidationError>),

    #[error("Serialization error: {message}")]
    SerializationError { message: String },

    /// Invalid message format error
    #[error("Invalid message format: {message}")]
    InvalidFormat { message: String },

    /// Field format error with full context
    #[error("Invalid field format - Field: {}, Component: {}, Value: '{}', Expected: {}", .0.field_tag, .0.component_name, .0.value, .0.format_spec)]
    InvalidFieldFormat(Box<InvalidFieldFormatError>),

    /// Missing required field with detailed context
    #[error("Missing required field {field_tag} ({field_name}) in {message_type}")]
    MissingRequiredField {
        /// SWIFT field tag
        field_tag: String,
        /// Rust field name in the struct
        field_name: String,
        /// Message type (MT103, MT202, etc.)
        message_type: String,
        /// Position where field was expected
        position_in_block4: Option<usize>,
    },

    /// Field parsing failed with detailed context
    #[error(
        "Failed to parse field {field_tag} of type {field_type} at line {position}: {original_error}"
    )]
    FieldParsingFailed {
        /// SWIFT field tag
        field_tag: String,
        /// Type of field being parsed
        field_type: String,
        /// Line number in message
        position: usize,
        /// Original error message
        original_error: String,
    },

    /// Component parsing error with specific details
    #[error(
        "Component parse error in field {field_tag}: {component_name} (index {component_index})"
    )]
    ComponentParseError {
        /// Field tag containing the component
        field_tag: String,
        /// Index of component in field
        component_index: usize,
        /// Name of the component
        component_name: String,
        /// Expected format
        expected_format: String,
        /// Actual value that failed
        actual_value: String,
    },

    /// Invalid block structure with detailed location
    #[error("Invalid block {block} structure: {message}")]
    InvalidBlockStructure {
        /// Block number (1-5)
        block: String,
        /// Detailed error message
        message: String,
    },

    /// Multiple parsing errors collected during message parsing
    #[error("Multiple parsing errors found ({} errors)", .0.len())]
    MultipleErrors(Vec<ParseError>),
}

/// Validation error for field-level validation
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
pub enum ValidationError {
    #[error("Field {field_tag} format validation failed: {message}")]
    FormatValidation { field_tag: String, message: String },

    #[error("Field {field_tag} length validation failed: expected {expected}, got {actual}")]
    LengthValidation {
        field_tag: String,
        expected: String,
        actual: usize,
    },

    #[error("Field {field_tag} pattern validation failed: {message}")]
    PatternValidation { field_tag: String, message: String },

    #[error("Field {field_tag} value validation failed: {message}")]
    ValueValidation { field_tag: String, message: String },

    #[error("Business rule validation failed: {rule_name} - {message}")]
    BusinessRuleValidation { rule_name: String, message: String },
}

/// Comprehensive SWIFT validation error system based on SWIFT Standard Error Codes
///
/// This error system implements all 1,335 SWIFT error codes across T, C, D, E, and G series
/// to provide precise feedback matching SWIFT network validation standards.
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
pub enum SwiftValidationError {
    /// T-Series: Technical/Format Validation Errors (275 codes)
    /// Format validation errors for field structure and basic syntax compliance
    #[error(transparent)]
    Format(Box<SwiftFormatError>),

    /// C-Series: Conditional/Business Rules Errors (57 codes)
    /// Business logic validation for conditional fields and cross-field relationships
    #[error(transparent)]
    Business(Box<SwiftBusinessError>),

    /// D-Series: Data/Content Validation Errors (77 codes)
    /// Content-specific validation including regional requirements and dependencies
    #[error(transparent)]
    Content(Box<SwiftContentError>),

    /// E-Series: Enhanced/Field Relation Validation Errors (86 codes)
    /// Advanced validation for instruction codes and complex business rules
    #[error(transparent)]
    Relation(Box<SwiftRelationError>),

    /// G-Series: General/Field Validation Errors (823 codes)
    /// General field validation across all MT categories
    #[error(transparent)]
    General(Box<SwiftGeneralError>),
}

/// T-Series: Technical/Format Validation Error
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
#[error("Format Error {code}: Field {field} contains '{value}', expected {expected}. {message}")]
pub struct SwiftFormatError {
    /// SWIFT error code (e.g., "T50", "T27")
    pub code: String,
    /// Field tag where error occurred
    pub field: String,
    /// Invalid value that caused the error
    pub value: String,
    /// Expected format or value
    pub expected: String,
    /// Human-readable error message
    pub message: String,
    /// Additional context for error recovery
    pub context: Option<String>,
}

/// C-Series: Conditional/Business Rules Error
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
#[error("Business Rule Violation {code}: {message} (Field: {field})")]
pub struct SwiftBusinessError {
    /// SWIFT error code (e.g., "C02", "C81")
    pub code: String,
    /// Primary field tag involved
    pub field: String,
    /// Related field tags for cross-field validation
    pub related_fields: Vec<String>,
    /// Human-readable error message
    pub message: String,
    /// Business rule that was violated
    pub rule_description: String,
    /// Additional context for error recovery
    pub context: Option<String>,
}

/// D-Series: Data/Content Validation Error
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
#[error("Content Validation Error {code}: {message} (Field: {field})")]
pub struct SwiftContentError {
    /// SWIFT error code (e.g., "D19", "D49")
    pub code: String,
    /// Field tag where error occurred
    pub field: String,
    /// Invalid content that caused the error
    pub content: String,
    /// Human-readable error message
    pub message: String,
    /// Regional or contextual requirements
    pub requirements: String,
    /// Additional context for error recovery
    pub context: Option<String>,
}

/// E-Series: Enhanced/Field Relation Validation Error
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
#[error("Relation Validation Error {code}: {message} (Field: {field})")]
pub struct SwiftRelationError {
    /// SWIFT error code (e.g., "E01", "E15")
    pub code: String,
    /// Primary field tag involved
    pub field: String,
    /// Related field tags that affect this validation
    pub related_fields: Vec<String>,
    /// Instruction code or option that caused the error
    pub instruction_context: Option<String>,
    /// Human-readable error message
    pub message: String,
    /// Relationship rule that was violated
    pub rule_description: String,
    /// Additional context for error recovery
    pub context: Option<String>,
}

/// G-Series: General/Field Validation Error
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
#[error("General Validation Error {code}: {message} (Field: {field})")]
pub struct SwiftGeneralError {
    /// SWIFT error code (e.g., "G001", "G050")
    pub code: String,
    /// Field tag where error occurred
    pub field: String,
    /// Invalid value that caused the error
    pub value: String,
    /// Human-readable error message
    pub message: String,
    /// MT category context (1-9 or Common)
    pub category: Option<String>,
    /// Additional context for error recovery
    pub context: Option<String>,
}

impl From<std::io::Error> for ParseError {
    fn from(err: std::io::Error) -> Self {
        ParseError::IoError {
            message: err.to_string(),
        }
    }
}

impl ParseError {
    /// Get a detailed debug report for the error
    pub fn debug_report(&self) -> String {
        match self {
            ParseError::InvalidFieldFormat(err) => {
                format!(
                    "Field Parsing Error:\n\
                     ├─ Field Tag: {}\n\
                     ├─ Component: {}\n\
                     ├─ Value: '{}'\n\
                     ├─ Expected Format: {}\n\
                     ├─ Position in Message: {}\n\
                     ├─ Details: {}\n\
                     └─ Hint: Check SWIFT format specification for field {}",
                    err.field_tag,
                    err.component_name,
                    err.value,
                    err.format_spec,
                    err.position
                        .map_or("unknown".to_string(), |p| p.to_string()),
                    err.inner_error,
                    err.field_tag
                )
            }
            ParseError::MissingRequiredField {
                field_tag,
                field_name,
                message_type,
                position_in_block4,
            } => {
                format!(
                    "Missing Required Field:\n\
                     ├─ Field Tag: {}\n\
                     ├─ Field Name: {}\n\
                     ├─ Message Type: {}\n\
                     ├─ Expected Position: {}\n\
                     └─ Hint: {} requires field {} to be present",
                    field_tag,
                    field_name,
                    message_type,
                    position_in_block4.map_or("unknown".to_string(), |p| p.to_string()),
                    message_type,
                    field_tag
                )
            }
            ParseError::ComponentParseError {
                field_tag,
                component_index,
                component_name,
                expected_format,
                actual_value,
            } => {
                format!(
                    "Component Parse Error:\n\
                     ├─ Field Tag: {field_tag}\n\
                     ├─ Component: {component_name} (index {component_index})\n\
                     ├─ Expected Format: {expected_format}\n\
                     ├─ Actual Value: '{actual_value}'\n\
                     └─ Hint: Component '{component_name}' must match format '{expected_format}'"
                )
            }
            ParseError::FieldParsingFailed {
                field_tag,
                field_type,
                position,
                original_error,
            } => {
                let line_num = if *position > 0xFFFF {
                    // Old format: encoded position
                    position >> 16
                } else {
                    // New format: just line number
                    *position
                };
                format!(
                    "Field Parsing Failed:\n\
                     ├─ Field Tag: {field_tag}\n\
                     ├─ Field Type: {field_type}\n\
                     ├─ Line Number: {line_num}\n\
                     ├─ Error: {original_error}\n\
                     └─ Hint: Check the field value matches the expected type"
                )
            }
            ParseError::InvalidBlockStructure { block, message } => {
                format!(
                    "Block Structure Error:\n\
                     ├─ Block: {block}\n\
                     ├─ Error: {message}\n\
                     └─ Hint: Ensure block {block} follows SWIFT message structure"
                )
            }
            ParseError::MultipleErrors(errors) => {
                let mut output = format!("Multiple Parsing Errors ({} total):\n", errors.len());
                for (idx, error) in errors.iter().enumerate() {
                    output.push_str(&format!("\n{}. {}\n", idx + 1, error.debug_report()));
                }
                output
            }
            // Fallback for other variants
            _ => format!("{self}"),
        }
    }

    /// Get a concise error message for logging
    pub fn brief_message(&self) -> String {
        match self {
            ParseError::InvalidFieldFormat(err) => {
                format!(
                    "Field {} component '{}' format error",
                    err.field_tag, err.component_name
                )
            }
            ParseError::MissingRequiredField {
                field_tag,
                message_type,
                ..
            } => {
                format!("Required field {field_tag} missing in {message_type}")
            }
            ParseError::ComponentParseError {
                field_tag,
                component_name,
                ..
            } => {
                format!("Field {field_tag} component '{component_name}' parse error")
            }
            ParseError::FieldParsingFailed {
                field_tag,
                field_type,
                position,
                ..
            } => {
                let line_num = if *position > 0xFFFF {
                    position >> 16
                } else {
                    *position
                };
                format!("Field {field_tag} (type {field_type}) parsing failed at line {line_num}")
            }
            ParseError::InvalidBlockStructure { block, .. } => {
                format!("Block {block} structure invalid")
            }
            ParseError::MultipleErrors(errors) => {
                format!("{} parsing errors found", errors.len())
            }
            _ => self.to_string(),
        }
    }

    /// Format error with message context
    pub fn format_with_context(&self, original_message: &str) -> String {
        match self {
            ParseError::FieldParsingFailed { position, .. } => {
                // Extract line and show context
                let lines: Vec<&str> = original_message.lines().collect();
                let line_num = if *position > 0xFFFF {
                    position >> 16
                } else {
                    *position
                };
                let mut output = self.debug_report();

                if line_num > 0 && line_num <= lines.len() {
                    output.push_str("\n\nContext:\n");
                    // Show 2 lines before and after
                    let start = line_num.saturating_sub(3);
                    let end = (line_num + 2).min(lines.len());

                    for (i, line) in lines.iter().enumerate().take(end).skip(start) {
                        if i == line_num - 1 {
                            output.push_str(&format!(">>> {} │ {}\n", i + 1, line));
                        } else {
                            output.push_str(&format!("    {} │ {}\n", i + 1, line));
                        }
                    }
                }
                output
            }
            ParseError::InvalidFieldFormat(err) if err.position.is_some() => {
                let lines: Vec<&str> = original_message.lines().collect();
                let pos = err.position.unwrap();
                let line_num = pos >> 16;
                let mut output = self.debug_report();

                if line_num > 0 && line_num <= lines.len() {
                    output.push_str("\n\nContext:\n");
                    let start = line_num.saturating_sub(3);
                    let end = (line_num + 2).min(lines.len());

                    for (i, line) in lines.iter().enumerate().take(end).skip(start) {
                        if i == line_num - 1 {
                            output.push_str(&format!(">>> {} │ {}\n", i + 1, line));
                        } else {
                            output.push_str(&format!("    {} │ {}\n", i + 1, line));
                        }
                    }
                }
                output
            }
            _ => self.debug_report(),
        }
    }
}

impl From<serde_json::Error> for ParseError {
    fn from(err: serde_json::Error) -> Self {
        ParseError::SerializationError {
            message: err.to_string(),
        }
    }
}

/// SWIFT Error Code Constants
///
/// This module contains all official SWIFT error codes organized by series.
/// Total: 1,335 unique error codes across all MT categories.
pub mod error_codes {
    /// T-Series: Technical/Format Validation Error Codes (275 codes)
    pub mod format {
        pub const T08: &str = "T08"; // Invalid code in field
        pub const T26: &str = "T26"; // Invalid slash usage
        pub const T27: &str = "T27"; // Invalid BIC code format
        pub const T28: &str = "T28"; // Invalid BIC code length
        pub const T29: &str = "T29"; // Invalid BIC code structure
        pub const T40: &str = "T40"; // Invalid amount format
        pub const T43: &str = "T43"; // Amount exceeds maximum digits
        pub const T45: &str = "T45"; // Invalid identifier code format
        pub const T50: &str = "T50"; // Invalid date format
        pub const T52: &str = "T52"; // Invalid currency code
        pub const T56: &str = "T56"; // Invalid structured address
        pub const T73: &str = "T73"; // Invalid country code
        // Additional T-series codes will be added as needed
    }

    /// C-Series: Conditional/Business Rules Error Codes (57 codes)
    pub mod business {
        pub const C02: &str = "C02"; // Currency code mismatch
        pub const C03: &str = "C03"; // Amount format validation
        pub const C08: &str = "C08"; // Commodity currency not allowed
        pub const C81: &str = "C81"; // Conditional field dependency
        // Additional C-series codes will be added as needed
    }

    /// D-Series: Data/Content Validation Error Codes (77 codes)
    pub mod content {
        pub const D17: &str = "D17"; // Field presence requirement
        pub const D18: &str = "D18"; // Mutually exclusive placement
        pub const D19: &str = "D19"; // IBAN mandatory for SEPA
        pub const D20: &str = "D20"; // Field 71A presence rules
        pub const D22: &str = "D22"; // Exchange rate dependency
        pub const D49: &str = "D49"; // Field 33B mandatory for EU
        pub const D50: &str = "D50"; // SHA charge restrictions
        pub const D51: &str = "D51"; // Field 33B with charge fields
        pub const D75: &str = "D75"; // Exchange rate mandatory
        pub const D79: &str = "D79"; // Field 71G dependency
        pub const D93: &str = "D93"; // Account restrictions by code
        // Additional D-series codes will be added as needed
    }

    /// E-Series: Enhanced/Field Relation Validation Error Codes (86 codes)
    pub mod relation {
        pub const E01: &str = "E01"; // Instruction code restrictions
        pub const E02: &str = "E02"; // Prohibited instruction codes
        pub const E03: &str = "E03"; // Field option restrictions
        pub const E04: &str = "E04"; // Party identifier requirements
        pub const E05: &str = "E05"; // Field 54A option restrictions
        pub const E06: &str = "E06"; // Multiple field dependency
        pub const E07: &str = "E07"; // Field 55A option restrictions
        pub const E09: &str = "E09"; // Party identifier mandatory
        pub const E10: &str = "E10"; // Beneficiary account mandatory
        pub const E13: &str = "E13"; // OUR charge restrictions
        pub const E15: &str = "E15"; // BEN charge requirements
        pub const E16: &str = "E16"; // Field restrictions with SPRI
        pub const E17: &str = "E17"; // Clearing code requirements
        pub const E18: &str = "E18"; // Account restrictions CHQB
        pub const E44: &str = "E44"; // Instruction code dependencies
        pub const E45: &str = "E45"; // Instruction code field dependencies
        // Additional E-series codes will be added as needed
    }

    /// G-Series: General/Field Validation Error Codes (823 codes)
    pub mod general {
        pub const G001: &str = "G001"; // Field format violation
        pub const G050: &str = "G050"; // Field content validation
        pub const G100: &str = "G100"; // Sequence validation
        // Additional G-series codes will be added as needed
    }
}

/// Helper functions for creating SWIFT validation errors
impl SwiftValidationError {
    /// Get the SWIFT error code for this validation error
    pub fn error_code(&self) -> &str {
        match self {
            SwiftValidationError::Format(err) => &err.code,
            SwiftValidationError::Business(err) => &err.code,
            SwiftValidationError::Content(err) => &err.code,
            SwiftValidationError::Relation(err) => &err.code,
            SwiftValidationError::General(err) => &err.code,
        }
    }

    /// Create a T-series format validation error
    pub fn format_error(
        code: &str,
        field: &str,
        value: &str,
        expected: &str,
        message: &str,
    ) -> Self {
        SwiftValidationError::Format(Box::new(SwiftFormatError {
            code: code.to_string(),
            field: field.to_string(),
            value: value.to_string(),
            expected: expected.to_string(),
            message: message.to_string(),
            context: None,
        }))
    }

    /// Create a C-series business rule validation error
    pub fn business_error(
        code: &str,
        field: &str,
        related_fields: Vec<String>,
        message: &str,
        rule_description: &str,
    ) -> Self {
        SwiftValidationError::Business(Box::new(SwiftBusinessError {
            code: code.to_string(),
            field: field.to_string(),
            related_fields,
            message: message.to_string(),
            rule_description: rule_description.to_string(),
            context: None,
        }))
    }

    /// Create a D-series content validation error
    pub fn content_error(
        code: &str,
        field: &str,
        content: &str,
        message: &str,
        requirements: &str,
    ) -> Self {
        SwiftValidationError::Content(Box::new(SwiftContentError {
            code: code.to_string(),
            field: field.to_string(),
            content: content.to_string(),
            message: message.to_string(),
            requirements: requirements.to_string(),
            context: None,
        }))
    }

    /// Create an E-series relation validation error
    pub fn relation_error(
        code: &str,
        field: &str,
        related_fields: Vec<String>,
        message: &str,
        rule_description: &str,
    ) -> Self {
        SwiftValidationError::Relation(Box::new(SwiftRelationError {
            code: code.to_string(),
            field: field.to_string(),
            related_fields,
            instruction_context: None,
            message: message.to_string(),
            rule_description: rule_description.to_string(),
            context: None,
        }))
    }

    /// Create a G-series general validation error
    pub fn general_error(
        code: &str,
        field: &str,
        value: &str,
        message: &str,
        category: Option<&str>,
    ) -> Self {
        SwiftValidationError::General(Box::new(SwiftGeneralError {
            code: code.to_string(),
            field: field.to_string(),
            value: value.to_string(),
            message: message.to_string(),
            category: category.map(|s| s.to_string()),
            context: None,
        }))
    }

    /// Get the error code from any SWIFT validation error
    pub fn code(&self) -> &str {
        match self {
            SwiftValidationError::Format(err) => &err.code,
            SwiftValidationError::Business(err) => &err.code,
            SwiftValidationError::Content(err) => &err.code,
            SwiftValidationError::Relation(err) => &err.code,
            SwiftValidationError::General(err) => &err.code,
        }
    }

    /// Get the field tag from any SWIFT validation error
    pub fn field(&self) -> &str {
        match self {
            SwiftValidationError::Format(err) => &err.field,
            SwiftValidationError::Business(err) => &err.field,
            SwiftValidationError::Content(err) => &err.field,
            SwiftValidationError::Relation(err) => &err.field,
            SwiftValidationError::General(err) => &err.field,
        }
    }

    /// Get the error message from any SWIFT validation error
    pub fn message(&self) -> &str {
        match self {
            SwiftValidationError::Format(err) => &err.message,
            SwiftValidationError::Business(err) => &err.message,
            SwiftValidationError::Content(err) => &err.message,
            SwiftValidationError::Relation(err) => &err.message,
            SwiftValidationError::General(err) => &err.message,
        }
    }
}

/// Convert SwiftValidationError to ValidationError for backward compatibility
impl From<SwiftValidationError> for ValidationError {
    fn from(swift_error: SwiftValidationError) -> Self {
        match swift_error {
            SwiftValidationError::Format(err) => ValidationError::FormatValidation {
                field_tag: err.field,
                message: format!("{}: {}", err.code, err.message),
            },
            SwiftValidationError::Business(err) => ValidationError::BusinessRuleValidation {
                rule_name: err.code,
                message: err.message,
            },
            SwiftValidationError::Content(err) => ValidationError::ValueValidation {
                field_tag: err.field,
                message: format!("{}: {}", err.code, err.message),
            },
            SwiftValidationError::Relation(err) => ValidationError::BusinessRuleValidation {
                rule_name: err.code,
                message: err.message,
            },
            SwiftValidationError::General(err) => ValidationError::FormatValidation {
                field_tag: err.field,
                message: format!("{}: {}", err.code, err.message),
            },
        }
    }
}

/// Convert SwiftValidationError to ParseError
impl From<SwiftValidationError> for ParseError {
    fn from(validation_error: SwiftValidationError) -> Self {
        ParseError::SwiftValidation(Box::new(validation_error))
    }
}

/// Convert ValidationError to SwiftValidationError
impl From<ValidationError> for SwiftValidationError {
    fn from(validation_error: ValidationError) -> Self {
        match validation_error {
            ValidationError::FormatValidation { field_tag, message } => {
                SwiftValidationError::format_error("T00", &field_tag, "", "", &message)
            }
            ValidationError::LengthValidation {
                field_tag,
                expected,
                actual,
            } => SwiftValidationError::format_error(
                "T00",
                &field_tag,
                &actual.to_string(),
                &expected,
                "Length validation failed",
            ),
            ValidationError::PatternValidation { field_tag, message } => {
                SwiftValidationError::format_error("T00", &field_tag, "", "", &message)
            }
            ValidationError::ValueValidation { field_tag, message } => {
                SwiftValidationError::content_error("D00", &field_tag, "", &message, "")
            }
            ValidationError::BusinessRuleValidation { rule_name, message } => {
                SwiftValidationError::business_error(&rule_name, "", vec![], &message, "")
            }
        }
    }
}