|
1 | | -from admin_extra_buttons.decorators import button |
2 | | -from django.contrib import admin |
3 | | -from django.http import HttpRequest, HttpResponse |
| 1 | +from typing import TypedDict, Protocol, TypeVar, Generic |
| 2 | +from django.contrib import messages |
| 3 | +from django.db.models import Model |
| 4 | +from django.http import HttpRequest |
| 5 | +from admin_extra_buttons.api import button |
4 | 6 |
|
5 | | -from ..models import SyncLog |
6 | | -from .base import BaseModelAdmin |
| 7 | +from ..contrib.hope.sync.context_programs import sync_context_programs, SyncStep as ContextProgramsSyncStep |
| 8 | +from ..contrib.hope.sync.context_geo import sync_context_geo, SyncStep as ContextGeoSyncStep |
7 | 9 |
|
8 | 10 |
|
9 | | -@admin.register(SyncLog) |
10 | | -class SyncLogAdmin(BaseModelAdmin): |
11 | | - list_display = ("content_type", "content_object", "last_update_date", "last_id") |
| 11 | +T_SyncStep = TypeVar("T_SyncStep", bound=ContextProgramsSyncStep | ContextGeoSyncStep) |
| 12 | +type SyncHandlerResp = dict[str, list[str] | dict[str, int]] |
| 13 | + |
| 14 | + |
| 15 | +class SyncHandler(Protocol, Generic[T_SyncStep]): |
| 16 | + def sync(self, step: T_SyncStep) -> SyncHandlerResp: |
| 17 | + pass |
| 18 | + |
| 19 | + |
| 20 | +class ContextProgramsSyncHandler: |
| 21 | + def sync(self, step: ContextProgramsSyncStep) -> SyncHandlerResp: |
| 22 | + return sync_context_programs(step) |
| 23 | + |
| 24 | + |
| 25 | +class ContextGeoSyncHandler: |
| 26 | + def sync(self, step: ContextGeoSyncStep) -> SyncHandlerResp: |
| 27 | + return sync_context_geo(step) |
| 28 | + |
| 29 | + |
| 30 | +class SyncConfig(TypedDict): |
| 31 | + model: type[Model] |
| 32 | + step: T_SyncStep |
| 33 | + sync_handler: SyncHandler |
| 34 | + |
| 35 | + |
| 36 | +class SyncAdminMixin: |
| 37 | + sync_config: SyncConfig |
12 | 38 |
|
13 | 39 | @button() |
14 | | - def sync_all(self, request: HttpRequest) -> "HttpResponse": |
15 | | - SyncLog.objects.refresh() |
| 40 | + def sync(self, request: HttpRequest) -> None: |
| 41 | + totals = self.sync_config["sync_handler"].sync(step=self.sync_config["step"]) |
| 42 | + if errors := totals.get("errors"): |
| 43 | + self.message_user(request, "; ".join(errors), level=messages.ERROR) |
| 44 | + else: |
| 45 | + info = totals[self.sync_config["model"]._meta.model_name] |
| 46 | + self.message_user(request, f"{info['add']} created - {info['upd']} updated", level=messages.SUCCESS) |
0 commit comments