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
use std::borrow::Cow;
use std::num::NonZeroU8;

use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
use time::macros::format_description;
use time::{Date, OffsetDateTime};
use validator::Validate;

use crate::errors::InvalidError;
use crate::{CanValidate, SDKError};

lazy_static! {
    static ref REGEX_BIRTH_DATE: Regex = Regex::new(r"\d{2}/\d{2}/\d{4}$").unwrap();
}

#[derive(Validate, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct YapayCustomer {
    #[validate]
    pub contacts: Vec<CustomerPhoneContact>,
    #[validate]
    pub addresses: Vec<CustomerAddress>,
    #[validate(length(min = 1))]
    pub name: String,
    /// Format of DD/MM/YYYY
    #[validate(regex = "REGEX_BIRTH_DATE")]
    pub birth_date: String,
    /// Only numbers.
    #[validate(length(equal = 11), custom = "crate::helpers::validate_cpf")]
    pub cpf: String,
    pub cnpj: Option<String>,
    #[validate(email)]
    pub email: String,
}

impl YapayCustomer {
    pub fn new(
        name: String,
        cpf: String,
        email: String,
        birth_date: String,
        phones: Vec<CustomerPhoneContact>,
        address: Vec<CustomerAddress>,
    ) -> Result<Self, InvalidError> {
        let customer = Self {
            contacts: phones,
            addresses: address,
            name,
            birth_date,
            cpf,
            cnpj: None,
            email,
        };

        match customer.validate() {
            Ok(_) => Ok(customer),
            Err(e) => Err(InvalidError::ValidatorLibError(e)),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct CustomerResponse {
    pub name: String,
    pub company_name: String,
    pub trade_name: String,
    pub cnpj: String,
}

#[derive(Validate, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CustomerPhoneContact {
    pub type_contact: PhoneContactType,
    #[validate(length(min = 8, max = 15))]
    pub number_contact: String,
}

#[derive(Validate, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CustomerAddress {
    pub type_address: AddressType,
    /// CEP somente números.
    #[validate(length(max = 8))]
    pub postal_code: String,
    pub street: String,
    pub number: String,
    pub completion: String,
    pub neighborhood: String,
    pub city: String,
    /// Somente a sigla do estado. Exemplo: SP
    #[validate(length(equal = 2))]
    pub state: String,
}

#[derive(Validate, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct YapayProduct {
    pub code: String,
    #[validate(length(max = 50))]
    pub sku_code: String,
    pub description: String,
    pub quantity: String,
    pub price_unit: String,
    pub extra: Option<String>,
}

impl YapayProduct {
    #[must_use]
    pub fn new(
        sku_or_code: String,
        description: String,
        quantity: NonZeroU8,
        price_unit: f64,
    ) -> Self {
        Self {
            code: sku_or_code.clone(),
            sku_code: sku_or_code,
            description,
            quantity: quantity.get().to_string(),
            price_unit: price_unit.to_string(),
            extra: None,
        }
    }
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransactionResponseCommon {}

/// A payment transaction used on requests.
///
/// Use the available builder methods:
///
/// [`YapayTransaction::online_goods`] if there are no shipping address;
///
/// [`YapayTransaction::physical_goods`] if there IS a shipping address;
#[derive(Validate, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct YapayTransaction {
    pub available_payment_methods: String,
    /// When [`Option::none`], this param will be the same as the [`transaction_id`] on
    /// `TransactionResponse`. You must ensure that his field is not repeated ever.
    #[validate(length(max = 20))]
    pub order_number: Option<String>,
    pub customer_ip: String,
    pub shipping_type: Option<String>,
    pub shipping_price: Option<String>,
    pub price_discount: String,
    /// URL in your server to receive IPN (Instant Payment Notification).
    pub url_notification: String,
    pub free: String,
}

impl YapayTransaction {
    /// An online transaction does not include a shipping address.
    ///
    /// `notification_url` should be an URL in your server to receive IPN (Instant Payment
    /// Notification).
    #[must_use]
    pub fn online_goods(
        order_number: String,
        customer_ip: String,
        notification_url: Option<&str>,
    ) -> Self {
        Self {
            available_payment_methods: "2,3,4,5,6,7,14,15,16,18,19,21,22,23".to_string(),
            order_number: Some(order_number),
            customer_ip,
            shipping_type: None,
            shipping_price: None,
            price_discount: "".to_string(),
            url_notification: notification_url.unwrap_or("").to_string(),
            free: "".to_string(),
        }
    }

    /// A physical product include a shipping address.
    pub fn physical_goods() {}
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransactionTrace {
    pub estimated_date: String,
}

/// Represents a card that was previously used to create a payment, and it was saved.
#[derive(Validate, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct YaypaySavedCardData {
    /// Parte do sistema anti-fraude. Obrigatório nos cartões.
    ///
    /// Veja mais sobre em:
    /// [Yapay Fingerprint](https://intermediador.dev.yapay.com.br/#/transacao-fingerprint)
    pub finger_print: String,

    /// The card token UUID that was return after a payment request.
    ///
    /// Example: a66cf237-3541-45d1-ab9c-a6b6e3f795f5
    pub card_token: String,

