14 KiB
14 KiB
Phase 7: Signals, Services & Tasks Implementation Plan
Overview
Phase 7 focuses on implementing Django signals for automation, service layer for business logic separation, and Celery tasks for background processing in the Tenhal Multidisciplinary Healthcare Platform.
Objectives
- Django Signals - Automate audit logging, notifications, and workflow triggers
- Service Layer - Separate business logic from views for better maintainability
- Celery Tasks - Background processing for reminders, reports, and integrations
- Scheduled Jobs - Periodic tasks using Celery Beat
Implementation Checklist
Part 1: Celery Setup & Configuration (30 minutes)
- Celery already configured in settings.py
- Create
AgdarCentre/celery.py- Celery app initialization - Update
AgdarCentre/__init__.py- Import Celery app - Create
.enventries for Redis configuration - Test Celery worker connection
Part 2: Django Signals (2-3 hours)
Core App Signals
- Create
core/signals.pypost_savesignal for Patient - Create audit log entrypost_savesignal for User - Send welcome emailpre_deletesignal for Patient - Soft delete implementationpost_savesignal for Consent - Notify relevant staff
Appointments App Signals
- Create
appointments/signals.pypost_savesignal for Appointment - Status change notificationspost_savesignal for Appointment (CONFIRMED) - Schedule reminder taskpost_savesignal for Appointment (COMPLETED) - Trigger invoice generationpost_savesignal for Appointment (CANCELLED) - Cancel reminderspre_savesignal for Appointment - Validate time slot conflicts
Finance App Signals
- Create
finance/signals.pypost_savesignal for Payment - Update invoice statuspost_savesignal for Invoice (ISSUED) - Send invoice notificationpost_savesignal for Invoice (OVERDUE) - Schedule overdue reminderpost_savesignal for Payment (COMPLETED) - Send receipt
Referrals App Signals
- Create
referrals/signals.pypost_savesignal for Referral (PENDING) - Notify receiving clinicpost_savesignal for Referral (ACCEPTED) - Notify sending clinicpost_savesignal for Referral (REJECTED) - Notify sending clinicpost_savesignal for Referral (COMPLETED) - Update statistics
Part 3: Service Layer (3-4 hours)
Core Services
- Create
core/services.pyPatientServiceclasscreate_patient()- Patient creation with validationupdate_patient()- Patient update with auditmerge_patients()- Merge duplicate patientsget_patient_summary()- Complete patient overview
FileServiceclasscreate_file()- File creation with auto-numberingclose_file()- File closure workflowreopen_file()- File reopening workflow
Appointments Services
- Create
appointments/services.pyAppointmentServiceclassbook_appointment()- Complete booking workflowconfirm_appointment()- Confirmation with validationreschedule_appointment()- Reschedule with conflict checkcancel_appointment()- Cancellation with reasoncheck_availability()- Provider availability checkget_calendar_slots()- Calendar view generation
ScheduleServiceclasscreate_schedule()- Schedule creationcheck_conflicts()- Conflict detectionget_available_slots()- Available time slots
Finance Services
- Create
finance/services.pyInvoiceServiceclassgenerate_invoice()- Auto-generate from appointmentissue_invoice()- Issue draft invoicecalculate_totals()- Calculate invoice totalsapply_discount()- Apply discount logicmark_paid()- Mark invoice as paid
PaymentServiceclassprocess_payment()- Payment processingrefund_payment()- Refund processingallocate_payment()- Allocate to invoices
PackageServiceclassactivate_package()- Activate patient packageconsume_session()- Consume package sessioncheck_balance()- Check remaining sessions
Referrals Services
- Create
referrals/services.pyReferralServiceclasscreate_referral()- Referral creation with validationaccept_referral()- Accept workflowreject_referral()- Reject workflowcomplete_referral()- Complete workflowcheck_auto_rules()- Check auto-referral rulesget_referral_statistics()- Statistics calculation
Part 4: Celery Tasks (3-4 hours)
Notification Tasks
- Create
core/tasks.pysend_email_task()- Async email sendingsend_sms_task()- Async SMS sendingsend_whatsapp_task()- Async WhatsApp sendingcreate_notification_task()- Create in-app notification
Appointment Tasks
- Create
appointments/tasks.pysend_appointment_reminder()- Send reminder (24h, 2h before)send_appointment_confirmation()- Send confirmationcheck_no_shows()- Check and mark no-showsgenerate_daily_schedule()- Generate daily schedule reportsync_calendar()- Sync with external calendar (future)
Finance Tasks
- Create
finance/tasks.pygenerate_invoice_from_appointment()- Auto-generate invoicesend_invoice_notification()- Send invoice to patientcheck_overdue_invoices()- Check and notify overduesend_payment_receipt()- Send payment receiptgenerate_financial_report()- Generate periodic reportsprocess_batch_payments()- Process batch payments
Referral Tasks
- Create
referrals/tasks.pysend_referral_notification()- Notify receiving cliniccheck_pending_referrals()- Check pending referralssend_referral_reminder()- Remind about pending referralsupdate_referral_statistics()- Update statistics
Integration Tasks
- Create
integrations/tasks.pysubmit_nphies_eligibility()- NPHIES eligibility checksubmit_nphies_prior_auth()- NPHIES prior authorizationsubmit_nphies_claim()- NPHIES claim submissionsubmit_zatca_invoice()- ZATCA e-invoice submissionsync_lab_results()- Sync lab resultssync_radiology_results()- Sync radiology results
Part 5: Celery Beat Scheduled Tasks (1-2 hours)
Periodic Tasks Configuration
-
Create
appointments/beat_schedule.py- Daily at 8:00 AM - Send appointment reminders for today
- Every 2 hours - Check for no-shows
- Daily at 6:00 PM - Generate next day schedule
-
Create
finance/beat_schedule.py- Daily at 9:00 AM - Check overdue invoices
- Weekly on Monday - Generate weekly financial report
- Monthly on 1st - Generate monthly financial report
-
Create
referrals/beat_schedule.py- Daily at 10:00 AM - Check pending referrals
- Weekly on Friday - Send referral statistics
-
Create
integrations/beat_schedule.py- Every 30 minutes - Sync lab results
- Every 30 minutes - Sync radiology results
- Daily at 11:00 PM - Submit pending ZATCA invoices
Part 6: Testing & Validation (2-3 hours)
Signal Tests
- Create
tests/test_signals.py- Test patient creation triggers audit log
- Test appointment confirmation triggers reminder
- Test payment triggers invoice update
- Test referral creation triggers notification
Service Tests
- Create
tests/test_services.py- Test appointment booking service
- Test invoice generation service
- Test payment processing service
- Test referral workflow service
Task Tests
- Create
tests/test_tasks.py- Test email sending task
- Test reminder task
- Test invoice generation task
- Test integration tasks
Integration Tests
- Test complete workflows
- Book appointment → Generate invoice → Send reminder
- Create referral → Notify → Accept → Complete
- Issue invoice → Process payment → Send receipt
Part 7: Documentation (1 hour)
- Create
SIGNALS_REFERENCE.md- Signal documentation - Create
SERVICES_REFERENCE.md- Service layer documentation - Create
TASKS_REFERENCE.md- Celery tasks documentation - Update
README.md- Add Celery setup instructions - Create
CELERY_DEPLOYMENT.md- Production deployment guide
File Structure
AgdarCentre/
├── celery.py # Celery app initialization
├── __init__.py # Import Celery app
│
core/
├── signals.py # Core app signals
├── services.py # Core business services
├── tasks.py # Core Celery tasks
│
appointments/
├── signals.py # Appointment signals
├── services.py # Appointment services
├── tasks.py # Appointment tasks
├── beat_schedule.py # Scheduled tasks
│
finance/
├── signals.py # Finance signals
├── services.py # Finance services
├── tasks.py # Finance tasks
├── beat_schedule.py # Scheduled tasks
│
referrals/
├── signals.py # Referral signals
├── services.py # Referral services
├── tasks.py # Referral tasks
├── beat_schedule.py # Scheduled tasks
│
integrations/
├── signals.py # Integration signals
├── services.py # Integration services
├── tasks.py # Integration tasks
├── beat_schedule.py # Scheduled tasks
│
tests/
├── test_signals.py # Signal tests
├── test_services.py # Service tests
├── test_tasks.py # Task tests
Key Design Patterns
1. Signal Pattern
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Appointment)
def appointment_confirmed(sender, instance, created, **kwargs):
if not created and instance.status == 'CONFIRMED':
# Schedule reminder task
send_appointment_reminder.apply_async(
args=[instance.id],
eta=instance.start_time - timedelta(hours=24)
)
2. Service Layer Pattern
class AppointmentService:
@staticmethod
def book_appointment(patient, provider, start_time, **kwargs):
# Validate availability
if not AppointmentService.check_availability(provider, start_time):
raise ValidationError("Time slot not available")
# Create appointment
appointment = Appointment.objects.create(
patient=patient,
provider=provider,
start_time=start_time,
**kwargs
)
# Trigger post-creation tasks
send_appointment_confirmation.delay(appointment.id)
return appointment
3. Celery Task Pattern
from celery import shared_task
@shared_task(bind=True, max_retries=3)
def send_appointment_reminder(self, appointment_id):
try:
appointment = Appointment.objects.get(id=appointment_id)
# Send reminder logic
send_sms(appointment.patient.phone, f"Reminder: {appointment}")
except Exception as exc:
raise self.retry(exc=exc, countdown=60)
Dependencies Already Installed
✅ celery>=5.3.4 ✅ redis>=5.0.1 ✅ django-celery-beat>=2.5.0 ✅ django-celery-results>=2.5.1
Environment Variables Needed
Add to .env:
# Celery Configuration
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0
# Email Configuration (for notifications)
EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=your-email@gmail.com
EMAIL_HOST_PASSWORD=your-app-password
DEFAULT_FROM_EMAIL=noreply@agdarcentre.sa
# SMS Configuration (Twilio)
TWILIO_ACCOUNT_SID=your-account-sid
TWILIO_AUTH_TOKEN=your-auth-token
TWILIO_PHONE_NUMBER=+1234567890
TWILIO_WHATSAPP_NUMBER=whatsapp:+1234567890
Running Celery
Development
# Terminal 1: Start Redis
redis-server
# Terminal 2: Start Celery Worker
celery -A AgdarCentre worker -l info
# Terminal 3: Start Celery Beat (for scheduled tasks)
celery -A AgdarCentre beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler
# Terminal 4: Start Django
python manage.py runserver
Production
# Use supervisor or systemd to manage processes
# See CELERY_DEPLOYMENT.md for details
Expected Benefits
-
Automation
- Automatic appointment reminders
- Auto-generated invoices
- Automated notifications
- Scheduled reports
-
Performance
- Background processing of heavy tasks
- Non-blocking email/SMS sending
- Async integration calls
- Improved response times
-
Maintainability
- Separated business logic in services
- Reusable service methods
- Testable components
- Clear code organization
-
Reliability
- Task retry mechanisms
- Error handling and logging
- Transaction management
- Audit trail automation
Timeline Estimate
- Part 1: Celery Setup - 30 minutes
- Part 2: Signals - 2-3 hours
- Part 3: Services - 3-4 hours
- Part 4: Tasks - 3-4 hours
- Part 5: Beat Schedule - 1-2 hours
- Part 6: Testing - 2-3 hours
- Part 7: Documentation - 1 hour
Total: 13-18 hours (2-3 days)
Success Criteria
- All signals properly connected and tested
- Service layer methods working correctly
- Celery tasks executing successfully
- Scheduled tasks running on time
- Email/SMS notifications working
- Integration tasks functioning
- Comprehensive test coverage
- Complete documentation
Next Phase Preview
Phase 8: Admin, RBAC & Auditing
- Custom Django admin interfaces
- Enhanced role-based permissions
- Detailed audit trails
- Compliance reporting
- User activity monitoring
Status: Ready to implement Priority: High (enables automation and background processing) Dependencies: Phase 6 (APIs) completed ✅