aa-fatanalysis 1.2.0__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/PKG-INFO +28 -3
  2. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/README.md +27 -2
  3. aa_fatanalysis-2.0.0/fatanalysis/__init__.py +1 -0
  4. aa_fatanalysis-2.0.0/fatanalysis/spa_api.py +528 -0
  5. aa_fatanalysis-2.0.0/fatanalysis/static/fatanalysis/spa/assets/index.css +1 -0
  6. aa_fatanalysis-2.0.0/fatanalysis/static/fatanalysis/spa/assets/index.js +204 -0
  7. aa_fatanalysis-2.0.0/fatanalysis/templates/fatanalysis/spa.html +28 -0
  8. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/test_auto_sync.py +1 -1
  9. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/test_participation.py +1 -1
  10. aa_fatanalysis-2.0.0/fatanalysis/tests/test_spa_api.py +320 -0
  11. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/test_views.py +10 -10
  12. aa_fatanalysis-2.0.0/fatanalysis/urls.py +29 -0
  13. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/views.py +18 -0
  14. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/pyproject.toml +1 -1
  15. aa_fatanalysis-1.2.0/fatanalysis/__init__.py +0 -1
  16. aa_fatanalysis-1.2.0/fatanalysis/urls.py +0 -17
  17. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/.gitignore +0 -0
  18. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/LICENSE +0 -0
  19. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/apps.py +0 -0
  20. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/auth_hooks.py +0 -0
  21. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/forms.py +0 -0
  22. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/management/__init__.py +0 -0
  23. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/management/commands/__init__.py +0 -0
  24. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/management/commands/fatanalysis_sync_all.py +0 -0
  25. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/0001_initial.py +0 -0
  26. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/0002_alter_uploadperiod_upload_date.py +0 -0
  27. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/0003_general.py +0 -0
  28. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/0004_fatsyncconfig_alter_fatentry_options_and_more.py +0 -0
  29. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/0005_fatmonthperiod_fats_by_time_and_more.py +0 -0
  30. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/0006_fatmonthperiod_fats_by_ship.py +0 -0
  31. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/0007_auto_sync.py +0 -0
  32. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/migrations/__init__.py +0 -0
  33. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/models.py +0 -0
  34. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/scheduling.py +0 -0
  35. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/services.py +0 -0
  36. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tasks.py +0 -0
  37. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/base.html +0 -0
  38. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/import_csv.html +0 -0
  39. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/index.html +0 -0
  40. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/overview.html +0 -0
  41. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/period_delete.html +0 -0
  42. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/period_detail.html +0 -0
  43. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/period_list.html +0 -0
  44. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/player_detail.html +0 -0
  45. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templates/fatanalysis/sync_management.html +0 -0
  46. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templatetags/__init__.py +0 -0
  47. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/templatetags/fatanalysis_tags.py +0 -0
  48. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/__init__.py +0 -0
  49. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/test_models.py +0 -0
  50. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/test_services.py +0 -0
  51. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/test_settings.py +0 -0
  52. {aa_fatanalysis-1.2.0 → aa_fatanalysis-2.0.0}/fatanalysis/tests/test_urls.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: aa-fatanalysis
3
- Version: 1.2.0
3
+ Version: 2.0.0
4
4
  Summary: FAT Analysis Plugin for Alliance Auth
5
5
  Author-email: Maddog Broekman <maddogbroekman@gmail.com>
6
6
  License: MIT License
@@ -60,9 +60,10 @@ Alliance Auth plugin for analyzing FATs (Fleet Activity Tracking). This plugin p
60
60
  - **INIT Auth Scraper**: Built-in scraper service to ingest reports directly from remote Alliance Auth AFAT instances using session cookies.
61
61
  - **Frontend Director UI**: Manage scraper credentials, test live connections, trigger on-demand imports, and upload CSVs directly from the web interface without needing Django admin.
62
62
  - **Automatic Sync**: A Celery task fetches the current month from INIT Auth on a schedule (default every 6 hours; during the first 3 days of a month the previous month too). Switch it on or off and set the interval on the Sync & Ingestion page. The plugin keeps its own Celery beat entry, so no `CELERYBEAT_SCHEDULE` entry in `local.py` is needed.
63
+ - **Modern SPA UI**: React + Tailwind CSS + shadcn/ui, following the Alliance Auth light/dark theme. Every table has per-column sorting and search. The classic Django templates stay available with `?classic=1`.
63
64
  - **Dynamic Time Windows**: Switch instantly between 30 Days (Latest), 90 Days, 120 Days, YTD, specific years, and All Time.