    #[validate(length(max = 4))]
    pub card_cvv: String,
    #[validate(length(min = 1, max = 2))]
    pub split: String,
}

#[derive(Validate, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[validate(schema(function = "validate_card_exp"))]
pub struct YapayCardData {
    /// Parte do sistema anti-fraude. Obrigatório nos cartões.
    ///
    /// Veja mais sobre em:
    /// [Yapay Fingerprint](https://intermediador.dev.yapay.com.br/#/transacao-fingerprint)
    pub finger_print: String,
    pub payment_method_id: CreditCard,
    pub card_name: String,
    pub card_number: String,

    /// Month in format of MM.
    #[validate(length(equal = 2))]
    pub card_expdate_month: String,

    /// Year in format of YYYY.
    #[validate(length(equal = 4))]
    pub card_expdate_year: String,

    #[validate(length(max = 4))]
    pub card_cvv: String,
    #[validate(length(min = 1, max = 2))]
    pub split: String,
}

impl YapayCardData {
    pub fn new(
        cc: CreditCard,
        cc_owner_name: String,
        cc_number: String,
        cc_exp_mm: String,
        cc_exp_yyyy: String,
        cc_cvv: String,
        installments: i8,
    ) -> Result<YapayCardData, SDKError> {
        let payment = Self {
            finger_print: "".to_string(),
            payment_method_id: cc,
            card_name: cc_owner_name,
            card_number: cc_number,
            card_expdate_month: cc_exp_mm,
            card_expdate_year: cc_exp_yyyy,
            card_cvv: cc_cvv,
            split: installments.to_string(),
        };

        if let Err(err) = payment.validate() {
            Err(InvalidError::ValidatorLibError(err).into())
        } else {
            Ok(payment)
        }
    }
}

impl CanValidate for YapayCardData {}

pub fn validate_card_exp(card_data: &YapayCardData) -> Result<(), validator::ValidationError> {
    let now = OffsetDateTime::now_utc().date();
    let res = validate_card_expiration(
        now,
        &*card_data.card_expdate_month,
        &*card_data.card_expdate_year,
    );

    match res {
        Ok(_) => Ok(()),
        Err(err) => Err(validator::ValidationError {
            code: Cow::from("exp_month and exp_year"),
            message: Some(Cow::from(err.to_string())),
            params: Default::default(),
        }),
    }
}

/// Month: 2 char
/// Year: 4 char
pub fn validate_card_expiration(
    time_cmp: Date,
    exp_month: &str,
    exp_year: &str,
) -> Result<(), SDKError> {
    let card_expiration = Date::parse(
        &*format!("01-{}-{}", exp_month, exp_year),
        format_description!("[day]-[month]-[year]"),
    )
    .unwrap();

    if card_expiration >= time_cmp {
        Ok(())
    } else {
        Err(InvalidError::CreditCardExpired.into())
    }
}

#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Debug)]
pub enum AddressType {
    #[serde(rename = "B")]
    Cobranca,
    #[serde(rename = "D")]
    Entrega,
}

/// Tabela de Contact
#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Debug, strum::Display)]
pub enum PhoneContactType {
    #[serde(rename = "H")]
    Residencial,
    #[serde(rename = "M")]
    Celular,
    #[serde(rename = "W")]
    Comercial,
}

/// Tabela de Contact
#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Debug)]
pub enum PaymentType {
    BankTransfer(BankTransfer),
}

#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Debug)]
pub enum BankTransfer {
    #[serde(rename = "7")]
    ItauShopline,
    #[serde(rename = "23")]
    BancoDoBrasil,
}

#[derive(Copy, Clone, Deserialize, Serialize, PartialEq, Debug)]
pub enum CreditCard {
    #[serde(rename = "3")]
    Visa,
    #[serde(rename = "4")]
    MasterCard,
    #[serde(rename = "5")]
    Amex,
    #[serde(rename = "16")]
    Elo,
    #[serde(rename = "20")]
    HiperCard,
    #[serde(rename = "25")]
    HiperItau,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Card {
    pub first_six_digits: String,
    pub last_four_digits: String,
    pub expiration_month: i64,
    pub expiration_year: i64,

    pub card_number_length: i64,
    pub security_code_length: i64,

    #[serde(with = "time::serde::rfc3339")]
    pub date_created: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub date_last_updated: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub date_due: OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResponseRoot<T> {
    pub message_response: ResponseMessage,
    pub data_response: T,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResponseMessage {
    pub message: String,
}

#[cfg(test)]
mod tests {
    use time::macros::format_description;
    use time::Date;

    use crate::common_types::validate_card_expiration;

    #[test]
    fn cc_valid_date() {
        let fmt = format_description!("[year]/[month padding:zero]/[day]");
        let datetime = Date::parse("2022/05/01", &fmt).unwrap();

        let res = validate_card_expiration(datetime, "05", "2022");
        assert!(res.is_ok());
    }

    #[test]
    fn cc_invalid_date() {
        let fmt = format_description!("[year]/[month padding:zero]/[day]");
        let datetime = Date::parse("2022/05/01", &fmt).unwrap();

        let res = validate_card_expiration(datetime, "06", "2021");
        assert!(res.is_err());
    }
}