amfnengine 0.3.5

Amortization Functions (AmFn) Engine
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! List of locales.
// Copyright (c) 2021 ShiftLeft Software
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use regex::Regex;
use rust_decimal::prelude::*;
use std::cell::Cell;
use std::collections::HashMap;

use super::{ElemLocale, ElemLocaleFormat};
use crate::core::CoreUtility;
use crate::ListTrait;

pub struct ListLocale {
    list_locale: Vec<ElemLocale>,

    /// Currently selected locale element.
    list_index: Cell<usize>,

    /// Currently selected user locale element.
    list_index_user: Cell<usize>,

    /// Currently selected cashflow locale element.
    list_index_cashflow: Cell<usize>,

    /// Currently selected event locale element.
    list_index_event: Cell<usize>,
}

/// List of currently active cashflows list implementation.

impl ListTrait for ListLocale {
    /// Clear all locales selects.

    fn clear(&mut self) {
        self.list_index_user.set(usize::MAX);
        self.list_index_cashflow.set(usize::MAX);
        self.list_index_event.set(usize::MAX);

        self.list_locale.clear();
    }

    /// Get the count of the locales list.
    ///
    /// # Return
    ///
    /// * See description.

    fn count(&self) -> usize {
        self.list_locale.len()
    }

    /// Get the index of the selected user locale (starting from 0).
    ///
    /// # Return
    ///
    /// * See description.

    fn index(&self) -> usize {
        self.list_index.get()
    }

    /// Select a locale based upon an index value.
    ///
    /// # Arguments
    ///
    /// * `index_param` - The index value of the locale to select (starting from 0).
    ///
    /// # Return
    ///
    /// * True if successful, otherwise false.

    fn get_element(&self, index_param: usize) -> bool {
        if index_param >= self.list_locale.len() {
            return false;
        }

        self.set_index(index_param);

        true
    }

    /// Set the list index.
    ///
    /// # Arguments
    ///
    /// * `index_param` - See description.

    fn set_index(&self, index_param: usize) -> bool {
        if index_param >= self.list_locale.len() {
            return false;
        }

        self.list_index.set(index_param);

        true
    }
}

/// List of locales default implementation.

impl Default for ListLocale {
    /// Create and return a new list of locale elements.
    ///
    /// # Return
    ///
    /// * See description.

    fn default() -> Self {
        ListLocale::new()
    }
}

/// List of locales implementation.

impl ListLocale {
    /// Create and return a new list of locale elements.
    ///
    /// # Return
    ///
    /// * See description.
    pub fn new() -> ListLocale {
        ListLocale {
            list_locale: Vec::new(),
            list_index: Cell::new(usize::MAX),
            list_index_user: Cell::new(usize::MAX),
            list_index_cashflow: Cell::new(usize::MAX),
            list_index_event: Cell::new(usize::MAX),
        }
    }

    /// Add a new locale to the locale list.
    ///
    /// # Arguments
    ///
    /// * `locale_str_param` - ISO language code (ISO 639)_ISO country code (ISO 3166).
    /// * `currency_code_param` - ISO currency code (ISO 4217).
    /// * `decimal_digits_param` - Currency decimal digits.
    /// * `date_in_format` - Date in format.
    /// * `date_out_format` - Date out format.
    /// * `resources_param` - Resources hash map.

    pub fn add_locale(
        &mut self,
        locale_str_param: &str,
        currency_code_param: &str,
        decimal_digits_param: usize,
        date_in_format_param: ElemLocaleFormat,
        date_out_format_param: ElemLocaleFormat,
        resources_param: HashMap<String, String>,
    ) {
        let resources = resources_param;

        self.list_locale.push(ElemLocale::new(
            locale_str_param,
            currency_code_param,
            decimal_digits_param,
            date_in_format_param,
            date_out_format_param,
            resources,
        ));
    }

    /// Append to the list locale.
    ///
    /// # Arguments
    ///
    /// * `list_locale` - See description.

