84 lines
3.0 KiB
Python
84 lines
3.0 KiB
Python
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.advance_ticket_automation")
|
|
def advance_ticket_automation_task(run_id: int) -> None:
|
|
from apps.tickets.automation import advance_ticket_automation
|
|
|
|
advance_ticket_automation(run_id)
|
|
|
|
|
|
@shared_task(name="apps.tickets.tasks.close_ticket_automation")
|
|
def close_ticket_automation_task(run_id: int) -> bool:
|
|
from apps.tickets.automation import close_due_ticket_automation
|
|
|
|
return close_due_ticket_automation(run_id)
|
|
|
|
|
|
@shared_task(name="apps.tickets.tasks.close_due_ticket_automations")
|
|
def close_due_ticket_automations_task() -> int:
|
|
from apps.tickets.automation import close_due_ticket_automation
|
|
from apps.tickets.models import TicketAutomationRun
|
|
|
|
run_ids = list(
|
|
TicketAutomationRun.objects.filter(
|
|
status="waiting_customer",
|
|
next_action_at__lte=timezone.now(),
|
|
).values_list("id", flat=True)[:500]
|
|
)
|
|
return sum(bool(close_due_ticket_automation(run_id)) for run_id in run_ids)
|
|
|
|
|
|
@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
|