Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
compliance.rs

1use super::*;
2
3/// Internal verdict from evaluating a single compliance rule.
4struct RuleVerdict {
5    passed: bool,
6    flagged: bool,
7    message: String,
8    recommendation: String,
9}
10
11/// Compliance monitor
12pub struct ComplianceMonitor {
13    compliance_rules: HashMap<String, ComplianceRule>,
14    surveillance_engine: SurveillanceEngine,
15    reporting_engine: ReportingEngine,
16}
17
18/// Surveillance engine
19pub struct SurveillanceEngine {
20    surveillance_rules: HashMap<String, SurveillanceRule>,
21    anomaly_detector: AnomalyDetector,
22    alert_manager: AlertManager,
23}
24
25/// Surveillance rules
26#[derive(Debug, Clone)]
27pub struct SurveillanceRule {
28    pub rule_id: String,
29    pub rule_name: String,
30    pub rule_type: SurveillanceRuleType,
31    pub conditions: Vec<SurveillanceCondition>,
32    pub actions: Vec<SurveillanceAction>,
33}
34
35/// Surveillance rule types
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub enum SurveillanceRuleType {
38    MarketManipulation,
39    InsiderTrading,
40    FrontRunning,
41    BestExecution,
42    TradeReporting,
43}
44
45/// Surveillance conditions
46#[derive(Debug, Clone)]
47pub struct SurveillanceCondition {
48    pub condition_id: String,
49    pub field: String,
50    pub operator: ComparisonOperator,
51    pub value: SurveillanceValue,
52}
53
54/// Surveillance values
55#[derive(Debug, Clone)]
56pub enum SurveillanceValue {
57    String(String),
58    Number(f64),
59    Boolean(bool),
60}
61
62/// Surveillance actions
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
64pub enum SurveillanceAction {
65    Alert,
66    Block,
67    Escalate,
68    Report,
69}
70
71/// Anomaly detector
72pub struct AnomalyDetector {
73    detection_algorithms: HashMap<String, DetectionAlgorithm>,
74    anomaly_patterns: HashMap<String, AnomalyPattern>,
75}
76
77/// Detection algorithms
78#[derive(Debug, Clone)]
79pub struct DetectionAlgorithm {
80    pub algorithm_id: String,
81    pub algorithm_type: DetectionAlgorithmType,
82    pub parameters: DetectionAlgorithmParameters,
83}
84
85/// Detection algorithm types
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87pub enum DetectionAlgorithmType {
88    Statistical,
89    MachineLearning,
90    RuleBased,
91    Hybrid,
92}
93
94/// Detection algorithm parameters
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct DetectionAlgorithmParameters {
97    pub confidence_threshold: f64,
98    pub sensitivity: f64,
99    pub lookback_period: u32,
100}
101
102/// Anomaly patterns
103#[derive(Debug, Clone)]
104pub struct AnomalyPattern {
105    pub pattern_id: String,
106    pub pattern_name: String,
107    pub pattern_type: AnomalyPatternType,
108    pub characteristics: Vec<String>,
109}
110
111/// Anomaly pattern types
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
113pub enum AnomalyPatternType {
114    Price,
115    Volume,
116    Timing,
117    Sequence,
118}
119
120/// Alert manager
121pub struct AlertManager {
122    alerts: HashMap<String, Alert>,
123    alert_escalation: AlertEscalation,
124    notification_system: NotificationSystem,
125}
126
127/// Alerts
128#[derive(Debug, Clone)]
129pub struct Alert {
130    pub alert_id: String,
131    pub alert_type: AlertType,
132    pub severity: AlertSeverity,
133    pub description: String,
134    pub source: String,
135    pub timestamp: u64,
136    pub status: AlertStatus,
137}
138
139/// Alert types
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum AlertType {
142    Compliance,
143    Risk,
144    Operational,
145    Security,
146}
147
148/// Alert severity
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub enum AlertSeverity {
151    Low,
152    Medium,
153    High,
154    Critical,
155}
156
157/// Alert status
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub enum AlertStatus {
160    New,
161    Acknowledged,
162    Investigating,
163    Resolved,
164    Closed,
165}
166
167/// Alert escalation
168pub struct AlertEscalation {
169    escalation_rules: HashMap<String, EscalationRule>,
170    escalation_history: HashMap<String, EscalationHistory>,
171}
172
173/// Escalation rules
174#[derive(Debug, Clone)]
175pub struct EscalationRule {
176    pub rule_id: String,
177    pub conditions: Vec<EscalationCondition>,
178    pub actions: Vec<EscalationAction>,
179}
180
181/// Escalation conditions
182#[derive(Debug, Clone)]
183pub struct EscalationCondition {
184    pub condition_id: String,
185    pub field: String,
186    pub operator: ComparisonOperator,
187    pub value: EscalationValue,
188}
189
190/// Escalation values
191#[derive(Debug, Clone)]
192pub enum EscalationValue {
193    String(String),
194    Number(f64),
195    Boolean(bool),
196}
197
198/// Escalation actions
199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
200pub enum EscalationAction {
201    Notify,
202    Escalate,
203    Block,
204    Report,
205}
206
207/// Escalation history
208#[derive(Debug, Clone)]
209pub struct EscalationHistory {
210    pub history_id: String,
211    pub alert_id: String,
212    pub escalation_steps: Vec<EscalationStep>,
213}
214
215/// Escalation steps
216#[derive(Debug, Clone)]
217pub struct EscalationStep {
218    pub step_id: String,
219    pub action: EscalationAction,
220    pub timestamp: u64,
221    pub performed_by: String,
222}
223
224/// Notification system
225pub struct NotificationSystem {
226    notification_channels: HashMap<String, NotificationChannel>,
227    notification_templates: HashMap<String, NotificationTemplate>,
228}
229
230/// Notification channels
231#[derive(Debug, Clone)]
232pub struct NotificationChannel {
233    pub channel_id: String,
234    pub channel_type: NotificationChannelType,
235    pub configuration: ChannelConfiguration,
236}
237
238/// Notification channel types
239#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
240pub enum NotificationChannelType {
241    Email,
242    SMS,
243    Slack,
244    Webhook,
245    InApp,
246}
247
248/// Channel configuration
249#[derive(Debug, Clone)]
250pub struct ChannelConfiguration {
251    pub endpoint: String,
252    pub authentication: AuthenticationMethod,
253    pub format: NotificationFormat,
254}
255
256/// Notification formats
257#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
258pub enum NotificationFormat {
259    Text,
260    HTML,
261    JSON,
262    Custom,
263}
264
265/// Notification templates
266#[derive(Debug, Clone)]
267pub struct NotificationTemplate {
268    pub template_id: String,
269    pub template_name: String,
270    pub template_type: NotificationTemplateType,
271    pub content: String,
272}
273
274/// Notification template types
275#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
276pub enum NotificationTemplateType {
277    Alert,
278    Report,
279    Summary,
280    Custom,
281}
282
283impl ComplianceMonitor {
284    /// Construct a `ComplianceMonitor` with default field values.
285    pub fn new() -> Self {
286        Self {
287            compliance_rules: HashMap::new(),
288            surveillance_engine: SurveillanceEngine::new(),
289            reporting_engine: ReportingEngine::new(),
290        }
291    }
292
293    /// Initialize `ComplianceMonitor`; `Ok` when ready.
294    pub fn initialize(&mut self) -> Result<(), FinancialError> {
295        self.surveillance_engine.initialize()?;
296        self.reporting_engine.initialize()?;
297        Ok(())
298    }
299
300    /// Register a compliance rule. Rules are keyed by `rule_id`; registering
301    /// with a duplicate id replaces the prior rule.
302    pub fn add_rule(&mut self, rule: ComplianceRule) {
303        self.compliance_rules.insert(rule.rule_id.clone(), rule);
304    }
305
306    /// Number of registered compliance rules.
307    pub fn rule_count(&self) -> usize {
308        self.compliance_rules.len()
309    }
310
311    /// Evaluate every registered compliance rule against the portfolio.
312    ///
313    /// Returns a `ComplianceResult` with:
314    /// - `status: Compliant` when every rule passes (or no rules are registered
315    ///   *and* the portfolio has no positions — an empty portfolio with no
316    ///   rules is trivially compliant; a non-empty portfolio with no rules is
317    ///   `Flagged` because compliance was never asserted).
318    /// - `status: NonCompliant` when one or more rules fail.
319    /// - `status: Flagged` when a rule neither clearly passes nor fails but
320    ///   warrants review (e.g. a `Custom` rule with no check).
321    /// - `risk_score`: fraction of rules that failed (0.0 = all pass, 1.0 = all fail).
322    /// - `violations`: human-readable descriptions of each failed rule.
323    /// - `recommendations`: suggested remediation per failed rule.
324    /// - `audit_entries`: one entry per evaluated rule.
325    pub fn check_compliance(
326        &mut self,
327        portfolio: &Portfolio,
328    ) -> Result<ComplianceResult, FinancialError> {
329        let mut violations = Vec::new();
330        let mut recommendations = Vec::new();
331        let mut audit_entries = Vec::new();
332        let mut failed = 0usize;
333        let mut flagged = 0usize;
334        let now = portfolio.last_updated;
335
336        // Special case: no rules registered.
337        if self.compliance_rules.is_empty() {
338            if portfolio.assets.is_empty() {
339                // Empty portfolio, no rules → trivially compliant.
340                return Ok(ComplianceResult {
341                    result_id: format!("compliance_{}_{}", portfolio.portfolio_id, now),
342                    portfolio_id: portfolio.portfolio_id.clone(),
343                    status: ComplianceStatus::Compliant,
344                    risk_score: 0.0,
345                    violations: Vec::new(),
346                    recommendations: Vec::new(),
347                    audit_entries: Vec::new(),
348                });
349            }
350            // Non-empty portfolio, no rules → we cannot assert compliance.
351            return Ok(ComplianceResult {
352                result_id: format!("compliance_{}_{}", portfolio.portfolio_id, now),
353                portfolio_id: portfolio.portfolio_id.clone(),
354                status: ComplianceStatus::Flagged,
355                risk_score: 1.0,
356                violations: vec![
357                    "No compliance rules registered — cannot assert compliance for a non-empty portfolio."
358                        .to_string(),
359                ],
360                recommendations: vec![
361                    "Register compliance rules (position limits, KYC/AML, margin, trading restrictions) before asserting compliance."
362                        .to_string(),
363                ],
364                audit_entries: Vec::new(),
365            });
366        }
367
368        let total_rules = self.compliance_rules.len();
369
370        // Evaluate each rule. Sort by rule_id for deterministic ordering.
371        let mut rule_ids: Vec<&String> = self.compliance_rules.keys().collect();
372        rule_ids.sort();
373
374        for rule_id in rule_ids {
375            let rule = &self.compliance_rules[rule_id];
376            let verdict = Self::evaluate_rule(rule, portfolio);
377
378            audit_entries.push(AuditEntry {
379                entry_id: format!("audit_{}_{}", rule.rule_id, now),
380                timestamp: now,
381                user_id: String::new(),
382                portfolio_id: portfolio.portfolio_id.clone(),
383                action: PortfolioAction::ComplianceCheck,
384                details: format!(
385                    "Rule '{}' ({}): {} — {}",
386                    rule.rule_id,
387                    rule.rule_type_as_str(),
388                    if verdict.passed { "PASS" } else { "FAIL" },
389                    verdict.message
390                ),
391                ip_address: String::new(),
392            });
393
394            if !verdict.passed {
395                failed += 1;
396                violations.push(format!("{}: {}", rule.rule_id, verdict.message));
397                recommendations.push(verdict.recommendation);
398            } else if verdict.flagged {
399                flagged += 1;
400            }
401        }
402
403        let risk_score = failed as f64 / total_rules as f64;
404
405        let status = if failed > 0 {
406            ComplianceStatus::NonCompliant
407        } else if flagged > 0 {
408            ComplianceStatus::Flagged
409        } else {
410            ComplianceStatus::Compliant
411        };
412
413        Ok(ComplianceResult {
414            result_id: format!("compliance_{}_{}", portfolio.portfolio_id, now),
415            portfolio_id: portfolio.portfolio_id.clone(),
416            status,
417            risk_score,
418            violations,
419            recommendations,
420            audit_entries,
421        })
422    }
423
424    /// Evaluate a single compliance rule against a portfolio.
425    fn evaluate_rule(rule: &ComplianceRule, portfolio: &Portfolio) -> RuleVerdict {
426        match rule.rule_type {
427            ComplianceRuleType::PositionLimit => {
428                let max_position = rule.parameters.get("max_position").copied().unwrap_or(0.0);
429                if max_position <= 0.0 {
430                    return RuleVerdict {
431                        passed: false,
432                        flagged: false,
433                        message: "PositionLimit rule has no max_position parameter".to_string(),
434                        recommendation: "Set the 'max_position' parameter to a positive value."
435                            .to_string(),
436                    };
437                }
438                // Check each asset's market value against the limit.
439                for asset in &portfolio.assets {
440                    if asset.market_value > max_position {
441                        return RuleVerdict {
442                            passed: false,
443                            flagged: false,
444                            message: format!(
445                                "Asset {} market value {:.2} exceeds max_position {:.2}",
446                                asset.symbol, asset.market_value, max_position
447                            ),
448                            recommendation: format!(
449                                "Reduce position in {} to at most {:.2}",
450                                asset.symbol, max_position
451                            ),
452                        };
453                    }
454                }
455                RuleVerdict {
456                    passed: true,
457                    flagged: false,
458                    message: "All positions within limit".to_string(),
459                    recommendation: String::new(),
460                }
461            }
462            ComplianceRuleType::KYC => {
463                let kyc_required = rule.parameters.get("kyc_required").copied().unwrap_or(1.0);
464                if kyc_required >= 1.0 {
465                    // In a real system, this would check the portfolio owner's KYC status
466                    // from an identity registry. Here we check the risk_profile as a proxy:
467                    // an Unverified profile fails KYC.
468                    let verified = matches!(
469                        portfolio.risk_profile.risk_tolerance,
470                        RiskTolerance::Conservative
471                            | RiskTolerance::Moderate
472                            | RiskTolerance::Aggressive
473                            | RiskTolerance::VeryAggressive
474                    ) && !portfolio.owner_id.is_empty();
475                    if !verified {
476                        return RuleVerdict {
477                            passed: false,
478                            flagged: false,
479                            message: "KYC verification required but owner identity not verified"
480                                .to_string(),
481                            recommendation: "Complete KYC verification before trading.".to_string(),
482                        };
483                    }
484                }
485                RuleVerdict {
486                    passed: true,
487                    flagged: false,
488                    message: "KYC verified".to_string(),
489                    recommendation: String::new(),
490                }
491            }
492            ComplianceRuleType::AML => {
493                let aml_required = rule.parameters.get("kyc_required").copied().unwrap_or(1.0);
494                if aml_required >= 1.0 && portfolio.owner_id.is_empty() {
495                    return RuleVerdict {
496                        passed: false,
497                        flagged: false,
498                        message: "AML clearance required but no owner identified".to_string(),
499                        recommendation: "Provide owner identification for AML screening."
500                            .to_string(),
501                    };
502                }
503                RuleVerdict {
504                    passed: true,
505                    flagged: false,
506                    message: "AML cleared".to_string(),
507                    recommendation: String::new(),
508                }
509            }
510            ComplianceRuleType::MarginRequirement => {
511                let margin_pct = rule.parameters.get("margin_pct").copied().unwrap_or(0.0);
512                if margin_pct <= 0.0 {
513                    return RuleVerdict {
514                        passed: false,
515                        flagged: false,
516                        message: "MarginRequirement rule has no margin_pct parameter".to_string(),
517                        recommendation: "Set the 'margin_pct' parameter to a positive value."
518                            .to_string(),
519                    };
520                }
521                let required_margin = portfolio.total_value * margin_pct / 100.0;
522                if portfolio.cash_balance < required_margin {
523                    return RuleVerdict {
524                        passed: false,
525                        flagged: false,
526                        message: format!(
527                            "Cash balance {:.2} below required margin {:.2} ({:.1}% of {:.2})",
528                            portfolio.cash_balance,
529                            required_margin,
530                            margin_pct,
531                            portfolio.total_value
532                        ),
533                        recommendation: format!(
534                            "Increase cash balance to at least {:.2} to meet margin requirement.",
535                            required_margin
536                        ),
537                    };
538                }
539                RuleVerdict {
540                    passed: true,
541                    flagged: false,
542                    message: format!(
543                        "Margin satisfied: {:.2} >= {:.2}",
544                        portfolio.cash_balance, required_margin
545                    ),
546                    recommendation: String::new(),
547                }
548            }
549            ComplianceRuleType::TradingRestriction => {
550                let restricted = rule
551                    .string_parameters
552                    .get("restricted_assets")
553                    .map(|s| s.as_str())
554                    .unwrap_or("");
555                if restricted.is_empty() {
556                    return RuleVerdict {
557                        passed: true,
558                        flagged: true,
559                        message: "TradingRestriction rule has no restricted_assets list — no assets restricted".to_string(),
560                        recommendation: "Populate 'restricted_assets' if trading restrictions are intended.".to_string(),
561                    };
562                }
563                let restricted_set: Vec<&str> = restricted.split(',').map(|s| s.trim()).collect();
564                for asset in &portfolio.assets {
565                    if restricted_set.contains(&asset.symbol.as_str()) {
566                        return RuleVerdict {
567                            passed: false,
568                            flagged: false,
569                            message: format!("Asset {} is on the restricted list", asset.symbol),
570                            recommendation: format!("Divest restricted asset {}.", asset.symbol),
571                        };
572                    }
573                }
574                RuleVerdict {
575                    passed: true,
576                    flagged: false,
577                    message: "No restricted assets held".to_string(),
578                    recommendation: String::new(),
579                }
580            }
581            ComplianceRuleType::Custom => {
582                // Custom rules always pass by default — they have no built-in check.
583                RuleVerdict {
584                    passed: true,
585                    flagged: true,
586                    message: "Custom rule — no built-in check, passes by default".to_string(),
587                    recommendation: "Implement a custom evaluator if enforcement is needed."
588                        .to_string(),
589                }
590            }
591        }
592    }
593}
594
595impl SurveillanceEngine {
596    /// Construct a `SurveillanceEngine` with default field values.
597    pub fn new() -> Self {
598        Self {
599            surveillance_rules: HashMap::new(),
600            anomaly_detector: AnomalyDetector::new(),
601            alert_manager: AlertManager::new(),
602        }
603    }
604
605    /// Initialize `SurveillanceEngine`; `Ok` when ready.
606    pub fn initialize(&mut self) -> Result<(), FinancialError> {
607        self.anomaly_detector.initialize()?;
608        self.alert_manager.initialize()?;
609        Ok(())
610    }
611
612    /// Add `surveillance_rule` to the `SurveillanceEngine`.
613    pub fn add_surveillance_rule(&mut self, rule: SurveillanceRule) {
614        self.surveillance_rules.insert(rule.rule_id.clone(), rule);
615    }
616
617    /// Look up `surveillance_rule` by id; `None`/`Err` when absent.
618    pub fn get_surveillance_rule(&self, rule_id: &str) -> Option<&SurveillanceRule> {
619        self.surveillance_rules.get(rule_id)
620    }
621
622    /// Ids of every registered `surveillance_rule`.
623    pub fn list_surveillance_rules(&self) -> Vec<String> {
624        self.surveillance_rules.keys().cloned().collect()
625    }
626}
627
628impl AnomalyDetector {
629    /// Construct a `AnomalyDetector` with default field values.
630    pub fn new() -> Self {
631        Self {
632            detection_algorithms: HashMap::new(),
633            anomaly_patterns: HashMap::new(),
634        }
635    }
636
637    /// Initialize `AnomalyDetector`; `Ok` when ready.
638    pub fn initialize(&mut self) -> Result<(), FinancialError> {
639        Ok(())
640    }
641
642    /// Add `detection_algorithm` to the `AnomalyDetector`.
643    pub fn add_detection_algorithm(&mut self, algorithm: DetectionAlgorithm) {
644        self.detection_algorithms
645            .insert(algorithm.algorithm_id.clone(), algorithm);
646    }
647
648    /// Look up `detection_algorithm` by id; `None`/`Err` when absent.
649    pub fn get_detection_algorithm(&self, algorithm_id: &str) -> Option<&DetectionAlgorithm> {
650        self.detection_algorithms.get(algorithm_id)
651    }
652
653    /// Ids of every registered `detection_algorithm`.
654    pub fn list_detection_algorithms(&self) -> Vec<String> {
655        self.detection_algorithms.keys().cloned().collect()
656    }
657
658    /// Add `anomaly_pattern` to the `AnomalyDetector`.
659    pub fn add_anomaly_pattern(&mut self, pattern: AnomalyPattern) {
660        self.anomaly_patterns
661            .insert(pattern.pattern_id.clone(), pattern);
662    }
663
664    /// Look up `anomaly_pattern` by id; `None`/`Err` when absent.
665    pub fn get_anomaly_pattern(&self, pattern_id: &str) -> Option<&AnomalyPattern> {
666        self.anomaly_patterns.get(pattern_id)
667    }
668
669    /// Ids of every registered `anomaly_pattern`.
670    pub fn list_anomaly_patterns(&self) -> Vec<String> {
671        self.anomaly_patterns.keys().cloned().collect()
672    }
673}
674
675impl AlertManager {
676    /// Construct a `AlertManager` with default field values.
677    pub fn new() -> Self {
678        Self {
679            alerts: HashMap::new(),
680            alert_escalation: AlertEscalation::new(),
681            notification_system: NotificationSystem::new(),
682        }
683    }
684
685    /// Initialize `AlertManager`; `Ok` when ready.
686    pub fn initialize(&mut self) -> Result<(), FinancialError> {
687        Ok(())
688    }
689
690    /// Add `alert` to the `AlertManager`.
691    pub fn add_alert(&mut self, alert: Alert) {
692        self.alerts.insert(alert.alert_id.clone(), alert);
693    }
694
695    /// Look up `alert` by id; `None`/`Err` when absent.
696    pub fn get_alert(&self, alert_id: &str) -> Option<&Alert> {
697        self.alerts.get(alert_id)
698    }
699
700    /// Ids of every registered `alert`.
701    pub fn list_alerts(&self) -> Vec<String> {
702        self.alerts.keys().cloned().collect()
703    }
704
705    /// The `alert_escalation` component.
706    pub fn alert_escalation(&self) -> &AlertEscalation {
707        &self.alert_escalation
708    }
709
710    /// The `alert_escalation` component (mutable).
711    pub fn alert_escalation_mut(&mut self) -> &mut AlertEscalation {
712        &mut self.alert_escalation
713    }
714
715    /// The `notification_system` component.
716    pub fn notification_system(&self) -> &NotificationSystem {
717        &self.notification_system
718    }
719
720    /// The `notification_system` component (mutable).
721    pub fn notification_system_mut(&mut self) -> &mut NotificationSystem {
722        &mut self.notification_system
723    }
724}
725
726impl AlertEscalation {
727    /// Construct a `AlertEscalation` with default field values.
728    pub fn new() -> Self {
729        Self {
730            escalation_rules: HashMap::new(),
731            escalation_history: HashMap::new(),
732        }
733    }
734
735    /// Add `escalation_rule` to the `AlertEscalation`.
736    pub fn add_escalation_rule(&mut self, rule: EscalationRule) {
737        self.escalation_rules.insert(rule.rule_id.clone(), rule);
738    }
739
740    /// Look up `escalation_rule` by id; `None`/`Err` when absent.
741    pub fn get_escalation_rule(&self, rule_id: &str) -> Option<&EscalationRule> {
742        self.escalation_rules.get(rule_id)
743    }
744
745    /// Ids of every registered `escalation_rule`.
746    pub fn list_escalation_rules(&self) -> Vec<String> {
747        self.escalation_rules.keys().cloned().collect()
748    }
749
750    /// Add `escalation_history` to the `AlertEscalation`.
751    pub fn add_escalation_history(&mut self, history: EscalationHistory) {
752        self.escalation_history
753            .insert(history.history_id.clone(), history);
754    }
755
756    /// Look up `escalation_history` by id; `None`/`Err` when absent.
757    pub fn get_escalation_history(&self, history_id: &str) -> Option<&EscalationHistory> {
758        self.escalation_history.get(history_id)
759    }
760
761    /// Ids of every registered `escalation_history`.
762    pub fn list_escalation_history(&self) -> Vec<String> {
763        self.escalation_history.keys().cloned().collect()
764    }
765}
766
767impl NotificationSystem {
768    /// Construct a `NotificationSystem` with default field values.
769    pub fn new() -> Self {
770        Self {
771            notification_channels: HashMap::new(),
772            notification_templates: HashMap::new(),
773        }
774    }
775
776    /// Add `channel` to the `NotificationSystem`.
777    pub fn add_channel(&mut self, channel: NotificationChannel) {
778        self.notification_channels
779            .insert(channel.channel_id.clone(), channel);
780    }
781
782    /// Look up `channel` by id; `None`/`Err` when absent.
783    pub fn get_channel(&self, channel_id: &str) -> Option<&NotificationChannel> {
784        self.notification_channels.get(channel_id)
785    }
786
787    /// Ids of every registered `channel`.
788    pub fn list_channels(&self) -> Vec<String> {
789        self.notification_channels.keys().cloned().collect()
790    }
791
792    /// Add `template` to the `NotificationSystem`.
793    pub fn add_template(&mut self, template: NotificationTemplate) {
794        self.notification_templates
795            .insert(template.template_id.clone(), template);
796    }
797
798    /// Look up `template` by id; `None`/`Err` when absent.
799    pub fn get_template(&self, template_id: &str) -> Option<&NotificationTemplate> {
800        self.notification_templates.get(template_id)
801    }
802
803    /// Ids of every registered `template`.
804    pub fn list_templates(&self) -> Vec<String> {
805        self.notification_templates.keys().cloned().collect()
806    }
807}