64
65
  - **Corp Participation & Averages**: Active Participation compares the mains with FATs to the corp's mains in Auth; the dashboard also shows corp averages (FATs per month, per active pilot and per member) for the selected window.
65
- - **Pilot Longitudinal Detail**: Track individual pilot participation trends over time with interactive Chart.js line and doughnut charts.
66
+ - **Pilot Longitudinal Detail**: Track individual pilot participation trends over time with interactive line and doughnut charts.
66
67
  - **Permissions Management**: Separate `fatanalysis.basic_access` (members) and `fatanalysis.manage_fatanalysis` (directors/leadership).
67
68
 
68
69
  ## Installation
@@ -98,8 +99,32 @@ Alliance Auth plugin for analyzing FATs (Fleet Activity Tracking). This plugin p
98
99
  sudo systemctl restart supervisor
99
100
  ```
100
101
  *(Or restart gunicorn and celery according to your specific setup)*
101
- Celery beat must be running for the automatic sync. `migrate` creates its schedule (`fatanalysis_auto_sync`, every 6 hours); it needs a session cookie on the Sync & Ingestion page to fetch data.
102
+ Restart the Celery workers too, also after every upgrade: a worker that is not restarted does not know new tasks.
103
+
104
+ 6. **Automatic sync (Celery task)**
105
+ The task `fatanalysis.tasks.auto_sync` fetches the current month from INIT Auth (and the previous month during the first 3 days of a month).
106
+ - **No `local.py` entry needed.** Do not add it to `CELERYBEAT_SCHEDULE`. `migrate` creates the periodic task `fatanalysis_auto_sync` (every 6 hours) in the database, and the plugin keeps it up to date.
107
+ - **Celery beat** must run with a database scheduler. Alliance Auth's default `allianceauth.crontab.schedulers.OffsetDatabaseScheduler` works.
108
+ - **Session cookie:** enter it on the Sync & Ingestion page (`/fatanalysis/sync/`); without it the task skips.
109
+ - **Settings:** switch the sync on or off and set the interval (1–168 hours) in the Automatic Sync card on that page. The change applies right away.
110
+ - Check that the workers know the task:
111
+
112
+ ```bash
113
+ celery -A myauth inspect registered | grep fatanalysis
114
+ ```
102
115
 
103
116
  ## Permissions
104
117
  - `fatanalysis.basic_access`: Allows members to view the FAT Analysis dashboard, filter by time windows, and view player details.
105
118
  - `fatanalysis.manage_fatanalysis`: Allows directors/leadership to access Sync & Ingestion management, configure the AFAT scraper, import CSVs, and manage/delete recording periods.
119
+
120
+ ## Frontend development
121
+
122
+ The UI is a Vite + React 19 + TypeScript + Tailwind v4 + shadcn/ui SPA in `frontend/`, scoped under `.aa-spa-root` (no global Preflight, so it does not disturb Bootstrap). The built bundle is committed in `fatanalysis/static/fatanalysis/spa/assets/`.
123
+
124
+ ```powershell
125
+ powershell -File frontend/build.ps1
126
+ ```
127
+
128
+ `build.ps1` copies the sources to `%LOCALAPPDATA%a-fatanalysis-frontend-build` (npm install fails on Google Drive), builds there and copies `index.js` and `index.css` back. After deploying, run `collectstatic` and restart the web workers.
129
+
130
+ The JSON API lives in `fatanalysis/spa_api.py` (`/fatanalysis/api/v1/spa/...`).
@@ -12,9 +12,10 @@ Alliance Auth plugin for analyzing FATs (Fleet Activity Tracking). This plugin p
12
12
  - **INIT Auth Scraper**: Built-in scraper service to ingest reports directly from remote Alliance Auth AFAT instances using session cookies.
13
13
  - **Frontend Director UI**: Manage scraper credentials, test live connections, trigger on-demand imports, and upload CSVs directly from the web interface without needing Django admin.
14
14
  - **Automatic Sync**: A Celery task fetches the current month from INIT Auth on a schedule (default every 6 hours; during the first 3 days of a month the previous month too). Switch it on or off and set the interval on the Sync & Ingestion page. The plugin keeps its own Celery beat entry, so no `CELERYBEAT_SCHEDULE` entry in `local.py` is needed.
15
+ - **Modern SPA UI**: React + Tailwind CSS + shadcn/ui, following the Alliance Auth light/dark theme. Every table has per-column sorting and search. The classic Django templates stay available with `?classic=1`.
15
16
  - **Dynamic Time Windows**: Switch instantly between 30 Days (Latest), 90 Days, 120 Days, YTD, specific years, and All Time.
16
17
  - **Corp Participation & Averages**: Active Participation compares the mains with FATs to the corp's mains in Auth; the dashboard also shows corp averages (FATs per month, per active pilot and per member) for the selected window.
17
- - **Pilot Longitudinal Detail**: Track individual pilot participation trends over time with interactive Chart.js line and doughnut charts.
18
+ - **Pilot Longitudinal Detail**: Track individual pilot participation trends over time with interactive line and doughnut charts.
18
19
  - **Permissions Management**: Separate `fatanalysis.basic_access` (members) and `fatanalysis.manage_fatanalysis` (directors/leadership).
19
20
 
20
21
  ## Installation
@@ -50,8 +51,32 @@ Alliance Auth plugin for analyzing FATs (Fleet Activity Tracking). This plugin p
50
51
  sudo systemctl restart supervisor
51
52
  ```
