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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use strum_macros::{EnumString, ToString};

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DebitNoteEvent {
    pub debit_note_id: String,
    pub event_date: DateTime<Utc>,
    #[serde(flatten)]
    pub event_type: DebitNoteEventType,
}

#[derive(Clone, Debug, Serialize, Deserialize, EnumString, ToString)]
#[serde(tag = "eventType")]
pub enum DebitNoteEventType {
    #[strum(to_string = "RECEIVED")]
    DebitNoteReceivedEvent,
    #[strum(to_string = "ACCEPTED")]
    DebitNoteAcceptedEvent,
    #[strum(to_string = "REJECTED")]
    DebitNoteRejectedEvent {
        rejection: crate::payment::Rejection,
    },
    #[strum(to_string = "CANCELLED")]
    DebitNoteCancelledEvent,
    #[strum(to_string = "SETTLED")]
    DebitNoteSettledEvent,
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::payment::{Rejection, RejectionReason};
    use bigdecimal::{BigDecimal, FromPrimitive};
    use chrono::TimeZone;

    #[test]
    fn test_serialize_rejected_event_has_flat_rejection() {
        let ie = DebitNoteEvent {
            debit_note_id: "ajdik".to_string(),
            event_date: Utc
                .datetime_from_str("2020-12-21T15:51:21.126645Z", "%+")
                .unwrap(),
            event_type: DebitNoteEventType::DebitNoteRejectedEvent {
                rejection: Rejection {
                    rejection_reason: RejectionReason::UnsolicitedService,
                    total_amount_accepted: BigDecimal::from_f32(3.14).unwrap(),
                    message: None,
                },
            },
        };

        assert_eq!(
            "{\"debitNoteId\":\"ajdik\",\
                \"eventDate\":\"2020-12-21T15:51:21.126645Z\",\
                \"eventType\":\"DebitNoteRejectedEvent\",\
                \"rejection\":{\
                    \"rejectionReason\":\"UNSOLICITED_SERVICE\",\
                    \"totalAmountAccepted\":\"3.140000\"\
                }\
             }",
            serde_json::to_string(&ie).unwrap()
        );
    }
}