52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
"""
|
|
Signals for Insurance Approvals app.
|
|
Automatically track status changes and create audit trail.
|
|
"""
|
|
|
|
from django.db.models.signals import pre_save, post_save
|
|
from django.dispatch import receiver
|
|
from .models import InsuranceApprovalRequest, ApprovalStatusHistory
|
|
|
|
|
|
@receiver(pre_save, sender=InsuranceApprovalRequest)
|
|
def track_status_change(sender, instance, **kwargs):
|
|
"""
|
|
Track status changes before saving.
|
|
Store the old status for comparison in post_save.
|
|
"""
|
|
if instance.pk:
|
|
try:
|
|
old_instance = InsuranceApprovalRequest.objects.get(pk=instance.pk)
|
|
instance._old_status = old_instance.status
|
|
except InsuranceApprovalRequest.DoesNotExist:
|
|
instance._old_status = None
|
|
else:
|
|
instance._old_status = None
|
|
|
|
|
|
@receiver(post_save, sender=InsuranceApprovalRequest)
|
|
def create_status_history(sender, instance, created, **kwargs):
|
|
"""
|
|
Create status history entry when status changes.
|
|
"""
|
|
if created:
|
|
# New approval request created
|
|
ApprovalStatusHistory.objects.create(
|
|
approval_request=instance,
|
|
from_status=None,
|
|
to_status=instance.status,
|
|
reason='Initial creation',
|
|
changed_by=instance.created_by
|
|
)
|
|
else:
|
|
# Check if status changed
|
|
old_status = getattr(instance, '_old_status', None)
|
|
if old_status and old_status != instance.status:
|
|
ApprovalStatusHistory.objects.create(
|
|
approval_request=instance,
|
|
from_status=old_status,
|
|
to_status=instance.status,
|
|
reason=f'Status changed from {old_status} to {instance.status}',
|
|
changed_by=instance.created_by # This should ideally be the current user
|
|
)
|