from django.shortcuts import get_object_or_404 from coldfront.core.allocation.models import Allocation from .models import AuditEvent from .resolvers import allocation_label from .utils import log_event PATCH_MARKER = "_cmmc_audit_allocation_workflow_patch_installed" def _date_value(value): return value.isoformat() if value else None def _allocation_summary(allocation): return allocation_label(allocation) def install_allocation_workflow_audit_patch(): from coldfront.core.allocation import views as allocation_views if getattr(allocation_views, PATCH_MARKER, False): return original_renew_post = allocation_views.AllocationRenewView.post def renew_post(self, request, *args, **kwargs): allocation = get_object_or_404( Allocation.objects.select_related("project", "status"), pk=self.kwargs.get("pk"), ) old_status = allocation.status.name old_end_date = allocation.end_date response = original_renew_post(self, request, *args, **kwargs) allocation.refresh_from_db() allocation = Allocation.objects.select_related("project", "status").get(pk=allocation.pk) new_status = allocation.status.name if old_status != new_status and new_status == "Renewal Requested": log_event( AuditEvent.Action.RENEWAL_REQUESTED, allocation, old_values={ "status": old_status, "end_date": _date_value(old_end_date), "project_id": allocation.project_id, }, new_values={ "status": new_status, "end_date": _date_value(allocation.end_date), "project_id": allocation.project_id, }, message=f"Renewal requested for {_allocation_summary(allocation)}", actor=getattr(request, "user", None), request=request, source=AuditEvent.Source.COLDFRONT_WORKFLOW, target_repr=_allocation_summary(allocation), ) return response allocation_views.AllocationRenewView.post = renew_post setattr(allocation_views, PATCH_MARKER, True)