1
+ use crate :: eu_vat:: EUVat ;
2
+ use crate :: gb_vat:: GBVat ;
3
+ use crate :: errors:: ValidationError ;
4
+
5
+ pub trait TaxIdType {
6
+ fn name ( & self ) -> & ' static str ;
7
+ }
8
+
9
+ struct TaxId {
10
+ value : String ,
11
+ country_code : String ,
12
+ local_value : String ,
13
+ id_type : & ' static str ,
14
+ }
15
+
16
+ impl TaxId {
17
+ pub fn new ( value : & str ) -> Result < TaxId , ValidationError > {
18
+ let country_code = & value[ 0 ..2 ] ;
19
+ let local_value = & value[ 2 ..] ;
20
+ let id_type: Box < dyn TaxIdType > = match country_code {
21
+ "SE" => Box :: new ( EUVat ) ,
22
+ "GB" => Box :: new ( GBVat ) ,
23
+ _ => return Err ( ValidationError :: new ( "Unknown country code" ) )
24
+ } ;
25
+
26
+ Ok ( TaxId {
27
+ id_type : id_type. name ( ) ,
28
+ value : value. to_string ( ) ,
29
+ country_code : country_code. to_string ( ) ,
30
+ local_value : local_value. to_string ( ) ,
31
+ } )
32
+ }
33
+
34
+ pub fn value ( & self ) -> & str { & self . value }
35
+ pub fn country_code ( & self ) -> & str { & self . country_code }
36
+ pub fn local_value ( & self ) -> & str { & self . local_value }
37
+ pub fn id_type ( & self ) -> & str { & self . id_type }
38
+ }
39
+
40
+ #[ cfg( test) ]
41
+ mod tests {
42
+ use super :: * ;
43
+
44
+ #[ test]
45
+ fn test_new_eu_vat ( ) {
46
+ let tax_id= TaxId :: new ( "SE1234567890" ) . unwrap ( ) ;
47
+ assert_eq ! ( tax_id. value( ) , "SE1234567890" ) ;
48
+ assert_eq ! ( tax_id. country_code( ) , "SE" ) ;
49
+ assert_eq ! ( tax_id. local_value( ) , "1234567890" ) ;
50
+ assert_eq ! ( tax_id. id_type( ) , "eu_vat" ) ;
51
+ }
52
+
53
+ #[ test]
54
+ fn test_new_gb_vat ( ) {
55
+ let tax_id = TaxId :: new ( "GB123456789" ) . unwrap ( ) ;
56
+ assert_eq ! ( tax_id. value( ) , "GB123456789" ) ;
57
+ assert_eq ! ( tax_id. country_code( ) , "GB" ) ;
58
+ assert_eq ! ( tax_id. local_value( ) , "123456789" ) ;
59
+ assert_eq ! ( tax_id. id_type( ) , "gb_vat" ) ;
60
+ }
61
+
62
+ #[ test]
63
+ #[ should_panic( expected = "Unknown country code" ) ]
64
+ fn test_new_unknown_country_code ( ) {
65
+ let _ = TaxId :: new ( "XX123456789" ) . unwrap ( ) ;
66
+ }
67
+ }
0 commit comments