1use crate::{
4 UfBrasil,
5 error::{Error, Result},
6};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Ambiente {
10 Homologacao,
11 Producao,
12}
13
14impl Ambiente {
15 pub fn codigo(&self) -> u8 {
16 match self {
17 Ambiente::Homologacao => 2,
18 Ambiente::Producao => 1,
19 }
20 }
21}
22
23#[derive(Debug, Clone)]
24pub struct Config {
25 pub cnpj: String,
26 pub uf: UfBrasil,
27 pub ambiente: Ambiente,
28 pub timeout_secs: u64,
29 pub tentar_novamente: bool,
30 pub max_tentativas: u32,
31}
32
33impl Config {
34 pub fn validar(&self) -> Result<()> {
35 if self.cnpj.len() != 14 {
36 return Err(Error::Config("CNPJ deve ter 14 dígitos".to_string()));
37 }
38 if !self.cnpj.chars().all(|c| c.is_ascii_digit()) {
39 return Err(Error::Config("CNPJ deve conter apenas números".to_string()));
40 }
41 Ok(())
42 }
43
44 pub fn with_timeout(mut self, timeout_secs: u64) -> Self {
45 self.timeout_secs = timeout_secs;
46 self
47 }
48
49 pub fn with_retry(mut self, tentar: bool, max_tentativas: u32) -> Self {
50 self.tentar_novamente = tentar;
51 self.max_tentativas = max_tentativas;
52 self
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn test_config_new() {
62 let config = {
63 let cnpj = "99999999999999".to_string();
64 let uf = UfBrasil::SP;
65 let ambiente = Ambiente::Homologacao;
66 Config {
67 cnpj,
68 uf,
69 ambiente,
70 timeout_secs: 30,
71 tentar_novamente: true,
72 max_tentativas: 3,
73 }
74 };
75 assert_eq!(config.cnpj, "99999999999999");
76 assert_eq!(config.timeout_secs, 30);
77 }
78
79 #[test]
80 fn test_config_validar_sucesso() {
81 let config = {
82 let cnpj = "12345678000199".to_string();
83 let uf = UfBrasil::SP;
84 let ambiente = Ambiente::Producao;
85 Config {
86 cnpj,
87 uf,
88 ambiente,
89 timeout_secs: 30,
90 tentar_novamente: true,
91 max_tentativas: 3,
92 }
93 };
94 assert!(config.validar().is_ok());
95 }
96
97 #[test]
98 fn test_config_validar_cnpj_invalido() {
99 let config = {
100 let cnpj = "123".to_string();
101 let uf = UfBrasil::SP;
102 let ambiente = Ambiente::Producao;
103 Config {
104 cnpj,
105 uf,
106 ambiente,
107 timeout_secs: 30,
108 tentar_novamente: true,
109 max_tentativas: 3,
110 }
111 };
112 assert!(config.validar().is_err());
113 }
114
115 #[test]
116 fn test_config_validar_cnpj_invalido_com_letras() {
117 let config = {
118 let cnpj = "1234teste".to_string();
119 let uf = UfBrasil::SP;
120 let ambiente = Ambiente::Producao;
121 Config {
122 cnpj,
123 uf,
124 ambiente,
125 timeout_secs: 30,
126 tentar_novamente: true,
127 max_tentativas: 3,
128 }
129 };
130 assert!(config.validar().is_err());
131 }
132
133 #[test]
134 fn test_ambiente_codigo() {
135 assert_eq!(Ambiente::Homologacao.codigo(), 2);
136 assert_eq!(Ambiente::Producao.codigo(), 1);
137 }
138}