Skip to main content

qualia_core_db/specialized_libs/medical_computing/
compliance.rs

1use super::*;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4
5/// Medical compliance monitor
6pub struct MedicalComplianceMonitor {
7    hipaa_compliance: HIPAACompliance,
8    gdpr_compliance: GDPRCompliance,
9    clinical_standards: ClinicalStandards,
10    audit_system: AuditSystem,
11}
12
13/// HIPAA compliance
14pub struct HIPAACompliance {
15    privacy_rules: HashMap<String, PrivacyRule>,
16    security_rules: HashMap<String, SecurityRule>,
17    breach_notification: BreachNotification,
18}
19
20/// Privacy rules
21#[derive(Debug, Clone)]
22pub struct PrivacyRule {
23    pub rule_id: String,
24    pub rule_name: String,
25    pub rule_type: PrivacyRuleType,
26    pub requirements: Vec<HIPAARequirement>,
27}
28
29/// Privacy rule types
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31pub enum PrivacyRuleType {
32    Use,
33    Disclosure,
34    Access,
35    Amendment,
36}
37
38/// HIPAA requirements
39#[derive(Debug, Clone)]
40pub struct HIPAARequirement {
41    pub requirement_id: String,
42    pub requirement_name: String,
43    pub requirement_text: String,
44    pub mandatory: bool,
45}
46
47/// Security rules
48#[derive(Debug, Clone)]
49pub struct SecurityRule {
50    pub rule_id: String,
51    pub rule_name: String,
52    pub rule_type: SecurityRuleType,
53    pub controls: Vec<SecurityControl>,
54}
55
56/// Security rule types
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58pub enum SecurityRuleType {
59    Administrative,
60    Physical,
61    Technical,
62}
63
64/// Security controls
65#[derive(Debug, Clone)]
66pub struct SecurityControl {
67    pub control_id: String,
68    pub control_name: String,
69    pub control_type: SecurityControlType,
70}
71
72/// Security control types
73#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
74pub enum SecurityControlType {
75    Preventive,
76    Detective,
77    Corrective,
78}
79
80/// Breach notification
81pub struct BreachNotification {
82    notification_rules: HashMap<String, NotificationRule>,
83    notification_templates: HashMap<String, NotificationTemplate>,
84}
85
86/// Notification rules
87#[derive(Debug, Clone)]
88pub struct NotificationRule {
89    pub rule_id: String,
90    pub rule_name: String,
91    pub trigger_conditions: Vec<TriggerCondition>,
92    pub notification_requirements: Vec<NotificationRequirement>,
93}
94
95/// Notification requirements
96#[derive(Debug, Clone)]
97pub struct NotificationRequirement {
98    pub requirement_id: String,
99    pub requirement_name: String,
100    pub requirement_text: String,
101    pub deadline: u32,
102}
103
104/// Notification templates
105#[derive(Debug, Clone)]
106pub struct NotificationTemplate {
107    pub template_id: String,
108    pub template_name: String,
109    pub template_content: String,
110    pub required_fields: Vec<String>,
111}
112
113/// GDPR compliance
114pub struct GDPRCompliance {
115    data_protection_principles: HashMap<String, DataProtectionPrinciple>,
116    data_subject_rights: HashMap<String, DataSubjectRight>,
117    data_processing_agreements: HashMap<String, DataProcessingAgreement>,
118}
119
120/// Data protection principles
121#[derive(Debug, Clone)]
122pub struct DataProtectionPrinciple {
123    pub principle_id: String,
124    pub principle_name: String,
125    pub principle_description: String,
126    pub implementation_guidance: String,
127}
128
129/// Data subject rights
130#[derive(Debug, Clone)]
131pub struct DataSubjectRight {
132    pub right_id: String,
133    pub right_name: String,
134    pub right_description: String,
135    pub implementation_procedures: Vec<ImplementationProcedure>,
136}
137
138/// Implementation procedures
139#[derive(Debug, Clone)]
140pub struct ImplementationProcedure {
141    pub procedure_id: String,
142    pub procedure_name: String,
143    pub procedure_steps: Vec<ProcedureStep>,
144}
145
146/// Procedure steps
147#[derive(Debug, Clone)]
148pub struct ProcedureStep {
149    pub step_id: String,
150    pub step_description: String,
151    pub step_responsible_party: String,
152    pub step_deadline: u32,
153}
154
155/// Data processing agreements
156#[derive(Debug, Clone)]
157pub struct DataProcessingAgreement {
158    pub agreement_id: String,
159    pub agreement_name: String,
160    pub agreement_terms: Vec<AgreementTerm>,
161}
162
163/// Agreement terms
164#[derive(Debug, Clone)]
165pub struct AgreementTerm {
166    pub term_id: String,
167    pub term_name: String,
168    pub term_description: String,
169    pub term_type: AgreementTermType,
170}
171
172/// Agreement term types
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174pub enum AgreementTermType {
175    Scope,
176    Duration,
177    Security,
178    Liability,
179}
180
181/// Clinical standards
182pub struct ClinicalStandards {
183    clinical_guidelines: HashMap<String, ClinicalGuideline>,
184    quality_metrics: HashMap<String, QualityMetric>,
185    best_practices: HashMap<String, BestPractice>,
186}
187
188/// Clinical guidelines
189#[derive(Debug, Clone)]
190pub struct ClinicalGuideline {
191    pub guideline_id: String,
192    pub guideline_name: String,
193    pub guideline_type: GuidelineType,
194    pub recommendations: Vec<GuidelineRecommendation>,
195}
196
197/// Guideline recommendations
198#[derive(Debug, Clone)]
199pub struct GuidelineRecommendation {
200    pub recommendation_id: String,
201    pub recommendation_text: String,
202    pub evidence_level: EvidenceLevel,
203    pub grade: RecommendationGrade,
204}
205
206/// Recommendation grades
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
208pub enum RecommendationGrade {
209    Strong,
210    Moderate,
211    Weak,
212    ExpertOpinion,
213}
214
215/// Best practices
216#[derive(Debug, Clone)]
217pub struct BestPractice {
218    pub practice_id: String,
219    pub practice_name: String,
220    pub practice_description: String,
221    pub implementation_steps: Vec<ImplementationStep>,
222}
223
224/// Implementation steps
225#[derive(Debug, Clone)]
226pub struct ImplementationStep {
227    pub step_id: String,
228    pub step_description: String,
229    pub step_resources: Vec<String>,
230}
231
232/// Audit system
233pub struct AuditSystem {
234    audit_trails: HashMap<String, AuditTrail>,
235    audit_reports: HashMap<String, AuditReport>,
236    compliance_monitoring: ComplianceMonitoring,
237}
238
239/// Audit trails
240#[derive(Debug, Clone)]
241pub struct AuditTrail {
242    pub trail_id: String,
243    pub trail_type: TrailType,
244    pub events: Vec<AuditEvent>,
245}
246
247/// Trail types
248#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
249pub enum TrailType {
250    Access,
251    Modification,
252    Deletion,
253    System,
254}
255
256/// Audit events
257#[derive(Debug, Clone)]
258pub struct AuditEvent {
259    pub event_id: String,
260    pub timestamp: u64,
261    pub user_id: String,
262    pub action: String,
263    pub resource: String,
264    pub outcome: String,
265}
266
267/// Audit reports
268#[derive(Debug, Clone)]
269pub struct AuditReport {
270    pub report_id: String,
271    pub report_name: String,
272    pub report_type: ReportType,
273    pub findings: Vec<AuditFinding>,
274}
275
276/// Report types
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278pub enum ReportType {
279    Compliance,
280    Security,
281    Performance,
282    Incident,
283}
284
285/// Audit findings
286#[derive(Debug, Clone)]
287pub struct AuditFinding {
288    pub finding_id: String,
289    pub finding_type: FindingType,
290    pub finding_description: String,
291    pub severity: FindingSeverity,
292    pub recommendations: Vec<String>,
293}
294
295/// Finding types
296#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
297pub enum FindingType {
298    Violation,
299    Weakness,
300    Gap,
301    Observation,
302}
303
304/// Finding severity
305#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
306pub enum FindingSeverity {
307    Low,
308    Medium,
309    High,
310    Critical,
311}
312
313/// Compliance monitoring
314pub struct ComplianceMonitoring {
315    monitoring_rules: HashMap<String, MonitoringRule>,
316    compliance_metrics: HashMap<String, ComplianceMetric>,
317}
318
319/// Monitoring rules
320#[derive(Debug, Clone)]
321pub struct MonitoringRule {
322    pub rule_id: String,
323    pub rule_name: String,
324    pub rule_type: MonitoringRuleType,
325    pub check_frequency: u32,
326}
327
328/// Monitoring rule types
329#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
330pub enum MonitoringRuleType {
331    Automated,
332    Manual,
333    Hybrid,
334}
335
336/// Compliance metrics
337#[derive(Debug, Clone)]
338pub struct ComplianceMetric {
339    pub metric_id: String,
340    pub metric_name: String,
341    pub metric_value: f64,
342    pub metric_target: f64,
343}
344
345impl MedicalComplianceMonitor {
346    /// Construct a `MedicalComplianceMonitor` with default field values.
347    pub fn new() -> Self {
348        Self {
349            hipaa_compliance: HIPAACompliance::new(),
350            gdpr_compliance: GDPRCompliance::new(),
351            clinical_standards: ClinicalStandards::new(),
352            audit_system: AuditSystem::new(),
353        }
354    }
355
356    /// Initialize every sub-component (HIPAA, GDPR, clinical standards, audit); `Ok` when all are ready.
357    pub fn initialize(&mut self) -> Result<(), MedicalError> {
358        self.hipaa_compliance.initialize()?;
359        self.gdpr_compliance.initialize()?;
360        self.clinical_standards.initialize()?;
361        self.audit_system.initialize()?;
362        Ok(())
363    }
364
365    /// Evaluate compliance for the specified `compliance_type` across registered rules,
366    /// security controls, data protection agreements, and quality metrics.
367    /// Returns `compliance_score: None` honestly if no rules are registered to evaluate.
368    pub fn check_compliance(
369        &mut self,
370        compliance_type: ComplianceType,
371    ) -> Result<ComplianceReport, MedicalError> {
372        let mut violations = Vec::new();
373        let mut recommendations = Vec::new();
374        let mut checks_evaluated = 0usize;
375        let mut checks_passed = 0usize;
376
377        match compliance_type {
378            ComplianceType::HIPAA => {
379                // Evaluate Privacy Rules
380                for (id, rule) in &self.hipaa_compliance.privacy_rules {
381                    checks_evaluated += 1;
382                    let has_empty_req = rule
383                        .requirements
384                        .iter()
385                        .any(|r| r.mandatory && r.requirement_text.trim().is_empty());
386                    if has_empty_req {
387                        violations.push(format!(
388                            "HIPAA Privacy: Rule '{id}' has empty mandatory requirements"
389                        ));
390                        recommendations.push(format!(
391                            "Define mandatory requirement text for privacy rule '{id}'"
392                        ));
393                    } else {
394                        checks_passed += 1;
395                    }
396                }
397                // Evaluate Security Rules
398                for (id, rule) in &self.hipaa_compliance.security_rules {
399                    checks_evaluated += 1;
400                    if rule.controls.is_empty() {
401                        violations.push(format!(
402                            "HIPAA Security: Rule '{id}' has no associated security controls"
403                        ));
404                        recommendations.push(format!(
405                            "Assign administrative/technical controls to rule '{id}'"
406                        ));
407                    } else {
408                        checks_passed += 1;
409                    }
410                }
411                // Check Breach Notification rules
412                for (id, rule) in &self.hipaa_compliance.breach_notification.notification_rules {
413                    checks_evaluated += 1;
414                    if rule.trigger_conditions.is_empty() {
415                        violations.push(format!(
416                            "HIPAA Breach Notification: Rule '{id}' has no trigger conditions"
417                        ));
418                    } else {
419                        checks_passed += 1;
420                    }
421                }
422            }
423            ComplianceType::GDPR => {
424                for (id, dpa) in &self.gdpr_compliance.data_processing_agreements {
425                    checks_evaluated += 1;
426                    if dpa.agreement_terms.is_empty() {
427                        violations.push(format!("GDPR DPA '{id}' lacks valid processing terms"));
428                        recommendations.push(format!("Specify explicit data processing terms for DPA '{id}'"));
429                    } else {
430                        checks_passed += 1;
431                    }
432                }
433                for (id, right) in &self.gdpr_compliance.data_subject_rights {
434                    checks_evaluated += 1;
435                    if right.implementation_procedures.is_empty() {
436                        violations.push(format!("GDPR data subject right '{id}' lacks implementation procedures"));
437                    } else {
438                        checks_passed += 1;
439                    }
440                }
441            }
442            ComplianceType::Clinical => {
443                for (id, metric) in &self.clinical_standards.quality_metrics {
444                    checks_evaluated += 1;
445                    if metric.acceptable_range.0 >= metric.acceptable_range.1 {
446                        violations.push(format!(
447                            "Clinical quality metric '{id}' has invalid acceptable range: [{}, {}]",
448                            metric.acceptable_range.0, metric.acceptable_range.1
449                        ));
450                        recommendations.push(format!(
451                            "Remediate clinical workflow to meet quality target for '{id}'"
452                        ));
453                    } else {
454                        checks_passed += 1;
455                    }
456                }
457            }
458            ComplianceType::Security => {
459                for (id, metric) in &self.audit_system.compliance_monitoring.compliance_metrics {
460                    checks_evaluated += 1;
461                    if metric.metric_value < metric.metric_target {
462                        violations.push(format!(
463                            "Security compliance metric '{id}' non-compliant: {} < {}",
464                            metric.metric_value, metric.metric_target
465                        ));
466                    } else {
467                        checks_passed += 1;
468                    }
469                }
470            }
471        }
472
473        let compliance_score = if checks_evaluated > 0 {
474            Some(checks_passed as f64 / checks_evaluated as f64)
475        } else {
476            None
477        };
478
479        let now = std::time::SystemTime::now()
480            .duration_since(std::time::UNIX_EPOCH)
481            .map(|d| d.as_secs())
482            .unwrap_or(0);
483
484        Ok(ComplianceReport {
485            report_id: format!("report_{now}"),
486            report_type: compliance_type,
487            compliance_score,
488            violations,
489            recommendations,
490            generated_at: now,
491        })
492    }
493}
494
495impl HIPAACompliance {
496    /// Construct a `HIPAACompliance` with default field values.
497    pub fn new() -> Self {
498        Self {
499            privacy_rules: HashMap::new(),
500            security_rules: HashMap::new(),
501            breach_notification: BreachNotification::new(),
502        }
503    }
504
505    /// Initialize `HIPAACompliance`; `Ok` when ready.
506    pub fn initialize(&mut self) -> Result<(), MedicalError> {
507        Ok(())
508    }
509
510    /// Add `privacy_rule` to the `HIPAACompliance`.
511    pub fn add_privacy_rule(&mut self, rule: PrivacyRule) {
512        self.privacy_rules.insert(rule.rule_id.clone(), rule);
513    }
514
515    /// Look up `privacy_rule` by id; `None` when absent.
516    pub fn get_privacy_rule(&self, rule_id: &str) -> Option<&PrivacyRule> {
517        self.privacy_rules.get(rule_id)
518    }
519
520    /// Add `security_rule` to the `HIPAACompliance`.
521    pub fn add_security_rule(&mut self, rule: SecurityRule) {
522        self.security_rules.insert(rule.rule_id.clone(), rule);
523    }
524
525    /// Look up `security_rule` by id; `None` when absent.
526    pub fn get_security_rule(&self, rule_id: &str) -> Option<&SecurityRule> {
527        self.security_rules.get(rule_id)
528    }
529
530    /// The `breach_notification` component.
531    pub fn breach_notification(&self) -> &BreachNotification {
532        &self.breach_notification
533    }
534}
535
536impl BreachNotification {
537    /// Construct a `BreachNotification` with default field values.
538    pub fn new() -> Self {
539        Self {
540            notification_rules: HashMap::new(),
541            notification_templates: HashMap::new(),
542        }
543    }
544
545    /// Add `notification_rule` to the `BreachNotification`.
546    pub fn add_notification_rule(&mut self, rule: NotificationRule) {
547        self.notification_rules.insert(rule.rule_id.clone(), rule);
548    }
549
550    /// Look up `notification_rule` by id; `None` when absent.
551    pub fn get_notification_rule(&self, rule_id: &str) -> Option<&NotificationRule> {
552        self.notification_rules.get(rule_id)
553    }
554
555    /// Add `notification_template` to the `BreachNotification`.
556    pub fn add_notification_template(&mut self, template: NotificationTemplate) {
557        self.notification_templates
558            .insert(template.template_id.clone(), template);
559    }
560
561    /// Look up `notification_template` by id; `None` when absent.
562    pub fn get_notification_template(&self, template_id: &str) -> Option<&NotificationTemplate> {
563        self.notification_templates.get(template_id)
564    }
565}
566
567impl GDPRCompliance {
568    /// Construct a `GDPRCompliance` with default field values.
569    pub fn new() -> Self {
570        Self {
571            data_protection_principles: HashMap::new(),
572            data_subject_rights: HashMap::new(),
573            data_processing_agreements: HashMap::new(),
574        }
575    }
576
577    /// Initialize `GDPRCompliance`; `Ok` when ready.
578    pub fn initialize(&mut self) -> Result<(), MedicalError> {
579        Ok(())
580    }
581
582    /// Add `data_protection_principle` to the `GDPRCompliance`.
583    pub fn add_data_protection_principle(&mut self, principle: DataProtectionPrinciple) {
584        self.data_protection_principles
585            .insert(principle.principle_id.clone(), principle);
586    }
587
588    /// Look up `data_protection_principle` by id; `None` when absent.
589    pub fn get_data_protection_principle(
590        &self,
591        principle_id: &str,
592    ) -> Option<&DataProtectionPrinciple> {
593        self.data_protection_principles.get(principle_id)
594    }
595
596    /// Add `data_subject_right` to the `GDPRCompliance`.
597    pub fn add_data_subject_right(&mut self, right: DataSubjectRight) {
598        self.data_subject_rights
599            .insert(right.right_id.clone(), right);
600    }
601
602    /// Look up `data_subject_right` by id; `None` when absent.
603    pub fn get_data_subject_right(&self, right_id: &str) -> Option<&DataSubjectRight> {
604        self.data_subject_rights.get(right_id)
605    }
606
607    /// Add `data_processing_agreement` to the `GDPRCompliance`.
608    pub fn add_data_processing_agreement(&mut self, agreement: DataProcessingAgreement) {
609        self.data_processing_agreements
610            .insert(agreement.agreement_id.clone(), agreement);
611    }
612
613    /// Look up `data_processing_agreement` by id; `None` when absent.
614    pub fn get_data_processing_agreement(
615        &self,
616        agreement_id: &str,
617    ) -> Option<&DataProcessingAgreement> {
618        self.data_processing_agreements.get(agreement_id)
619    }
620}
621
622impl ClinicalStandards {
623    /// Construct a `ClinicalStandards` with default field values.
624    pub fn new() -> Self {
625        Self {
626            clinical_guidelines: HashMap::new(),
627            quality_metrics: HashMap::new(),
628            best_practices: HashMap::new(),
629        }
630    }
631
632    /// Initialize `ClinicalStandards`; `Ok` when ready.
633    pub fn initialize(&mut self) -> Result<(), MedicalError> {
634        Ok(())
635    }
636
637    /// Add `clinical_guideline` to the `ClinicalStandards`.
638    pub fn add_clinical_guideline(&mut self, guideline: ClinicalGuideline) {
639        self.clinical_guidelines
640            .insert(guideline.guideline_id.clone(), guideline);
641    }
642
643    /// Look up `clinical_guideline` by id; `None` when absent.
644    pub fn get_clinical_guideline(&self, guideline_id: &str) -> Option<&ClinicalGuideline> {
645        self.clinical_guidelines.get(guideline_id)
646    }
647
648    /// Add `quality_metric` to the `ClinicalStandards`.
649    pub fn add_quality_metric(&mut self, metric: QualityMetric) {
650        self.quality_metrics
651            .insert(metric.metric_id.clone(), metric);
652    }
653
654    /// Look up `quality_metric` by id; `None` when absent.
655    pub fn get_quality_metric(&self, metric_id: &str) -> Option<&QualityMetric> {
656        self.quality_metrics.get(metric_id)
657    }
658
659    /// Add `best_practice` to the `ClinicalStandards`.
660    pub fn add_best_practice(&mut self, practice: BestPractice) {
661        self.best_practices
662            .insert(practice.practice_id.clone(), practice);
663    }
664
665    /// Look up `best_practice` by id; `None` when absent.
666    pub fn get_best_practice(&self, practice_id: &str) -> Option<&BestPractice> {
667        self.best_practices.get(practice_id)
668    }
669}
670
671impl AuditSystem {
672    /// Construct a `AuditSystem` with default field values.
673    pub fn new() -> Self {
674        Self {
675            audit_trails: HashMap::new(),
676            audit_reports: HashMap::new(),
677            compliance_monitoring: ComplianceMonitoring::new(),
678        }
679    }
680
681    /// Initialize `AuditSystem`; `Ok` when ready.
682    pub fn initialize(&mut self) -> Result<(), MedicalError> {
683        Ok(())
684    }
685
686    /// Add `audit_trail` to the `AuditSystem`.
687    pub fn add_audit_trail(&mut self, trail: AuditTrail) {
688        self.audit_trails.insert(trail.trail_id.clone(), trail);
689    }
690
691    /// Look up `audit_trail` by id; `None` when absent.
692    pub fn get_audit_trail(&self, trail_id: &str) -> Option<&AuditTrail> {
693        self.audit_trails.get(trail_id)
694    }
695
696    /// Add `audit_report` to the `AuditSystem`.
697    pub fn add_audit_report(&mut self, report: AuditReport) {
698        self.audit_reports.insert(report.report_id.clone(), report);
699    }
700
701    /// Look up `audit_report` by id; `None` when absent.
702    pub fn get_audit_report(&self, report_id: &str) -> Option<&AuditReport> {
703        self.audit_reports.get(report_id)
704    }
705
706    /// The `compliance_monitoring` component.
707    pub fn compliance_monitoring(&self) -> &ComplianceMonitoring {
708        &self.compliance_monitoring
709    }
710}
711
712impl ComplianceMonitoring {
713    /// Construct a `ComplianceMonitoring` with default field values.
714    pub fn new() -> Self {
715        Self {
716            monitoring_rules: HashMap::new(),
717            compliance_metrics: HashMap::new(),
718        }
719    }
720
721    /// Add `monitoring_rule` to the `ComplianceMonitoring`.
722    pub fn add_monitoring_rule(&mut self, rule: MonitoringRule) {
723        self.monitoring_rules.insert(rule.rule_id.clone(), rule);
724    }
725
726    /// Look up `monitoring_rule` by id; `None` when absent.
727    pub fn get_monitoring_rule(&self, rule_id: &str) -> Option<&MonitoringRule> {
728        self.monitoring_rules.get(rule_id)
729    }
730
731    /// Add `compliance_metric` to the `ComplianceMonitoring`.
732    pub fn add_compliance_metric(&mut self, metric: ComplianceMetric) {
733        self.compliance_metrics
734            .insert(metric.metric_id.clone(), metric);
735    }
736
737    /// Look up `compliance_metric` by id; `None` when absent.
738    pub fn get_compliance_metric(&self, metric_id: &str) -> Option<&ComplianceMetric> {
739        self.compliance_metrics.get(metric_id)
740    }
741
742    /// `true` when the named metric's value satisfies its threshold.
743    pub fn is_compliant(&self, metric_id: &str) -> bool {
744        if let Some(metric) = self.compliance_metrics.get(metric_id) {
745            metric.metric_value >= metric.metric_target
746        } else {
747            false
748        }
749    }
750}