# """ # Viewflow workflows for quality app. # Provides quality assurance, incident management, and improvement workflows. # """ # # from viewflow import Flow, lock # from viewflow.base import this, flow_func # from viewflow.contrib import celery # from viewflow.decorators import flow_view # from viewflow.fields import CharField, ModelField # from viewflow.forms import ModelForm # from viewflow.views import CreateProcessView, UpdateProcessView # from viewflow.models import Process, Task # from django.contrib.auth.models import User # from django.urls import reverse_lazy # from django.utils import timezone # from django.db import transaction # from django.core.mail import send_mail # # from .models import ( # QualityIndicator, QualityMeasurement, IncidentReport, RiskAssessment, # AuditPlan, AuditFinding, ImprovementProject # ) # from .views import ( # IncidentReportingView, IncidentInvestigationView, RootCauseAnalysisView, # CorrectiveActionView, IncidentClosureView, QualityMeasurementView, # IndicatorAnalysisView, AuditPlanningView, AuditExecutionView, # FindingManagementView, ImprovementProjectView, RiskAssessmentView # ) # # # class IncidentManagementProcess(Process): # """ # Viewflow process model for incident management # """ # incident_report = ModelField(IncidentReport, help_text='Associated incident report') # # # Process status tracking # incident_reported = models.BooleanField(default=False) # initial_assessment_completed = models.BooleanField(default=False) # investigation_assigned = models.BooleanField(default=False) # investigation_completed = models.BooleanField(default=False) # root_cause_identified = models.BooleanField(default=False) # corrective_actions_planned = models.BooleanField(default=False) # actions_implemented = models.BooleanField(default=False) # effectiveness_verified = models.BooleanField(default=False) # incident_closed = models.BooleanField(default=False) # # class Meta: # verbose_name = 'Incident Management Process' # verbose_name_plural = 'Incident Management Processes' # # # class IncidentManagementFlow(Flow): # """ # Incident Management Workflow # # This flow manages patient safety incidents from reporting through # investigation, corrective action, and closure. # """ # # process_class = IncidentManagementProcess # # # Flow definition # start = ( # flow_func(this.start_incident_management) # .Next(this.report_incident) # ) # # report_incident = ( # flow_view(IncidentReportingView) # .Permission('quality.can_report_incidents') # .Next(this.assess_incident) # ) # # assess_incident = ( # flow_func(this.perform_initial_assessment) # .Next(this.assign_investigation) # ) # # assign_investigation = ( # flow_view(InvestigationAssignmentView) # .Permission('quality.can_assign_investigations') # .Next(this.investigate_incident) # ) # # investigate_incident = ( # flow_view(IncidentInvestigationView) # .Permission('quality.can_investigate_incidents') # .Next(this.analyze_root_cause) # ) # # analyze_root_cause = ( # flow_view(RootCauseAnalysisView) # .Permission('quality.can_analyze_root_causes') # .Next(this.plan_corrective_actions) # ) # # plan_corrective_actions = ( # flow_view(CorrectiveActionView) # .Permission('quality.can_plan_corrective_actions') # .Next(this.implement_actions) # ) # # implement_actions = ( # flow_view(ActionImplementationView) # .Permission('quality.can_implement_actions') # .Next(this.verify_effectiveness) # ) # # verify_effectiveness = ( # flow_view(EffectivenessVerificationView) # .Permission('quality.can_verify_effectiveness') # .Next(this.close_incident) # ) # # close_incident = ( # flow_func(this.complete_incident_management) # .Next(this.end) # ) # # end = flow_func(this.end_incident_management) # # # Flow functions # def start_incident_management(self, activation): # """Initialize the incident management process""" # process = activation.process # incident = process.incident_report # # # Update incident status # incident.status = 'reported' # incident.save() # # # Send immediate notifications # self.notify_incident_reported(incident) # # # Check for high-severity incidents # if incident.severity in ['severe_harm', 'death']: # self.notify_critical_incident(incident) # self.notify_regulatory_bodies(incident) # # def perform_initial_assessment(self, activation): # """Perform initial incident assessment""" # process = activation.process # incident = process.incident_report # # # Update incident status # incident.status = 'under_investigation' # incident.save() # # # Mark assessment completed # process.initial_assessment_completed = True # process.save() # # # Determine investigation priority # self.determine_investigation_priority(incident) # # # Send assessment notifications # self.notify_assessment_completed(incident) # # def complete_incident_management(self, activation): # """Finalize the incident management process""" # process = activation.process # incident = process.incident_report # # # Update incident status # incident.status = 'closed' # incident.closed_date = timezone.now() # incident.save() # # # Mark process as completed # process.incident_closed = True # process.save() # # # Send completion notifications # self.notify_incident_closure(incident) # # # Update quality metrics # self.update_incident_metrics(incident) # # # Generate lessons learned # self.generate_lessons_learned(incident) # # def end_incident_management(self, activation): # """End the incident management workflow""" # process = activation.process # # # Generate incident summary report # self.generate_incident_summary(process.incident_report) # # # Helper methods # def notify_incident_reported(self, incident): # """Notify quality staff of incident report""" # from django.contrib.auth.models import Group # # quality_staff = User.objects.filter( # groups__name='Quality Staff' # ) # # for staff in quality_staff: # send_mail( # subject=f'Incident Reported: {incident.incident_number}', # message=f'New {incident.get_severity_display()} incident reported: {incident.title}', # from_email='quality@hospital.com', # recipient_list=[staff.email], # fail_silently=True # ) # # def notify_critical_incident(self, incident): # """Notify of critical incident""" # quality_managers = User.objects.filter( # groups__name='Quality Managers' # ) # # for manager in quality_managers: # send_mail( # subject=f'CRITICAL INCIDENT: {incident.incident_number}', # message=f'Critical incident requiring immediate attention: {incident.title}', # from_email='quality@hospital.com', # recipient_list=[manager.email], # fail_silently=True # ) # # def notify_regulatory_bodies(self, incident): # """Notify regulatory bodies if required""" # if incident.regulatory_notification: # # This would implement regulatory notification logic # pass # # def determine_investigation_priority(self, incident): # """Determine investigation priority based on severity""" # severity_priority_map = { # 'death': 'urgent', # 'severe_harm': 'high', # 'moderate_harm': 'medium', # 'minor_harm': 'low', # 'no_harm': 'low' # } # # incident.priority = severity_priority_map.get(incident.severity, 'medium') # incident.save() # # def notify_assessment_completed(self, incident): # """Notify assessment completion""" # if incident.assigned_to and incident.assigned_to.email: # send_mail( # subject=f'Investigation Assignment: {incident.incident_number}', # message=f'You have been assigned to investigate incident: {incident.title}', # from_email='quality@hospital.com', # recipient_list=[incident.assigned_to.email], # fail_silently=True # ) # # def notify_incident_closure(self, incident): # """Notify incident closure""" # # Notify reporter # if incident.reported_by and incident.reported_by.email: # send_mail( # subject=f'Incident Closed: {incident.incident_number}', # message=f'The incident you reported has been investigated and closed.', # from_email='quality@hospital.com', # recipient_list=[incident.reported_by.email], # fail_silently=True # ) # # def update_incident_metrics(self, incident): # """Update incident quality metrics""" # # This would update incident reporting metrics # pass # # def generate_lessons_learned(self, incident): # """Generate lessons learned from incident""" # # This would create lessons learned documentation # pass # # def generate_incident_summary(self, incident): # """Generate incident summary report""" # # This would generate comprehensive incident report # pass # # # class QualityMonitoringProcess(Process): # """ # Viewflow process model for quality monitoring # """ # quality_indicator = ModelField(QualityIndicator, help_text='Associated quality indicator') # # # Process status tracking # data_collected = models.BooleanField(default=False) # measurement_calculated = models.BooleanField(default=False) # analysis_completed = models.BooleanField(default=False) # trends_identified = models.BooleanField(default=False) # actions_recommended = models.BooleanField(default=False) # report_generated = models.BooleanField(default=False) # monitoring_completed = models.BooleanField(default=False) # # class Meta: # verbose_name = 'Quality Monitoring Process' # verbose_name_plural = 'Quality Monitoring Processes' # # # class QualityMonitoringFlow(Flow): # """ # Quality Monitoring Workflow # # This flow manages quality indicator monitoring including data # collection, analysis, and reporting. # """ # # process_class = QualityMonitoringProcess # # # Flow definition # start = ( # flow_func(this.start_quality_monitoring) # .Next(this.collect_data) # ) # # collect_data = ( # flow_view(DataCollectionView) # .Permission('quality.can_collect_data') # .Next(this.calculate_measurement) # ) # # calculate_measurement = ( # flow_view(QualityMeasurementView) # .Permission('quality.can_calculate_measurements') # .Next(this.analyze_results) # ) # # analyze_results = ( # flow_view(IndicatorAnalysisView) # .Permission('quality.can_analyze_indicators') # .Next(this.identify_trends) # ) # # identify_trends = ( # flow_func(this.perform_trend_analysis) # .Next(this.recommend_actions) # ) # # recommend_actions = ( # flow_view(ActionRecommendationView) # .Permission('quality.can_recommend_actions') # .Next(this.generate_report) # ) # # generate_report = ( # flow_view(QualityReportView) # .Permission('quality.can_generate_reports') # .Next(this.complete_monitoring) # ) # # complete_monitoring = ( # flow_func(this.finalize_quality_monitoring) # .Next(this.end) # ) # # end = flow_func(this.end_quality_monitoring) # # # Flow functions # def start_quality_monitoring(self, activation): # """Initialize the quality monitoring process""" # process = activation.process # indicator = process.quality_indicator # # # Send notification to responsible staff # self.notify_monitoring_due(indicator) # # def perform_trend_analysis(self, activation): # """Perform trend analysis on quality data""" # process = activation.process # indicator = process.quality_indicator # # # Analyze trends in measurements # trends = self.analyze_indicator_trends(indicator) # # if trends: # process.trends_identified = True # process.save() # # # Alert if concerning trends identified # if self.is_concerning_trend(trends): # self.alert_quality_managers(indicator, trends) # # def finalize_quality_monitoring(self, activation): # """Finalize the quality monitoring process""" # process = activation.process # indicator = process.quality_indicator # # # Mark monitoring as completed # process.monitoring_completed = True # process.save() # # # Send completion notifications # self.notify_monitoring_completion(indicator) # # # Schedule next monitoring cycle # self.schedule_next_monitoring(indicator) # # def end_quality_monitoring(self, activation): # """End the quality monitoring workflow""" # process = activation.process # # # Generate monitoring summary # self.generate_monitoring_summary(process.quality_indicator) # # # Helper methods # def notify_monitoring_due(self, indicator): # """Notify responsible staff of monitoring due""" # if indicator.responsible_user and indicator.responsible_user.email: # send_mail( # subject=f'Quality Monitoring Due: {indicator.name}', # message=f'Quality indicator monitoring is due for: {indicator.name}', # from_email='quality@hospital.com', # recipient_list=[indicator.responsible_user.email], # fail_silently=True # ) # # def analyze_indicator_trends(self, indicator): # """Analyze trends in quality indicator""" # # This would implement trend analysis logic # return {} # # def is_concerning_trend(self, trends): # """Check if trends are concerning""" # # This would implement trend evaluation logic # return False # # def alert_quality_managers(self, indicator, trends): # """Alert quality managers of concerning trends""" # quality_managers = User.objects.filter( # groups__name='Quality Managers' # ) # # for manager in quality_managers: # send_mail( # subject=f'Quality Alert: {indicator.name}', # message=f'Concerning trend identified in quality indicator: {indicator.name}', # from_email='quality@hospital.com', # recipient_list=[manager.email], # fail_silently=True # ) # # def notify_monitoring_completion(self, indicator): # """Notify monitoring completion""" # # This would notify relevant parties # pass # # def schedule_next_monitoring(self, indicator): # """Schedule next monitoring cycle""" # # This would schedule the next monitoring cycle # pass # # def generate_monitoring_summary(self, indicator): # """Generate monitoring summary""" # # This would generate monitoring summary # pass # # # class AuditManagementProcess(Process): # """ # Viewflow process model for audit management # """ # audit_plan = ModelField(AuditPlan, help_text='Associated audit plan') # # # Process status tracking # audit_planned = models.BooleanField(default=False) # team_assigned = models.BooleanField(default=False) # audit_conducted = models.BooleanField(default=False) # findings_documented = models.BooleanField(default=False) # corrective_actions_planned = models.BooleanField(default=False) # actions_implemented = models.BooleanField(default=False) # follow_up_completed = models.BooleanField(default=False) # audit_closed = models.BooleanField(default=False) # # class Meta: # verbose_name = 'Audit Management Process' # verbose_name_plural = 'Audit Management Processes' # # # class AuditManagementFlow(Flow): # """ # Audit Management Workflow # # This flow manages quality audits from planning through # execution, finding management, and closure. # """ # # process_class = AuditManagementProcess # # # Flow definition # start = ( # flow_func(this.start_audit_management) # .Next(this.plan_audit) # ) # # plan_audit = ( # flow_view(AuditPlanningView) # .Permission('quality.can_plan_audits') # .Next(this.assign_team) # ) # # assign_team = ( # flow_view(AuditTeamAssignmentView) # .Permission('quality.can_assign_audit_teams') # .Next(this.conduct_audit) # ) # # conduct_audit = ( # flow_view(AuditExecutionView) # .Permission('quality.can_conduct_audits') # .Next(this.document_findings) # ) # # document_findings = ( # flow_view(FindingManagementView) # .Permission('quality.can_document_findings') # .Next(this.plan_corrective_actions) # ) # # plan_corrective_actions = ( # flow_view(CorrectiveActionPlanningView) # .Permission('quality.can_plan_corrective_actions') # .Next(this.implement_actions) # ) # # implement_actions = ( # flow_view(ActionImplementationView) # .Permission('quality.can_implement_actions') # .Next(this.follow_up) # ) # # follow_up = ( # flow_view(AuditFollowUpView) # .Permission('quality.can_follow_up_audits') # .Next(this.close_audit) # ) # # close_audit = ( # flow_func(this.complete_audit_management) # .Next(this.end) # ) # # end = flow_func(this.end_audit_management) # # # Flow functions # def start_audit_management(self, activation): # """Initialize the audit management process""" # process = activation.process # audit = process.audit_plan # # # Update audit status # audit.status = 'planned' # audit.save() # # # Send notification to audit team # self.notify_audit_planned(audit) # # def complete_audit_management(self, activation): # """Finalize the audit management process""" # process = activation.process # audit = process.audit_plan # # # Update audit status # audit.status = 'completed' # audit.actual_end_date = timezone.now().date() # audit.save() # # # Mark process as completed # process.audit_closed = True # process.save() # # # Send completion notifications # self.notify_audit_completion(audit) # # # Update audit metrics # self.update_audit_metrics(audit) # # def end_audit_management(self, activation): # """End the audit management workflow""" # process = activation.process # # # Generate audit summary report # self.generate_audit_summary(process.audit_plan) # # # Helper methods # def notify_audit_planned(self, audit): # """Notify audit team of planned audit""" # audit_team = audit.audit_team.all() # for member in audit_team: # if member.email: # send_mail( # subject=f'Audit Planned: {audit.title}', # message=f'You have been assigned to audit: {audit.title}', # from_email='quality@hospital.com', # recipient_list=[member.email], # fail_silently=True # ) # # def notify_audit_completion(self, audit): # """Notify audit completion""" # # Notify department being audited # if audit.department: # department_staff = User.objects.filter( # department=audit.department # ) # for staff in department_staff: # if staff.email: # send_mail( # subject=f'Audit Completed: {audit.title}', # message=f'The audit of your department has been completed.', # from_email='quality@hospital.com', # recipient_list=[staff.email], # fail_silently=True # ) # # def update_audit_metrics(self, audit): # """Update audit performance metrics""" # # This would update audit metrics # pass # # def generate_audit_summary(self, audit): # """Generate audit summary report""" # # This would generate comprehensive audit report # pass # # # class ImprovementProjectProcess(Process): # """ # Viewflow process model for improvement projects # """ # improvement_project = ModelField(ImprovementProject, help_text='Associated improvement project') # # # Process status tracking # project_initiated = models.BooleanField(default=False) # team_assembled = models.BooleanField(default=False) # baseline_established = models.BooleanField(default=False) # improvements_implemented = models.BooleanField(default=False) # results_measured = models.BooleanField(default=False) # sustainability_ensured = models.BooleanField(default=False) # project_completed = models.BooleanField(default=False) # # class Meta: # verbose_name = 'Improvement Project Process' # verbose_name_plural = 'Improvement Project Processes' # # # class ImprovementProjectFlow(Flow): # """ # Improvement Project Workflow # # This flow manages quality improvement projects using # structured methodologies like PDSA and Lean. # """ # # process_class = ImprovementProjectProcess # # # Flow definition # start = ( # flow_func(this.start_improvement_project) # .Next(this.initiate_project) # ) # # initiate_project = ( # flow_view(ProjectInitiationView) # .Permission('quality.can_initiate_projects') # .Next(this.assemble_team) # ) # # assemble_team = ( # flow_view(TeamAssemblyView) # .Permission('quality.can_assemble_teams') # .Next(this.establish_baseline) # ) # # establish_baseline = ( # flow_view(BaselineEstablishmentView) # .Permission('quality.can_establish_baseline') # .Next(this.implement_improvements) # ) # # implement_improvements = ( # flow_view(ImprovementImplementationView) # .Permission('quality.can_implement_improvements') # .Next(this.measure_results) # ) # # measure_results = ( # flow_view(ResultsMeasurementView) # .Permission('quality.can_measure_results') # .Next(this.ensure_sustainability) # ) # # ensure_sustainability = ( # flow_view(SustainabilityView) # .Permission('quality.can_ensure_sustainability') # .Next(this.complete_project) # ) # # complete_project = ( # flow_func(this.finalize_improvement_project) # .Next(this.end) # ) # # end = flow_func(this.end_improvement_project) # # # Flow functions # def start_improvement_project(self, activation): # """Initialize the improvement project process""" # process = activation.process # project = process.improvement_project # # # Update project status # project.status = 'planned' # project.save() # # # Send notification to project team # self.notify_project_initiated(project) # # def finalize_improvement_project(self, activation): # """Finalize the improvement project process""" # process = activation.process # project = process.improvement_project # # # Update project status # project.status = 'completed' # project.actual_end_date = timezone.now().date() # project.save() # # # Mark process as completed # process.project_completed = True # process.save() # # # Send completion notifications # self.notify_project_completion(project) # # # Calculate ROI # self.calculate_project_roi(project) # # def end_improvement_project(self, activation): # """End the improvement project workflow""" # process = activation.process # # # Generate project summary report # self.generate_project_summary(process.improvement_project) # # # Helper methods # def notify_project_initiated(self, project): # """Notify project team of project initiation""" # project_team = project.project_team.all() # for member in project_team: # if member.email: # send_mail( # subject=f'Improvement Project Started: {project.title}', # message=f'You have been assigned to improvement project: {project.title}', # from_email='quality@hospital.com', # recipient_list=[member.email], # fail_silently=True # ) # # def notify_project_completion(self, project): # """Notify project completion""" # # Notify sponsor # if project.sponsor and project.sponsor.email: # send_mail( # subject=f'Project Completed: {project.title}', # message=f'The improvement project you sponsored has been completed.', # from_email='quality@hospital.com', # recipient_list=[project.sponsor.email], # fail_silently=True # ) # # def calculate_project_roi(self, project): # """Calculate project return on investment""" # # This would implement ROI calculation logic # pass # # def generate_project_summary(self, project): # """Generate project summary report""" # # This would generate comprehensive project report # pass # # # class RiskManagementProcess(Process): # """ # Viewflow process model for risk management # """ # risk_assessment = ModelField(RiskAssessment, help_text='Associated risk assessment') # # # Process status tracking # risk_identified = models.BooleanField(default=False) # risk_assessed = models.BooleanField(default=False) # controls_evaluated = models.BooleanField(default=False) # mitigation_planned = models.BooleanField(default=False) # controls_implemented = models.BooleanField(default=False) # effectiveness_monitored = models.BooleanField(default=False) # risk_managed = models.BooleanField(default=False) # # class Meta: # verbose_name = 'Risk Management Process' # verbose_name_plural = 'Risk Management Processes' # # # class RiskManagementFlow(Flow): # """ # Risk Management Workflow # # This flow manages risk identification, assessment, # mitigation, and monitoring activities. # """ # # process_class = RiskManagementProcess # # # Flow definition # start = ( # flow_func(this.start_risk_management) # .Next(this.identify_risk) # ) # # identify_risk = ( # flow_view(RiskIdentificationView) # .Permission('quality.can_identify_risks') # .Next(this.assess_risk) # ) # # assess_risk = ( # flow_view(RiskAssessmentView) # .Permission('quality.can_assess_risks') # .Next(this.evaluate_controls) # ) # # evaluate_controls = ( # flow_view(ControlEvaluationView) # .Permission('quality.can_evaluate_controls') # .Next(this.plan_mitigation) # ) # # plan_mitigation = ( # flow_view(MitigationPlanningView) # .Permission('quality.can_plan_mitigation') # .Next(this.implement_controls) # ) # # implement_controls = ( # flow_view(ControlImplementationView) # .Permission('quality.can_implement_controls') # .Next(this.monitor_effectiveness) # ) # # monitor_effectiveness = ( # flow_view(EffectivenessMonitoringView) # .Permission('quality.can_monitor_effectiveness') # .Next(this.manage_risk) # ) # # manage_risk = ( # flow_func(this.complete_risk_management) # .Next(this.end) # ) # # end = flow_func(this.end_risk_management) # # # Flow functions # def start_risk_management(self, activation): # """Initialize the risk management process""" # process = activation.process # risk = process.risk_assessment # # # Update risk status # risk.status = 'active' # risk.save() # # # Send notification to risk owner # self.notify_risk_identified(risk) # # def complete_risk_management(self, activation): # """Finalize the risk management process""" # process = activation.process # risk = process.risk_assessment # # # Update risk status based on residual risk level # if risk.residual_risk_level in ['low', 'medium']: # risk.status = 'active' # else: # risk.status = 'under_review' # # risk.save() # # # Mark process as completed # process.risk_managed = True # process.save() # # # Send completion notifications # self.notify_risk_management_completion(risk) # # # Schedule risk review # self.schedule_risk_review(risk) # # def end_risk_management(self, activation): # """End the risk management workflow""" # process = activation.process # # # Generate risk management summary # self.generate_risk_summary(process.risk_assessment) # # # Helper methods # def notify_risk_identified(self, risk): # """Notify risk owner of identified risk""" # if risk.responsible_person and risk.responsible_person.email: # send_mail( # subject=f'Risk Assignment: {risk.title}', # message=f'You have been assigned responsibility for risk: {risk.title}', # from_email='quality@hospital.com', # recipient_list=[risk.responsible_person.email], # fail_silently=True # ) # # def notify_risk_management_completion(self, risk): # """Notify risk management completion""" # # This would notify relevant parties # pass # # def schedule_risk_review(self, risk): # """Schedule risk review""" # # This would schedule periodic risk reviews # pass # # def generate_risk_summary(self, risk): # """Generate risk management summary""" # # This would generate risk summary # pass # # # # Celery tasks for background processing # @celery.job # def auto_generate_quality_reports(): # """Background task to automatically generate quality reports""" # try: # # This would generate scheduled quality reports # return True # except Exception: # return False # # # @celery.job # def monitor_quality_indicators(): # """Background task to monitor quality indicators""" # try: # # This would check quality indicators for threshold breaches # return True # except Exception: # return False # # # @celery.job # def schedule_audits(): # """Background task to schedule audits""" # try: # # This would schedule regular audits # return True # except Exception: # return False # # # @celery.job # def track_corrective_actions(): # """Background task to track corrective action progress""" # try: # # This would monitor corrective action due dates # return True # except Exception: # return False # # # @celery.job # def risk_monitoring(): # """Background task to monitor risks""" # try: # # This would monitor risk levels and control effectiveness # return True # except Exception: # return False #