52
53
  *(Or restart gunicorn and celery according to your specific setup)*
53
- Celery beat must be running for the automatic sync. `migrate` creates its schedule (`fatanalysis_auto_sync`, every 6 hours); it needs a session cookie on the Sync & Ingestion page to fetch data.
54
+ Restart the Celery workers too, also after every upgrade: a worker that is not restarted does not know new tasks.
55
+
56
+ 6. **Automatic sync (Celery task)**
57
+ The task `fatanalysis.tasks.auto_sync` fetches the current month from INIT Auth (and the previous month during the first 3 days of a month).
58
+ - **No `local.py` entry needed.** Do not add it to `CELERYBEAT_SCHEDULE`. `migrate` creates the periodic task `fatanalysis_auto_sync` (every 6 hours) in the database, and the plugin keeps it up to date.
59
+ - **Celery beat** must run with a database scheduler. Alliance Auth's default `allianceauth.crontab.schedulers.OffsetDatabaseScheduler` works.
60
+ - **Session cookie:** enter it on the Sync & Ingestion page (`/fatanalysis/sync/`); without it the task skips.
61
+ - **Settings:** switch the sync on or off and set the interval (1–168 hours) in the Automatic Sync card on that page. The change applies right away.
62
+ - Check that the workers know the task:
63
+
64
+ ```bash
65
+ celery -A myauth inspect registered | grep fatanalysis
66
+ ```
54
67
 
55
68
  ## Permissions
56
69
  - `fatanalysis.basic_access`: Allows members to view the FAT Analysis dashboard, filter by time windows, and view player details.
57
70
  - `fatanalysis.manage_fatanalysis`: Allows directors/leadership to access Sync & Ingestion management, configure the AFAT scraper, import CSVs, and manage/delete recording periods.
