tmflib 0.1.38

Interface library for processing TMF payloads
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
//! Customer Module
//!
use chrono::Utc;
use serde::{Deserialize, Serialize};

#[cfg(all(feature = "tmf632", feature = "build-V4"))]
use crate::tmf632::organization_v4::Organization;
#[cfg(all(feature = "tmf632", feature = "build-V5"))]
use crate::tmf632::organization_v5::Organization;

use super::characteristic::Characteristic;
use crate::common::contact::ContactMedium;
use crate::common::event::{Event, EventPayload};
use crate::common::related_party::RelatedParty;
use crate::{gen_code, HasId, HasName, HasReference, HasValidity, TMFEvent, TimePeriod};
use tmflib_derive::{HasId, HasName, HasValidity};
use uuid::Uuid;

use super::MOD_PATH;

const CLASS_PATH: &str = "customer";
const CUST_ID_SIZE: usize = 5;
/// Default customer status
pub const CUST_STATUS: &str = "New";
const CUST_SEGMENT_CHAR: &str = "marketSegment";

/// Customer object
#[derive(Clone, Default, Debug, Deserialize, HasId, HasName, HasValidity, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Customer {
    /// Html Reference to this object
    pub href: Option<String>,
    /// Unique Id
    pub id: Option<String>,
    /// Name of this
    pub name: Option<String>,
    /// Customer status
    pub status: Option<String>,
    /// Reason for current status
    pub status_reason: Option<String>,
    /// Validity of this record
    pub valid_for: Option<TimePeriod>,
    contact_medium: Option<Vec<ContactMedium>>,
    characteristic: Option<Vec<Characteristic>>,
    related_party: Vec<RelatedParty>,
    engaged_party: Option<RelatedParty>,
}

impl Customer {
    /// Create new customer object against an [Organization] (legal entity)
    /// ```
    /// # use tmflib::tmf629::customer::Customer;
    /// #[cfg(all(feature = "tmf632", feature = "build-V4"))]
    /// # use tmflib::tmf632::organization_v4::Organization;
    /// #[cfg(all(feature = "tmf632", feature = "build-V5"))]
    /// # use tmflib::tmf632::organization_v5::Organization;
    /// let org = Organization::new("Legal Entity");
    /// let cust = Customer::new(org);
    /// ```
    pub fn new(org: Organization) -> Customer {
        let mut cust = Customer::create();
        cust.name = Some(org.get_name());
        // Not sure on including the name here but the id is only generated on create(), so a name change would
        // not impact the generated code. Ideally as we're throwing away a lot of the resulting hash to get the
        // code, it might help avoid collisions if we add some more entropy?
        cust.generate_code(None);
        cust.engaged_party = Some(RelatedParty::from(org));

        cust.status = Some(CUST_STATUS.to_string());
        cust.contact_medium = Some(vec![]);
        cust
    }

    /// Geneate a unique customer code via cryptographic functions
    /// Uses [crate::gen_code].
    pub fn generate_code(&mut self, offset: Option<u32>) {
        // Generate a new code based on name

        // Generate Id if none exists
        if self.id.is_none() {
            self.generate_id();
        };

        // Generate code
        let (code, hash) = gen_code(
            self.get_name(),
            self.get_id(),
            offset,
            None,
            Some(CUST_ID_SIZE),
        );

        let code = Characteristic {
            name: String::from("code"),
            value_type: String::from("string"),
            value: code.into(),
        };
        let hash = Characteristic {
            name: String::from("hash"),
            value_type: String::from("string"),
            value: hash.into(),
        };
        // Create vec if it doesn't exist
        if self.characteristic.is_none() {
            self.characteristic = Some(vec![]);
        }

        // Replace characteristics if they exist, to ensure only a single instance of each
        self.replace_characteristic(code);
        self.replace_characteristic(hash);
    }

    /// Try to find characteristic with given name
    pub fn get_characteristic(&self, characteristic: &str) -> Option<Characteristic> {
        match &self.characteristic {
            Some(c) => c.iter().find(|x| x.name == characteristic).cloned(),
            None => None,
        }
    }

