from celery import shared_task from django.utils import timezone from apps.agents.models import AgentArtifact, AgentRun from apps.audit.models import OperationAuditLog from apps.modelhub.models import ModelInvocation from apps.tickets.draft_services import execute_draft_analysis from apps.tickets.models import TicketDraft from apps.tickets.storage import delete_object @shared_task(name="apps.tickets.tasks.execute_ticket_draft_analysis") def execute_ticket_draft_analysis(draft_id: int, run_id: int) -> None: execute_draft_analysis(draft_id, run_id) @shared_task(name="apps.tickets.tasks.cleanup_expired_ticket_drafts") def cleanup_expired_ticket_drafts() -> int: queryset = TicketDraft.objects.filter( expires_at__lt=timezone.now(), confirmed_ticket__isnull=True ).prefetch_related("materials") count = queryset.count() for draft in queryset: public_id = str(draft.public_id) for material in draft.materials.all(): try: delete_object(material.storage_path) except Exception: pass OperationAuditLog.objects.create( user=draft.created_by, module="tickets", action="draft_expired", target_type="ticket_draft", target_id=str(draft.public_id), request_snapshot={ "status": draft.status, "guided_rounds": draft.guided_rounds, "material_count": draft.materials.count(), }, result="success", ) runs = AgentRun.objects.filter(input_payload__draft_public_id=public_id) invocation_ids = list( ModelInvocation.objects.filter(agent_attempts__step__run__in=runs) .values_list("id", flat=True) .distinct() ) AgentArtifact.objects.filter( artifact_type="ticket_draft", payload__draft_public_id=public_id ).delete() runs.delete() ModelInvocation.objects.filter(id__in=invocation_ids).delete() draft.delete() return count