71
+
72
+ ## Frontend development
73
+
74
+ The UI is a Vite + React 19 + TypeScript + Tailwind v4 + shadcn/ui SPA in `frontend/`, scoped under `.aa-spa-root` (no global Preflight, so it does not disturb Bootstrap). The built bundle is committed in `fatanalysis/static/fatanalysis/spa/assets/`.
75
+
76
+ ```powershell
77
+ powershell -File frontend/build.ps1
78
+ ```
79
+
80
+ `build.ps1` copies the sources to `%LOCALAPPDATA%a-fatanalysis-frontend-build` (npm install fails on Google Drive), builds there and copies `index.js` and `index.css` back. After deploying, run `collectstatic` and restart the web workers.
81
+
82
+ The JSON API lives in `fatanalysis/spa_api.py` (`/fatanalysis/api/v1/spa/...`).
@@ -0,0 +1 @@
1
+ __version__ = "2.0.0"
@@ -0,0 +1,528 @@
1
+ """JSON API and host view for the aa-fatanalysis React/shadcn SPA.
2
+
3
+ Permissions mirror the classic views: ``fatanalysis.basic_access`` for read-only
4
+ data, ``fatanalysis.manage_fatanalysis`` for sync management and deleting periods.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import calendar
10
+ import json
11
+ import logging
12
+ from collections.abc import Callable
13
+ from datetime import timedelta
14
+ from functools import wraps
15
+ from typing import Any
16
+
17
+ from django.contrib.auth.models import User
18
+ from django.http import HttpRequest, HttpResponse, JsonResponse
19
+ from django.shortcuts import render
20
+ from django.utils import timezone
21
+ from django.utils.translation import gettext as _
22
+ from django.views.decorators.http import require_GET, require_POST
23
+
24
+ from .forms import FatAutoSyncForm, FatSyncBulkForm, FatSyncConfigForm, FatSyncSingleMonthForm
25
+ from .models import FatEntry, FatMonthPeriod, FatSyncConfig
26
+ from .scheduling import PERIODIC_TASK_NAME, ensure_auto_sync_schedule
27
+ from .services import AfatScraperService, FatAggregationService
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ BASIC = "fatanalysis.basic_access"
32
+ MANAGE = "fatanalysis.manage_fatanalysis"
33
+ RAW_WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
34
+
35
+
36
+ def api_permission_required(perm: str) -> Callable[[Callable[..., HttpResponse]], Callable[..., HttpResponse]]:
37
+ """Like ``permission_required`` but answers with JSON 401/403 instead of redirecting."""
38
+
39
+ def decorator(view: Callable[..., HttpResponse]) -> Callable[..., HttpResponse]:
40
+ @wraps(view)
41
+ def wrapper(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
42
+ if not request.user.is_authenticated:
43
+ return JsonResponse({"error": _("Authentication required.")}, status=401)
44
+ if not request.user.has_perm(perm):
45
+ return JsonResponse({"error": _("Permission denied.")}, status=403)
46
+ return view(request, *args, **kwargs)
47
+
48
+ return wrapper
49
+
50
+ return decorator
51
+
52
+
53
+ def _json_body(request: HttpRequest) -> dict[str, Any]:
54
+ """Parse the JSON request body into a dict (empty on invalid input)."""
55
+ if not request.body:
56
+ return {}
57
+ try:
58
+ data = json.loads(request.body)
59
+ except (json.JSONDecodeError, UnicodeDecodeError):
60
+ return {}
61
+ return data if isinstance(data, dict) else {}
62
+
63
+
64
+ def form_errors(form: Any) -> str:
65
+ """Flatten Django form errors into one readable string."""
66
+ parts = []
67
+ for field, errors in form.errors.items():
68
+ parts.append(f"{field}: {' '.join(str(e) for e in errors)}")
69
+ return "; ".join(parts)
70
+
71
+
72
+ def spa_context(request: HttpRequest, title: object) -> dict[str, Any]:
73
+ """Template context for the SPA host page."""
74
+ return {"title": title}
75
+
76
+
77
+ def render_spa(request: HttpRequest, title: object) -> HttpResponse:
78
+ """Render the SPA host template."""
79
+ return render(request, "fatanalysis/spa.html", spa_context(request, title))
80
+
81
+
82
+ def _weekday_labels() -> list[str]:
83
+ return [
84
+ str(_("Monday")),
85
+ str(_("Tuesday")),
86
+ str(_("Wednesday")),
87
+ str(_("Thursday")),
88
+ str(_("Friday")),
89
+ str(_("Saturday")),
90
+ str(_("Sunday")),
91
+ ]
92
+
93
+
94
+ def _period_summary(period: FatMonthPeriod, counts: dict[int, tuple[int, int]] | None = None) -> dict[str, Any]:
95
+ """Serialize a period; ``counts`` maps period id to (active, total) pilot counts."""
96
+ if counts is not None:
97
+ active, total = counts.get(period.pk, (0, 0))
98
+ else:
99
+ active, total = period.active_pilots_count, period.total_pilots_count
100
+ return {
101
+ "id": period.pk,
102
+ "label": period.label,
103
+ "year": period.year,
104
+ "month": period.month,
105
+ "short": f"{period.year}-{period.month:02d}",
106
+ "corporation_name": period.corporation_name,
107
+ "total_fats": period.total_fats,
108
+ "active_pilots": active,
109
+ "total_pilots": total,
110
+ "created_at": period.created_at.isoformat(),
111
+ "updated_at": period.updated_at.isoformat(),
112
+ "synced_by": period.synced_by.username if period.synced_by else "",
113
+ }
114
+
115
+
116
+ def _period_counts(periods: list[FatMonthPeriod]) -> dict[int, tuple[int, int]]:
117
+ """Active/total pilot counts for all periods in one pass (no N+1)."""
118
+ result: dict[int, list[int]] = {p.pk: [0, 0] for p in periods}
119
+ rows = FatEntry.objects.filter(period_id__in=result.keys()).values_list("period_id", "total_fats")
120
+ for period_id, fats in rows:
121
+ result[period_id][1] += 1
122
+ if fats > 0:
123
+ result[period_id][0] += 1
124
+ return {k: (v[0], v[1]) for k, v in result.items()}
125
+
126
+
127
+ def _config_payload(config: FatSyncConfig) -> dict[str, Any]:
128
+ """Serialize sync config without exposing the session cookie value."""
129
+
130
+ def iso(value: Any) -> str | None:
131
+ return value.isoformat() if value else None
132
+
133
+ return {
134
+ "corporation_id": config.corporation_id,
135
+ "corporation_name": config.corporation_name,
136
+ "source_url": config.source_url,
137
+ "user_agent": config.user_agent,
138
+ "session_cookie_configured": bool(config.session_cookie),
139
+ "last_sync_at": iso(config.last_sync_at),
140
+ "last_sync_status": config.last_sync_status,
141
+ "last_sync_log": config.last_sync_log,
142
+ "auto_sync_enabled": config.auto_sync_enabled,
143
+ "auto_sync_interval_hours": config.auto_sync_interval_hours,
144
+ "last_auto_sync_at": iso(config.last_auto_sync_at),
145
+ "last_auto_sync_status": config.last_auto_sync_status,
146
+ "last_auto_sync_message": config.last_auto_sync_message,
147
+ }
148
+
149
+
150
+ def _auto_sync_schedule(config: FatSyncConfig) -> dict[str, Any]:
151
+ """Refresh interval and the expected time of the next automatic sync (from the beat schedule)."""
152
+ from django_celery_beat.models import PeriodicTask
153
+
154
+ task = PeriodicTask.objects.filter(name=PERIODIC_TASK_NAME).only("last_run_at", "enabled").first()
155
+ last_run = (task.last_run_at if task else None) or config.last_auto_sync_at
156
+ interval = timedelta(hours=config.auto_sync_interval_hours)
157
+ enabled = config.auto_sync_enabled
158
+ next_run = last_run + interval if enabled and last_run else None
159
+ return {
160
+ "enabled": enabled,
161
+ "interval_hours": config.auto_sync_interval_hours,
162
+ "last_run_at": last_run.isoformat() if last_run else None,
163
+ "next_run_at": next_run.isoformat() if next_run else None,
164
+ "last_status": config.last_auto_sync_status,
165
+ }
166
+
167
+
168
+ def _month_choices() -> list[dict[str, Any]]:
169
+ return [{"value": i, "label": calendar.month_name[i]} for i in range(1, 13)]
170
+
171
+
172
+ def _sync_payload(config: FatSyncConfig) -> dict[str, Any]:
173
+ periods = list(FatMonthPeriod.objects.filter(corporation_id=config.corporation_id))
174
+ now = timezone.now()
175
+ return {
176
+ "config": _config_payload(config),
177
+ "periods_count": len(periods),
178
+ "months": _month_choices(),
179
+ "current_year": now.year,
180
+ "current_month": now.month,
181
+ }
182
+
183
+
184
+ @require_GET
185
+ @api_permission_required(BASIC)
186
+ def api_overview(request: HttpRequest) -> JsonResponse:
187
+ """Dashboard data for a time window (same aggregation as the classic index view)."""
188
+ window = request.GET.get("window", "90d")
189
+ config = FatSyncConfig.get_solo()
190
+ years = sorted(
191
+ set(
192
+ FatMonthPeriod.objects.filter(corporation_id=config.corporation_id)
193
+ .order_by()
194
+ .values_list("year", flat=True)
195
+ .distinct()
196
+ ),
197
+ reverse=True,
198
+ )
199
+ if not years:
200
+ years = [timezone.now().year]
201
+
202
+ agg = FatAggregationService.aggregate_data(corporation_id=config.corporation_id, window=window)
203
+ periods = agg["periods"]
204
+ pilots = [
205
+ {
206
+ "character_name": p["character_name"],
207
+ "character_id": p["character_id"],
208
+ "main_character_name": p["main_character_name"],
209
+ "is_main": p["is_main"],
210
+ "total_fats": p["total_fats"],
211
+ "avg_fats_per_month": p["avg_fats_per_month"],
212
+ "active_months": p["active_months"],
213
+ "period_values": p["period_values"],
214
+ "dynamic_values": p["dynamic_values"],
215
+ }
216
+ for p in agg["pilots"]
217
+ ]
218
+ return JsonResponse(
219
+ {
220
+ "window": window,
221
+ "available_years": years,
222
+ "can_manage": request.user.has_perm(MANAGE),
223
+ "corporation_name": config.corporation_name,
224
+ "auto_sync": _auto_sync_schedule(config),
225
+ "periods": [{"id": p.pk, "label": p.label, "short": f"{p.year}-{p.month:02d}"} for p in periods],
226
+ "dynamic_headers": agg["dynamic_headers"],
227
+ "pilots": pilots,
228
+ "total_fats": agg["total_fats"],
229
+ "active_pilots_count": agg["active_pilots_count"],
230
+ "member_count": agg["member_count"],
231
+ "active_member_count": agg["active_member_count"],
232
+ "participation_pct": agg["participation_pct"],
233
+ "avg_fats_per_month": agg["avg_fats_per_month"],
234
+ "avg_fats_per_active_pilot": agg["avg_fats_per_active_pilot"],
235
+ "avg_fats_per_member": agg["avg_fats_per_member"],
236
+ "trend_labels": agg["trend_labels"],
237
+ "trend_values": agg["trend_values"],
238
+ "ship_type_distribution": agg["ship_type_distribution"],
239
+ "fat_type_distribution": agg["fat_type_distribution"],
240
+ "fats_by_time_labels": agg["fats_by_time_labels"],
241
+ "fats_by_time_values": agg["fats_by_time_values"],
242
+ "fats_by_weekday_labels": agg["fats_by_weekday_labels"],
243
+ "fats_by_weekday_values": agg["fats_by_weekday_values"],
244
+ }
245
+ )
246
+
247
+
248
+ @require_GET
249
+ @api_permission_required(BASIC)
250
+ def api_player(request: HttpRequest, character_name: str) -> JsonResponse:
251
+ """Longitudinal participation of one pilot."""
252
+ entries = list(
253
+ FatEntry.objects.filter(character_name=character_name)
254
+ .select_related("period", "character")
255
+ .order_by("period__year", "period__month")
256
+ )
257
+ if not entries:
258
+ return JsonResponse(
259
+ {"error": _("No FAT participation data found for %(pilot)s.") % {"pilot": character_name}}, status=404
260
+ )
261
+
262
+ totals: dict[str, int] = {}
263
+ for entry in entries:
264
+ for key, value in entry.fat_details.items():
265
+ totals[key] = totals.get(key, 0) + value
266
+ headers = sorted(totals)
267
+ latest = entries[-1]
268
+ rows = [
269
+ {
270
+ "period_id": e.period_id,
271
+ "period_label": e.period.label,
272
+ "period_short": f"{e.period.year}-{e.period.month:02d}",
273
+ "total_fats": e.total_fats,
274
+ "dynamic_values": [e.fat_details.get(h, 0) for h in headers],
275
+ }
276
+ for e in entries
277
+ ]
278
+ return JsonResponse(
279
+ {
280
+ "character_name": character_name,
281
+ "is_main": latest.is_main,
282
+ "main_character_name": latest.main_character_name,
283
+ "total_fats": sum(e.total_fats for e in entries),
284
+ "active_periods_count": sum(1 for e in entries if e.total_fats > 0),
285
+ "total_periods_count": len(entries),
286
+ "dynamic_headers": headers,
287
+ "entries": rows,
288
+ "trend_labels": [r["period_label"] for r in rows],
289
+ "trend_totals": [r["total_fats"] for r in rows],
290
+ "pie_labels": [k for k in headers if totals[k] > 0],
291
+ "pie_values": [totals[k] for k in headers if totals[k] > 0],
292
+ }
293
+ )
294
+
295
+
296
+ @require_GET
297
+ @api_permission_required(BASIC)
298
+ def api_periods(request: HttpRequest) -> JsonResponse:
299
+ """All recorded periods for the configured corporation."""
300
+ config = FatSyncConfig.get_solo()
301
+ periods = list(
302
+ FatMonthPeriod.objects.filter(corporation_id=config.corporation_id)
303
+ .select_related("synced_by")
304
+ .order_by("-year", "-month")
305
+ )
306
+ counts = _period_counts(periods)
307
+ return JsonResponse(
308
+ {
309
+ "periods": [_period_summary(p, counts) for p in periods],
310
+ "can_manage": request.user.has_perm(MANAGE),
311
+ }
312
+ )
313
+
314
+
315
+ @require_GET
316
+ @api_permission_required(BASIC)
317
+ def api_period_detail(request: HttpRequest, period_id: int) -> JsonResponse:
318
+ """One monthly period with its entries and distributions."""
319
+ period = FatMonthPeriod.objects.select_related("synced_by").filter(pk=period_id).first()
320
+ if period is None:
321
+ return JsonResponse({"error": _("Period not found.")}, status=404)
322
+
323
+ entries = list(period.entries.order_by("-total_fats", "character_name"))
324
+ headers = sorted({k for e in entries for k in e.fat_details})
325
+ rows = [
326
+ {
327
+ "character_name": e.character_name,
328
+ "is_main": e.is_main,
329
+ "total_fats": e.total_fats,
330
+ "dynamic_values": [e.fat_details.get(h, 0) for h in headers],
331
+ }
332
+ for e in entries
333
+ ]
334
+
335
+ time_values = [int(period.fats_by_time.get(str(h), 0)) for h in range(24)] if period.fats_by_time else [0] * 24
336
+ weekday_values = (
337
+ [int(period.fats_by_weekday.get(d, 0)) for d in RAW_WEEKDAYS] if period.fats_by_weekday else [0] * 7
338
+ )
339
+ ships: dict[str, int] = {}
340
+ if period.fats_by_ship and isinstance(period.fats_by_ship, dict):
341
+ ranked = sorted(
342
+ ((k, int(v)) for k, v in period.fats_by_ship.items() if int(v) > 0), key=lambda x: x[1], reverse=True
343
+ )
344
+ for ship, count in ranked[:12]:
345
+ ships[ship] = count
346
+ other = sum(c for _name, c in ranked[12:])
347
+ if other > 0:
348
+ ships[str(_("Other Ships"))] = other
349
+
350
+ summary = _period_summary(period, {period.pk: (sum(1 for e in entries if e.total_fats > 0), len(entries))})
351
+ return JsonResponse(
352
+ {
353
+ "period": summary,
354
+ "can_manage": request.user.has_perm(MANAGE),
355
+ "dynamic_headers": headers,
356
+ "entries": rows,
357
+ "top_labels": [r["character_name"] for r in rows[:15]],
358
+ "top_values": [r["total_fats"] for r in rows[:15]],
359
+ "ship_type_distribution": ships,
360
+ "fats_by_time_labels": [f"{h:02d}:00" for h in range(24)],
361
+ "fats_by_time_values": time_values,
362
+ "fats_by_weekday_labels": _weekday_labels(),
363
+ "fats_by_weekday_values": weekday_values,
364
+ }
365
+ )
366
+
367
+
368
+ @require_POST
369
+ @api_permission_required(MANAGE)
370
+ def api_period_delete(request: HttpRequest, period_id: int) -> JsonResponse:
371
+ """Delete a period and all its entries."""
372
+ period = FatMonthPeriod.objects.filter(pk=period_id).first()
373
+ if period is None:
374
+ return JsonResponse({"error": _("Period not found.")}, status=404)
375
+ label = period.label
376
+ period.delete()
377
+ return JsonResponse(
378
+ {"ok": True, "message": _("Period %(label)s and all associated entries deleted.") % {"label": label}}
379
+ )
380
+
381
+
382
+ @require_GET
383
+ @api_permission_required(MANAGE)
384
+ def api_sync(request: HttpRequest) -> JsonResponse:
385
+ """Sync configuration, status and log."""
386
+ return JsonResponse(_sync_payload(FatSyncConfig.get_solo()))
387
+
388
+
389
+ def _config_form_data(config: FatSyncConfig, data: dict[str, Any]) -> dict[str, Any]:
390
+ """Merge posted values over the stored config; blank cookie keeps the stored one."""
391
+ merged = {
392
+ "corporation_id": data.get("corporation_id", config.corporation_id),
393
+ "corporation_name": data.get("corporation_name", config.corporation_name),
394
+ "source_url": data.get("source_url", config.source_url),
395
+ "user_agent": data.get("user_agent", config.user_agent),
396
+ "session_cookie": config.session_cookie,
397
+ }
398
+ if data.get("clear_session_cookie"):
399
+ merged["session_cookie"] = ""
400
+ elif str(data.get("session_cookie") or "").strip():
401
+ merged["session_cookie"] = str(data["session_cookie"]).strip()
402
+ return merged
403
+
404
+
405
+ @require_POST
406
+ @api_permission_required(MANAGE)
407
+ def api_sync_config(request: HttpRequest) -> JsonResponse:
408
+ """Save connection settings, optionally testing the connection afterwards."""
409
+ config = FatSyncConfig.get_solo()
410
+ data = _json_body(request)
411
+ form = FatSyncConfigForm(_config_form_data(config, data), instance=config)
412
+ if not form.is_valid():
413
+ return JsonResponse({"error": form_errors(form)}, status=400)
414
+ config = form.save()
415
+ payload = _sync_payload(config)
416
+ if data.get("test"):
417
+ success, msg = AfatScraperService(config=config).test_connection()
418
+ payload.update({"ok": success, "message": msg})
419
+ return JsonResponse(payload, status=200 if success else 400)
420
+ payload.update({"ok": True, "message": _("AFAT sync configuration updated successfully.")})
421
+ return JsonResponse(payload)
422
+
423
+
424
+ @require_POST
425
+ @api_permission_required(MANAGE)
426
+ def api_sync_month(request: HttpRequest) -> JsonResponse:
427
+ """Fetch and ingest a single month from INIT Auth."""
428
+ config = FatSyncConfig.get_solo()
429
+ form = FatSyncSingleMonthForm(_json_body(request))
430
+ if not form.is_valid():
431
+ return JsonResponse({"error": form_errors(form)}, status=400)
432
+ year = int(form.cleaned_data["year"])
433
+ month = int(form.cleaned_data["month"])
434
+ user = request.user if isinstance(request.user, User) else None
435
+ try:
436
+ period = AfatScraperService(config=config).sync_month(year, month, synced_by=user)
437
+ except Exception as exc: # noqa: BLE001 - surface any scraper failure to the director
438
+ logger.exception("Scraper fetch error for single month: %s", exc)
439
+ return JsonResponse({"error": _("Scraper error: %(err)s") % {"err": str(exc)}}, status=502)
440
+ if period is None:
441
+ return JsonResponse(
442
+ {
443
+ "ok": True,
444
+ "period_id": None,
445
+ "message": _("No pilot records found on INIT Auth for %(month)s/%(year)s.")
446
+ % {"month": month, "year": year},
447
+ **_sync_payload(FatSyncConfig.get_solo()),
448
+ }
449
+ )
450
+ return JsonResponse(
451
+ {
452
+ "ok": True,
453
+ "period_id": period.pk,
454
+ "message": _("Successfully fetched and ingested %(count)s records for %(period)s (%(total)s total FATs).")
455
+ % {"count": period.entries.count(), "period": period.label, "total": period.total_fats},
456
+ **_sync_payload(FatSyncConfig.get_solo()),
457
+ }
458
+ )
459
+
460
+
461
+ @require_POST
462
+ @api_permission_required(MANAGE)
463
+ def api_sync_bulk(request: HttpRequest) -> JsonResponse:
464
+ """Crawl all historical periods from INIT Auth."""
465
+ config = FatSyncConfig.get_solo()
466
+ form = FatSyncBulkForm(_json_body(request))
467
+ if not form.is_valid():
468
+ return JsonResponse({"error": form_errors(form)}, status=400)
469
+ user = request.user if isinstance(request.user, User) else None
470
+ try:
471
+ summary = AfatScraperService(config=config).crawl_all_periods(
472
+ start_year=int(form.cleaned_data["start_year"]),
473
+ end_year=int(form.cleaned_data["end_year"]),
474
+ end_month=int(form.cleaned_data["end_month"]),
475
+ synced_by=user,
476
+ )
477
+ except Exception as exc: # noqa: BLE001
478
+ logger.exception("Bulk sync crawler error: %s", exc)
479
+ return JsonResponse({"error": _("Bulk sync error: %(err)s") % {"err": str(exc)}}, status=502)
480
+ return JsonResponse(
481
+ {
482
+ "ok": True,
483
+ "message": _(
484
+ "Initial bulk sync completed: %(ingested)s monthly periods ingested "
485
+ "(%(total)s total FATs), %(skipped)s skipped without records."
486
+ )
487
+ % {
488
+ "ingested": summary["ingested_periods"],
489
+ "total": summary["total_fats"],
490
+ "skipped": summary["skipped_periods"],
491
+ },
492
+ **_sync_payload(FatSyncConfig.get_solo()),
493
+ }
494
+ )
495
+
496
+
497
+ @require_POST
498
+ @api_permission_required(MANAGE)
499
+ def api_sync_auto(request: HttpRequest) -> JsonResponse:
500
+ """Save the automatic sync switch and interval."""
501
+ config = FatSyncConfig.get_solo()
502
+ data = _json_body(request)
503
+ form = FatAutoSyncForm(
504
+ {
505
+ "auto_sync_enabled": data.get("auto_sync_enabled", False) or "",
506
+ "auto_sync_interval_hours": data.get("auto_sync_interval_hours", config.auto_sync_interval_hours),
507
+ },
508
+ instance=config,
509
+ )
510
+ if not form.is_valid():
511
+ return JsonResponse({"error": form_errors(form)}, status=400)
512
+ config = form.save()
513
+ ensure_auto_sync_schedule(config)
514
+ if config.auto_sync_enabled:
515
+ message = _("Automatic sync runs every %(hours)s hours.") % {"hours": config.auto_sync_interval_hours}
516
+ else:
517
+ message = _("Automatic sync is switched off.")
518
+ return JsonResponse({"ok": True, "message": message, **_sync_payload(config)})
519
+
520
+
521
+ @require_POST
522
+ @api_permission_required(MANAGE)
523
+ def api_sync_log_clear(request: HttpRequest) -> JsonResponse:
524
+ """Clear the sync activity log."""
525
+ config = FatSyncConfig.get_solo()
526
+ config.last_sync_log = ""
527
+ config.save(update_fields=["last_sync_log"])
528
+ return JsonResponse({"ok": True, "message": _("Sync log cleared."), **_sync_payload(config)})