49 lines
No EOL
1.6 KiB
Python
49 lines
No EOL
1.6 KiB
Python
from django.utils.timezone import now
|
|
from .models import AuditLog, Risk, Notification
|
|
|
|
def model_diff(old, new, fields=None):
|
|
"""
|
|
Compare two model instances and return a dict of changed fields.
|
|
- old: previous model instance (from DB)
|
|
- new: updated model instance (unsaved)
|
|
- fields: optional list of fields to check
|
|
"""
|
|
changes = {}
|
|
opts = new._meta
|
|
|
|
if fields is None:
|
|
fields = [f.name for f in opts.fields]
|
|
|
|
for field_name in fields:
|
|
old_value = getattr(old, field_name, None)
|
|
new_value = getattr(new, field_name, None)
|
|
|
|
if old_value != new_value:
|
|
changes[field_name] = {"old": old_value, "new": new_value}
|
|
|
|
return changes
|
|
|
|
def check_risk_followups():
|
|
"""
|
|
Check if follow ups need attention and create notifications.
|
|
Ensures no duplicate notifications per risk per day
|
|
"""
|
|
today = now().date()
|
|
risks = Risk.objects.filter(follow_up__lte=today)
|
|
|
|
for risk in risks:
|
|
if risk.owner:
|
|
notification, created = Notification.objects.get_or_create(
|
|
user=risk.owner,
|
|
message=f"Follow-up required for risk: {risk.title}",
|
|
defaults={"read": False, "sent": False},
|
|
)
|
|
|
|
if created:
|
|
AuditLog.objects.create(
|
|
user=None, # system action
|
|
action="create",
|
|
model="Notification",
|
|
object_id=notification.pk,
|
|
changes={"message": notification.message, "user": risk.owner.username},
|
|
) |