    /// Replace a characteristic returning the old value if found.
    /// Creates the characteristic array if it doesn't exist.
    /// Creates the characteristic entry if it doesn't exist.
    /// Replaces the characteristic entry if it does exist.
    ///
    /// # Returns
    /// Will return the previous value if it existed.
    /// This
    /// # Example
    /// ```
    /// # use tmflib::tmf629::{characteristic::Characteristic,customer::Customer};
    /// let mut cust = Customer::default();
    /// let char = Characteristic::from(("Validated","NotYet"));
    /// let old_char = cust.replace_characteristic(char);
    ///
    /// assert_eq!(old_char.is_none(),true);
    /// ```
    pub fn replace_characteristic(
        &mut self,
        characteristic: Characteristic,
    ) -> Option<Characteristic> {
        match self.characteristic.as_mut() {
            Some(c) => {
                // Characteristic array exist
                let pos = c.iter().position(|c| c.name == characteristic.name);
                match pos {
                    Some(u) => {
                        // Clone old value for return
                        let old = c[u].clone();
                        // Replace
                        c[u] = characteristic;
                        Some(old)
                    }
                    None => {
                        // This means the characteristic could not be found, instead we insert it
                        // Additional we return None to indicate that no old value was found
                        c.push(characteristic);
                        None
                    }
                }
            }
            None => {
                // Characteristic Vec was not created yet, create it now.
                self.characteristic = Some(vec![characteristic]);
                // Return None to show no previous value existed.
                None
            }
        }
    }

    /// Set the name of the customer
    pub fn name(&mut self, name: String) {
        self.name = Some(name.clone());
    }

    /// Set the market segment
    pub fn set_market_segment(&mut self, segment: impl Into<String>) -> Option<Characteristic> {
        let segment_char = Characteristic::new(CUST_SEGMENT_CHAR, segment);
        self.replace_characteristic(segment_char)
    }

    /// Get the market segment
    pub fn get_market_segment(&self) -> Option<Characteristic> {
        self.get_characteristic(CUST_SEGMENT_CHAR)
    }

    /// Upgrade the customer to a cryptographic code to replace a sequential Id.
    /// Will return the newly generated cryptographic code.
    /// Takes the following steps:
    /// -   Moves existing ID into characteristic of 'Id'
    /// -   Generate cryptographic code via generate_code
    /// -   Replace Id, with newly genreated code.
    /// -   Returns new code.
    ///
    /// # Returns
    /// Will return the new code.
    /// # Example
    /// ```
    /// # use tmflib::tmf629::{characteristic::Characteristic,customer::Customer};
    /// # use tmflib::HasId;
    /// let mut cust = Customer::default();
    /// cust.set_id("1");
    /// let char = cust.upgrade_to_code(None);
    /// ```
    pub fn upgrade_to_code(&mut self, offset: Option<u32>) -> Option<Characteristic> {
        // Step 1, Create new Characteristic for old Id
        let old_id = Characteristic {
            name: String::from("Id"),
            value_type: String::from("string"),
            value: self.get_id().into(),
        };
        self.replace_characteristic(old_id);
        // Step 2, generate new code
        self.generate_code(offset);
        let code = self.get_characteristic("code")?;
        // Step 3, We can only set the id if code was found
        let code_val = code.value.as_str()?;
        self.set_id(code_val.to_string());
        // Step 4, return new code
        Some(code)
    }
}

impl From<&Organization> for Customer {
    fn from(value: &Organization) -> Self {
        let mut customer = Customer::new(value.to_owned());
        customer.generate_code(None);
        customer
    }
}

impl HasReference for Customer {
    type RefType = RelatedParty;
    fn as_ref(&self) -> Option<Self::RefType> {
        Some(RelatedParty::from(self))
    }
}

/// Customer Event Type
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum CustomerEventType {
    /// Customer Created
    CustomerCreateEvent,
    /// Customer Attribute Changed
    CustomerAttributeValueChangeEvent,
    /// Customer Status Changed
    CustomerStateChangeEvent,
    /// Customer Deleted
    CustomerDeleteEvent,
}

/// Container for the payload
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CustomerEvent {
    /// Customer
    pub customer: Customer,
}

impl TMFEvent<CustomerEvent> for Customer {
    fn event(&self) -> CustomerEvent {
        CustomerEvent {
            customer: self.clone(),
        }
    }
}

impl EventPayload<CustomerEvent> for Customer {
    type Subject = Customer;
    type EventType = CustomerEventType;

