From e34ccbfb48ef46ee24885300c13e73da04c1b64c Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Wed, 28 Aug 2024 16:43:47 -0400 Subject: [PATCH] membershipworks: Set action labels without overriding `_get_tool_dict` --- membershipworks/admin.py | 69 +++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/membershipworks/admin.py b/membershipworks/admin.py index 8a25c10..85a0e30 100644 --- a/membershipworks/admin.py +++ b/membershipworks/admin.py @@ -22,13 +22,39 @@ from .models import ( Member, Transaction, ) -from .tasks.scrape import ( - scrape_event_details, - scrape_membershipworks, -) +from .tasks.scrape import scrape_event_details, scrape_membershipworks from .tasks.ucsAccounts import sync_accounts +class TaskLabel: + def __init__(self, label: str, task) -> None: + self.label = label + self.task = task + + def __str__(self) -> str: + try: + last_run = naturaltime( + Task.objects.filter(group=self.task.q_task_group) + .values_list("started", flat=True) + .latest("started") + ) + except Task.DoesNotExist: + last_run = "Never" + return f"{self.label} [Last Run {last_run}]" + + +def run_task_action(admin: admin.ModelAdmin, label: str, task): + @action(label=TaskLabel(label, task)) + def action_func(request, obj): + async_task(task, group=task.q_task_group) + admin.message_user( + request, + "Queued task, please wait a few seconds/minutes then refresh the page", + ) + + return action_func + + class ReadOnlyAdminMixin: def has_add_permission(self, request, obj=None): return False @@ -45,36 +71,13 @@ class BaseMembershipWorksAdmin( ): changelist_actions = ("refresh_membershipworks_data", "sync_ucs_accounts") - # internal method from DjangoObjectActions - def _get_tool_dict(self, tool_name): - tool = super(DjangoObjectActions, self)._get_tool_dict(tool_name) - if tool_name == "refresh_membershipworks_data": - try: - last_run_time = naturaltime( - Task.objects.filter(group=scrape_membershipworks.q_task_group) - .values_list("started", flat=True) - .latest("started") - ) - except Task.DoesNotExist: - last_run_time = "Never" - tool["label"] = f"Refresh Data [Last Run {last_run_time}]" - return tool + @property + def refresh_membershipworks_data(self): + return run_task_action(self, "Refresh Data", scrape_membershipworks) - @action - def refresh_membershipworks_data(self, request, obj): - async_task(scrape_membershipworks, group=scrape_membershipworks.q_task_group) - self.message_user( - request, - "Queued refresh, please wait a few seconds/minutes then refresh the page", - ) - - @action - def sync_ucs_accounts(self, request, obj): - async_task(sync_accounts, group=sync_accounts.q_task_group) - self.message_user( - request, - "Queued refresh, please wait a few seconds/minutes then refresh the page", - ) + @property + def sync_ucs_accounts(self): + return run_task_action(self, "Sync UCS Accounts", sync_accounts) class MemberFlagInline(admin.TabularInline):