    pub fn append_locales(&mut self, mut list_locale: ListLocale) {
        loop {
            match list_locale.list_locale.pop() {
                None => {
                    break;
                }
                Some(o) => {
                    self.list_locale.push(o);
                }
            }
        }
    }

    /// Copy the locale list and return a new locale list.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn copy(&self) -> ListLocale {
        let mut locales = ListLocale::new();

        for locale in self.list_locale.iter() {
            locales.add_locale(
                locale.locale_str(),
                locale.currency_code(),
                locale.decimal_digits(),
                locale.format_in().copy(),
                locale.format_out().copy(),
                locale.resources().clone(),
            );
        }

        locales
    }

    /// Get the locale string.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn locale_str(&self, event: bool) -> &str {
        match self.list_locale.get(self.get_locale_index(event)) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o.locale_str(),
        }
    }

    /// Get the currency code.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn currency_code(&self, event: bool) -> &str {
        match self.list_locale.get(self.get_locale_index(event)) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o.currency_code(),
        }
    }

    /// Get the decimal digits.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn decimal_digits(&self, event: bool) -> usize {
        match self.list_locale.get(self.get_locale_index(event)) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o.decimal_digits(),
        }
    }

    /// Get the format in.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_in(&self, event: bool) -> &ElemLocaleFormat {
        match self.list_locale.get(self.get_locale_index(event)) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o.format_in(),
        }
    }

    /// Get the format out.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_out(&self, event: bool) -> &ElemLocaleFormat {
        match self.list_locale.get(self.get_locale_index(event)) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o.format_out(),
        }
    }

    /// Get the resources.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn resources(&self, event: bool) -> &HashMap<String, String> {
        match self.list_locale.get(self.get_locale_index(event)) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o.resources(),
        }
    }

    /// Get the user locale.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn user_locale(&self) -> &ElemLocale {
        match self.list_locale.get(self.list_index_user.get()) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o,
        }
    }

    /// Get the cashflow locale.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn cashflow_locale(&self) -> &ElemLocale {
        match self.list_locale.get(self.list_index_cashflow.get()) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o,
        }
    }

    /// Get the event locale.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn event_locale(&self) -> &ElemLocale {
        match self.list_locale.get(self.list_index_event.get()) {
            None => {
                panic!("Locale list index not set");
            }
            Some(o) => o,
        }
    }

    /// Return the cashflow currency code.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn cashflow_currency_code(&self) -> &str {
        self.get_locale(false).currency_code()
    }

    /// Return the event currency code.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn event_currency_code(&self) -> &str {
        self.get_locale(true).currency_code()
    }

    /// Format a date and return the internal format.
    ///
    /// # Arguments
    ///
    /// * `display_val` - The display value to parse.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_date_in(&self, display_val: &str) -> String {
        let text: String = match Regex::new(self.get_locale(true).format_in().date_regex()) {
            Err(_e) => return String::from(display_val),
            Ok(o) => o
                .replace(
                    display_val,
                    self.get_locale(true).format_in().date_replace(),
                )
                .to_string(),
        };

        let dd: Vec<_> = text.split('-').collect();
        if dd.len() != 3 {
            let now = CoreUtility::date_now();
            return format!("{:04}-{:02}-{:02}", now / 10000, now / 100 % 100, now % 100);
        }

        let mut year = String::from(dd[0]);
        if year.len() < 3 {
            let century = if CoreUtility::parse_integer(year.as_str()) < crate::SERIAL_BASE_CENTURY
            {
                "20"
            } else {
                "19"
            };
            year = format!("{}{}", century, self.zerofill(year.as_str(), 2));
        }

        if year.len() != 4 {
            let now = CoreUtility::date_now();
            return format!("{:04}-{:02}-{:02}", now / 10000, now / 100 % 100, now % 100);
        }

        format!(
            "{:04}-{:02}-{:02}",
            year,
            self.zerofill(dd[1], 2),
            self.zerofill(dd[2], 2)
        )
    }

    /// Format an integer and return the internal format.
    ///
    /// # Arguments
    ///
    /// * `display_val` - The display value to parse.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_integer_in(&self, display_val: &str) -> String {
        match Regex::new(self.get_locale(true).format_in().integer_regex()) {
            Err(_e) => String::from(display_val),
            Ok(o) => o
                .replace(
                    display_val,
                    self.get_locale(true).format_in().integer_replace(),
                )
                .to_string(),
        }
    }

    /// Format a decimal and return the internal format.
    ///
    /// # Arguments
    ///
    /// * `display_val` - The display value to parse.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_decimal_in(&self, display_val: &str) -> String {
        match Regex::new(self.get_locale(true).format_in().decimal_regex()) {
            Err(_e) => String::from(display_val),
            Ok(o) => o
                .replace(
                    display_val,
                    self.get_locale(true).format_in().decimal_replace(),
                )
                .to_string(),
        }
    }

    /// Format a currency and return the internal format.
    ///
    /// # Arguments
    ///
    /// * `display_val` - The display value to parse.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_currency_in(&self, display_val: &str) -> String {
        match Regex::new(self.get_locale(true).format_in().currency_regex()) {
            Err(_e) => String::from(display_val),
            Ok(o) => o
                .replace(
                    display_val,
                    self.get_locale(true).format_in().currency_replace(),
                )
                .to_string(),
        }
    }

    /// Format and return a date string.
    ///
    /// # Arguments
    ///
    /// * `val` - The usize date value to format.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_date_out(&self, val: usize) -> String {
        let text = format!("{:04}-{:02}-{:02}", val / 10000, val / 100 % 100, val % 100);

        match Regex::new(self.get_locale(true).format_out().date_regex()) {
            Err(_e) => text,
            Ok(o) => o
                .replace(
                    text.as_str(),
                    self.get_locale(true).format_out().date_replace(),
                )
                .to_string(),
        }
    }

    /// Format and return an integer string.
    ///
    /// # Arguments
    ///
    /// * `val` - The i32 value to format.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_integeri_out(&self, val: i32) -> String {
        let text = val.to_string();

        match Regex::new(self.get_locale(true).format_out().integer_regex()) {
            Err(_e) => text,
            Ok(o) => o
                .replace(
                    text.as_str(),
                    self.get_locale(true).format_out().integer_replace(),
                )
                .to_string(),
        }
    }

    /// Format and return an integer string.
    ///
    /// # Arguments
    ///
    /// * `val` - The usize value to format.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_integer_out(&self, val: usize) -> String {
        self.format_integeri_out(val as i32)
    }

    /// Format and return a decimal string.
    ///
    /// # Arguments
    ///
    /// * `val` - The decimal value to format.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_decimal_out(&self, val: Decimal) -> String {
        let mut text =
            CoreUtility::util_round(val, crate::MAXIMUM_DISPLAY_DECIMAL_DIGITS).to_string();

        let tokens: Vec<_> = text.split('.').collect();
        if tokens.len() > 1 {
            let mut fract = String::from(tokens[1]);
            fract.truncate(crate::MAXIMUM_DISPLAY_DECIMAL_DIGITS);
            text = format!("{}.{}", tokens[0], fract);
        } else {
            text.push_str(".0");
        }

        match Regex::new(self.get_locale(true).format_out().decimal_regex()) {
            Err(_e) => text,
            Ok(o) => o
                .replace(
                    text.as_str(),
                    self.get_locale(true).format_out().decimal_replace(),
                )
                .to_string(),
        }
    }

    /// Format and return a currency string.
    ///
    /// # Arguments
    ///
    /// * `val` - The decimal value to format.
    /// * `decimal_digits` - The number of decimal digits to round.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn format_currency_out(&self, val: Decimal, decimal_digits: usize) -> String {
        let mut text = CoreUtility::util_round(val, decimal_digits).to_string();

        let tokens: Vec<_> = text.split('.').collect();
        let mut fract = String::from("");
        if tokens.len() > 1 {
            fract = String::from(tokens[1]);
            fract.truncate(decimal_digits);
            text = format!("{}.{}", tokens[0], fract);
        } else {
            text.push('.');
        }

        let mut zeros = decimal_digits - fract.len();
        while zeros > 0 {
            text.push('0');
            zeros -= 1;
        }

        match Regex::new(self.get_locale(true).format_out().currency_regex()) {
            Err(_e) => text,
            Ok(o) => o
                .replace(
                    text.as_str(),
                    self.get_locale(true).format_out().currency_replace(),
                )
                .to_string(),
        }
    }

    /// Get the most relevant locale index.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn get_locale_index(&self, event: bool) -> usize {
        if event && self.list_index_event.get() != usize::MAX {
            return self.list_index_event.get();
        }
        if self.list_index_cashflow.get() != usize::MAX {
            return self.list_index_cashflow.get();
        }

        self.list_index_user.get()
    }

    /// Get the most relevant locale.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn get_locale(&self, event: bool) -> &ElemLocale {
        if event && self.list_index_event.get() != usize::MAX {
            return self.event_locale();
        }
        if self.list_index_cashflow.get() != usize::MAX {
            return self.cashflow_locale();
        }

        self.user_locale()
    }

    /// Get the most relevant locale string.
    ///
    /// # Arguments
    ///
    /// * `event` - Check event level.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn get_locale_str(&self, event: bool) -> &str {
        if event && self.list_index_event.get() != usize::MAX {
            return self.event_locale().locale_str();
        }
        if self.list_index_cashflow.get() != usize::MAX {
            return self.cashflow_locale().locale_str();
        }

        self.user_locale().locale_str()
    }

    /// Get the resource string for the locale.
    ///
    /// # Arguments
    ///
    /// * `key` - The resource key.
    ///
    /// # Return
    ///
    /// * See description.
    #[allow(clippy::manual_unwrap_or)]

    pub fn get_resource(&self, key: &str) -> &str {
        match self.get_locale(true).resources().get(key) {
            None => "",
            Some(o) => o,
        }
    }

    /// Select a user locale parameter.
    ///
    /// # Arguments
    ///
    /// * `locale_str_param` - Locale string to select.

    pub fn select_user_locale(&self, locale_str_param: &str) {
        for (index, loc) in self.list_locale.iter().enumerate() {
            if loc.locale_str() == locale_str_param {
                self.list_index_user.set(index);
                return;
            }
        }

        self.list_index_user.set(usize::MAX);
    }

    /// Select a cashflow locale parameter.
    ///
    /// # Arguments
    ///
    /// * `locale_str_param` - Locale string to select.

    pub fn select_cashflow_locale(&self, locale_str_param: &str) {
        for (index, loc) in self.list_locale.iter().enumerate() {
            if loc.locale_str() == locale_str_param {
                self.list_index_cashflow.set(index);
                return;
            }
        }

        self.list_index_cashflow.set(usize::MAX);
    }

    /// Select an event locale parameter.
    ///
    /// # Arguments
    ///
    /// * `locale_str_param` - Locale string to select.

    pub fn select_event_locale(&self, locale_str_param: &str) {
        for (index, loc) in self.list_locale.iter().enumerate() {
            if loc.locale_str() == locale_str_param {
                self.list_index_event.set(index);
                return;
            }
        }

        self.list_index_event.set(usize::MAX);
    }

    /// Fill leading zeros for a number.
    ///
    /// # Arguments
    ///
    /// * `val` - The number to zero fill.
    /// * `size` - The number of digits.
    ///
    /// # Return
    ///
    /// * See description.

    pub fn zerofill(&self, val: &str, size: usize) -> String {
        let mut text = String::from("");
        let mut len = (size as i32) - (val.len() as i32);
        while len > 0 {
            text.push('0');
            len -= 1;
        }

        format!("{}{}", text, val)
    }
}