    fn to_event(
        &self,
        event_type: Self::EventType,
    ) -> crate::common::event::Event<CustomerEvent, Self::EventType> {
        let now = Utc::now();
        let desc = format!(
            "{:?} for {} [{}]",
            event_type,
            self.get_name(),
            self.get_id()
        );
        let event_time = chrono::DateTime::from_timestamp(now.timestamp(), 0).unwrap();
        let code = self.get_characteristic("code");
        let code = code.map(|f| f.value);
        Event {
            correlation_id: Some(code.unwrap_or_default().to_string()),
            description: Some(desc),
            domain: Some(Customer::get_class()),
            event_id: Uuid::new_v4().to_string(),
            field_path: None,
            href: Some(self.get_href()),
            id: Some(self.get_id()),
            title: Some(self.get_name()),
            event_time: event_time.to_string(),
            priority: None,
            time_occurred: Some(event_time.to_string()),
            event_type,
            event: self.event(),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    const CUSTOMER: &str = "ACustomer";
    const CUSTOMER_BAD: &str = " ACustomer ";
    const CUSTOMER_UID: u16 = 174;
    const CUSTOMER_SEGMENT: &str = "MarketSegment";

    #[test]
    fn test_customer_new_name() {
        let org = Organization::new(CUSTOMER);
        let customer = Customer::new(org);

        assert_eq!(customer.name, Some(CUSTOMER.into()));
        assert_eq!(customer.id.is_some(), true);
        assert_eq!(customer.href.is_some(), true);
    }

    #[test]
    fn test_customer_new_org() {
        let org1 = Organization::new(CUSTOMER);
        let org2 = org1.clone();
        let customer = Customer::new(org1);

        assert_eq!(customer.engaged_party, Some(RelatedParty::from(org2)));
    }

    #[test]
    fn test_customer_new_code() {
        let org1 = Organization::new(CUSTOMER);
        let customer = Customer::new(org1);

        assert!(customer.get_characteristic("code").is_some());
    }

    #[test]
    fn test_customer_from_org() {
        let org1 = Organization::new(CUSTOMER);
        let customer = Customer::from(&org1);

        assert_eq!(org1.name, customer.name);
    }

    #[test]
    fn test_customer_characteristic_replace() {
        let org1 = Organization::new(CUSTOMER);
        let mut customer = Customer::from(&org1);

        let code_new = Characteristic {
            name: "code".into(),
            value: "ABC".into(),
            value_type: "String".into(),
        };
        let code_new_clone = code_new.clone();
        let code_old = customer.get_characteristic("code");
        let code_replace = customer.replace_characteristic(code_new);
        let code_replaced = customer.get_characteristic("code");

        // code_old and code_replace should be the same
        assert_eq!(code_old.unwrap().value, code_replace.unwrap().value);
        // code_new and code_replaced should be the same
        assert_eq!(code_new_clone.value, code_replaced.unwrap().value);
    }

    #[test]
    fn test_customer_code_whitespace() {
        // use default() to avoid id generation via new()
        let mut cust1 = Customer::default();
        cust1.set_id(CUSTOMER_UID.to_string());
        cust1.set_name(CUSTOMER);

        // Create second customer using name with whitespace
        let mut cust2 = Customer::default();
        cust2.set_id(CUSTOMER_UID.to_string());
        cust2.set_name(CUSTOMER_BAD);

        // Generate customer codes
        cust1.generate_code(None);
        cust2.generate_code(None);

        let code1 = cust1.get_characteristic("code").unwrap();
        let code2 = cust2.get_characteristic("code").unwrap();

        // Customer codes should be the same, but the ID is different.
        assert_eq!(code1.value, code2.value);
    }

    #[test]
    fn test_customer_characteristic_new_missing() {
        // Test replacing a non-existing characteristic
        let characteristic = Characteristic::from(("weather", "rainy"));

        let org1 = Organization::new(CUSTOMER);
        let mut customer = Customer::from(&org1);

        customer.replace_characteristic(characteristic);

        let test_char = customer.get_characteristic("weather");

        assert!(test_char.is_some());
    }

    #[test]
    fn test_customer_characteristic_default_missing() {
        // Test replacing a non-existing characteristic, on a default Customer (i.e. no Vec creatd)
        let characteristic = Characteristic::from(("weather", "rainy"));

        let mut customer = Customer::default();

        customer.replace_characteristic(characteristic);

        let test_char = customer.get_characteristic("weather");

        assert!(test_char.is_some());
    }

    #[test]
    fn test_customer_upgrade_to_code() {
        let mut customer = Customer::default();
        customer.set_id("1");
        let code = customer.upgrade_to_code(None).unwrap();

        let char = customer.get_characteristic("code");

        // Returned value should match "code" characteristic
        assert_eq!(code.value, char.unwrap().value);
        // Simlarly, the id should match the code
        assert_eq!(code.value, customer.get_id());
    }

    #[test]
    fn test_customer_marketsegment() {
        let mut customer = Customer::default();
        let old_segment = customer.set_market_segment(CUSTOMER_SEGMENT.to_string());

        assert_eq!(old_segment.is_none(), true);

        let segment = customer.get_market_segment();

        assert_eq!(segment.is_some(), true);
        assert_eq!(segment.unwrap().value, CUSTOMER_SEGMENT);
    }

    #[test]
    fn test_customer_noid() {
        let customer = Customer::default();

        assert_eq!(customer.get_id(), String::default());
        assert_eq!(customer.get_href(), String::default());
    }

    #[test]
    fn test_customer_asref() {
        let org = Organization::new(CUSTOMER);
        let customer = Customer::from(&org);

        let ref_party = customer.as_ref().unwrap();

        assert_eq!(ref_party.name.unwrap(), CUSTOMER.to_string());
        assert_eq!(ref_party.id, customer.get_id());
        assert_eq!(ref_party.href, customer.get_href());
    }
}