|
| 1 | +from typing import List |
| 2 | + |
| 3 | +from celery import shared_task |
| 4 | +from django.conf import settings |
| 5 | + |
| 6 | +from hypha.apply.funds.models.submissions import ApplicationSubmission |
| 7 | +from hypha.apply.funds.models.utils import SubmissionExportManager |
| 8 | +from hypha.apply.funds.utils import export_submissions_to_csv |
| 9 | +from hypha.apply.todo.options import ( |
| 10 | + DOWNLOAD_SUBMISSIONS_EXPORT, |
| 11 | + FAILED_SUBMISSIONS_EXPORT, |
| 12 | +) |
| 13 | +from hypha.apply.todo.views import add_task_to_user |
| 14 | +from hypha.apply.users.models import User |
| 15 | + |
| 16 | + |
| 17 | +@shared_task |
| 18 | +def generate_submission_csv( |
| 19 | + qs_ids: List[int], request_user_id: int, base_uri: str |
| 20 | +) -> None: |
| 21 | + """Celery task to generate a CSV file containing the given submission IDs |
| 22 | +
|
| 23 | + Integer IDs have to be used as QuerySets are not simple data types & can't be |
| 24 | + passed to workers. |
| 25 | +
|
| 26 | + Updates the user's SubmissionExportManager object with status/final data, then |
| 27 | + adds a download task to the user's `My Tasks` when completed. |
| 28 | +
|
| 29 | + Args: |
| 30 | + qs_ids: A list of application IDs to generate the CSV export for |
| 31 | + request_user_id: The ID of the user issuing the export request |
| 32 | + """ |
| 33 | + try: |
| 34 | + qs = ApplicationSubmission.objects.filter(id__in=qs_ids) |
| 35 | + request_user = User.objects.get(pk=request_user_id) |
| 36 | + |
| 37 | + # If the user already has an existing export, delete it to begin the new one |
| 38 | + if current := SubmissionExportManager.objects.filter(user=request_user): |
| 39 | + current.delete() |
| 40 | + |
| 41 | + export_manager = SubmissionExportManager.objects.create( |
| 42 | + user=request_user, total_export=len(qs_ids) |
| 43 | + ) |
| 44 | + csv_string = export_submissions_to_csv(qs, base_uri) |
| 45 | + export_manager.export_data = "".join(csv_string.readlines()) |
| 46 | + export_manager.set_completed_and_save() |
| 47 | + |
| 48 | + user_task = DOWNLOAD_SUBMISSIONS_EXPORT |
| 49 | + |
| 50 | + except Exception as exc: |
| 51 | + # Update the status to failed |
| 52 | + export_manager.set_failed_and_save() |
| 53 | + user_task = FAILED_SUBMISSIONS_EXPORT |
| 54 | + |
| 55 | + if settings.SENTRY_DSN: |
| 56 | + # If sentry is enabled, pass the exception to sentry |
| 57 | + from sentry_sdk import capture_exception |
| 58 | + |
| 59 | + capture_exception(exc) |
| 60 | + else: |
| 61 | + # Otherwise re-raise it |
| 62 | + raise exc |
| 63 | + finally: |
| 64 | + # When the generation is complete or failed, add a task to the user's dashboard (only if async) |
| 65 | + if not settings.CELERY_TASK_ALWAYS_EAGER: |
| 66 | + add_task_to_user( |
| 67 | + code=user_task, |
| 68 | + user=request_user, |
| 69 | + related_obj=export_manager, |
| 70 | + ) |
0 commit comments