2023-04-08 10:28:44 -04:00
|
|
|
import datetime
|
2024-12-11 13:03:37 -05:00
|
|
|
import itertools
|
|
|
|
from typing import TYPE_CHECKING, Any
|
2023-01-24 21:21:26 -05:00
|
|
|
|
2024-12-11 13:03:37 -05:00
|
|
|
from django.conf import settings
|
2023-04-08 10:28:44 -04:00
|
|
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
2024-08-26 23:45:39 -04:00
|
|
|
from django.contrib.postgres.aggregates import StringAgg
|
2023-04-08 10:28:44 -04:00
|
|
|
from django.core.exceptions import BadRequest
|
2024-08-26 23:45:39 -04:00
|
|
|
from django.db.models import Count, F, FloatField, Func, Q, Value, Window
|
2024-08-29 13:15:50 -04:00
|
|
|
from django.db.models.functions import Lead, NullIf, Trunc
|
2024-12-11 13:03:37 -05:00
|
|
|
from django.http import Http404, HttpRequest, HttpResponse
|
|
|
|
from django.shortcuts import render
|
2024-01-17 21:17:24 -05:00
|
|
|
from django.urls import path, reverse_lazy
|
2023-04-08 10:28:44 -04:00
|
|
|
from django.utils.text import slugify
|
2024-12-11 13:03:37 -05:00
|
|
|
from django.views.generic import TemplateView
|
2023-04-08 10:28:44 -04:00
|
|
|
from django.views.generic.list import ListView
|
|
|
|
|
2024-01-26 13:58:14 -05:00
|
|
|
import django_filters
|
2024-12-11 13:03:37 -05:00
|
|
|
import django_q.tasks as q2_tasks
|
2024-01-22 22:58:07 -05:00
|
|
|
import django_tables2 as tables
|
2024-01-26 13:58:14 -05:00
|
|
|
from django_filters.views import BaseFilterView
|
2024-01-22 22:58:07 -05:00
|
|
|
from django_tables2 import SingleTableMixin
|
|
|
|
from django_tables2.export.views import ExportMixin
|
2024-12-11 13:03:37 -05:00
|
|
|
from pydantic import BaseModel, Field, ValidationError
|
|
|
|
from unifi_access import AccessClient, ResponseCode, UnifiAccessError
|
|
|
|
from unifi_access.schemas import (
|
|
|
|
FullUser,
|
|
|
|
NfcCard,
|
|
|
|
NfcCardEnrollmentSessionId,
|
|
|
|
NfcCardEnrollmentStatus,
|
|
|
|
User,
|
|
|
|
UserId,
|
|
|
|
UserStatus,
|
|
|
|
)
|
2024-01-22 22:58:07 -05:00
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
from .models import Door, HIDEvent
|
2024-04-18 11:30:18 -04:00
|
|
|
from .tables import (
|
|
|
|
BusiestDayOfWeekTable,
|
|
|
|
BusiestTimeOfDayTable,
|
|
|
|
DeniedAccessTable,
|
|
|
|
DetailByDayTable,
|
|
|
|
MostActiveMembersTable,
|
|
|
|
UnitTimeTable,
|
|
|
|
)
|
2023-04-08 10:28:44 -04:00
|
|
|
|
2024-08-07 14:09:42 -04:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from django.core.paginator import Page
|
|
|
|
|
2023-11-30 12:06:16 -05:00
|
|
|
REPORTS = []
|
2023-04-08 10:28:44 -04:00
|
|
|
|
|
|
|
|
2024-05-04 16:38:51 -04:00
|
|
|
def register_report(cls: "type[BaseAccessReport]"):
|
2023-11-30 12:06:16 -05:00
|
|
|
REPORTS.append(cls)
|
2023-04-08 10:28:44 -04:00
|
|
|
return cls
|
|
|
|
|
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
class AccessReportFilterSet(django_filters.FilterSet):
|
2024-01-26 13:58:14 -05:00
|
|
|
timestamp = django_filters.DateFromToRangeFilter()
|
2024-02-08 10:47:32 -05:00
|
|
|
door = django_filters.ModelMultipleChoiceFilter(
|
|
|
|
queryset=Door.objects.all(), distinct=False
|
|
|
|
)
|
2024-01-26 13:58:14 -05:00
|
|
|
|
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
class BaseAccessReport(
|
2024-01-26 13:58:14 -05:00
|
|
|
BaseFilterView, ExportMixin, SingleTableMixin, PermissionRequiredMixin, ListView
|
2024-01-22 22:58:07 -05:00
|
|
|
):
|
2023-04-08 10:28:44 -04:00
|
|
|
model = HIDEvent
|
|
|
|
permission_required = "doorcontrol.view_hidevent"
|
|
|
|
paginate_by = 20
|
|
|
|
context_object_name = "object_list"
|
|
|
|
template_name = "doorcontrol/access_report.dj.html"
|
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
export_formats = ("csv", "xlsx", "ods")
|
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
filterset_class = AccessReportFilterSet
|
2024-01-26 13:58:14 -05:00
|
|
|
|
2024-05-04 16:38:51 -04:00
|
|
|
_report_name: str
|
2023-04-08 10:28:44 -04:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _report_types(cls):
|
|
|
|
yield [
|
|
|
|
cls._report_name,
|
|
|
|
reverse_lazy("doorcontrol:" + slugify(cls._report_name)),
|
|
|
|
]
|
|
|
|
|
2023-11-30 12:06:16 -05:00
|
|
|
@classmethod
|
|
|
|
def _urlpattern(cls):
|
|
|
|
slug = slugify(cls._report_name)
|
|
|
|
return path(f"reports/{slug}", cls.as_view(), name=slug)
|
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
@property
|
|
|
|
def export_name(self):
|
|
|
|
return slugify(self._report_name)
|
|
|
|
|
2023-04-08 10:28:44 -04:00
|
|
|
def _selected_report(self):
|
|
|
|
return self._report_name
|
|
|
|
|
2024-05-04 16:38:51 -04:00
|
|
|
def get_paginate_by(self, queryset) -> int | None:
|
2023-04-08 10:28:44 -04:00
|
|
|
if "items_per_page" in self.request.GET:
|
2024-05-04 16:38:51 -04:00
|
|
|
return int(self.request.GET["items_per_page"])
|
2023-04-08 10:28:44 -04:00
|
|
|
return super().get_paginate_by(queryset)
|
|
|
|
|
|
|
|
def get_queryset(self):
|
2024-01-26 13:58:14 -05:00
|
|
|
return super().get_queryset().select_related("door")
|
2023-04-08 10:28:44 -04:00
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super().get_context_data(**kwargs)
|
2023-11-30 12:06:16 -05:00
|
|
|
context["report_types"] = [
|
|
|
|
rt for report in REPORTS for rt in report._report_types()
|
|
|
|
]
|
2023-04-08 10:28:44 -04:00
|
|
|
|
|
|
|
page: Page = context["page_obj"]
|
|
|
|
context["paginator_range"] = page.paginator.get_elided_page_range(page.number)
|
|
|
|
context["selected_report"] = self._selected_report()
|
|
|
|
context["items_per_page"] = self.get_paginate_by(None)
|
|
|
|
|
|
|
|
return context
|
|
|
|
|
|
|
|
|
|
|
|
@register_report
|
|
|
|
class AccessPerUnitTime(BaseAccessReport):
|
2024-01-22 22:58:07 -05:00
|
|
|
table_class = UnitTimeTable
|
2023-04-08 10:28:44 -04:00
|
|
|
UNIT_TIMES = ["day", "week", "month", "year"]
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _report_types(cls):
|
|
|
|
for unit_time in cls.UNIT_TIMES:
|
|
|
|
yield (
|
|
|
|
"Access per " + unit_time.title(),
|
|
|
|
reverse_lazy("doorcontrol:access-per-unit-time", args=[unit_time]),
|
|
|
|
)
|
|
|
|
|
2023-11-30 12:06:16 -05:00
|
|
|
@classmethod
|
|
|
|
def _urlpattern(cls):
|
|
|
|
return path(
|
|
|
|
"reports/access-per-<unit_time>",
|
|
|
|
cls.as_view(),
|
|
|
|
name="access-per-unit-time",
|
|
|
|
)
|
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
@property
|
|
|
|
def _report_name(self):
|
|
|
|
unit_time = self.kwargs["unit_time"]
|
|
|
|
return "Access per " + unit_time.title()
|
|
|
|
|
2023-04-08 10:28:44 -04:00
|
|
|
def _selected_report(self) -> str:
|
|
|
|
return "Access per " + self.kwargs["unit_time"].title()
|
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
def get_table_kwargs(self):
|
2023-04-08 10:28:44 -04:00
|
|
|
unit_time = self.kwargs["unit_time"]
|
2024-01-22 22:58:07 -05:00
|
|
|
if unit_time == "week":
|
|
|
|
unit_time_column = tables.TemplateColumn(
|
|
|
|
verbose_name=unit_time.title(),
|
|
|
|
template_code=(
|
|
|
|
"{{ value|date|default:default }} - "
|
|
|
|
"{{ value|add:one_week|date|default:default }}"
|
|
|
|
),
|
|
|
|
extra_context={"one_week": datetime.timedelta(weeks=1)},
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
if unit_time == "day":
|
|
|
|
date_format = "DATE_FORMAT"
|
|
|
|
elif unit_time == "month":
|
|
|
|
date_format = "N Y"
|
|
|
|
elif unit_time == "year":
|
|
|
|
date_format = "Y"
|
|
|
|
|
|
|
|
unit_time_column = tables.DateColumn(
|
|
|
|
date_format, verbose_name=unit_time.title()
|
2023-04-08 10:28:44 -04:00
|
|
|
)
|
2024-01-22 22:58:07 -05:00
|
|
|
|
|
|
|
return {
|
|
|
|
"sequence": ("unit_time", "..."),
|
|
|
|
"extra_columns": (("unit_time", unit_time_column),),
|
|
|
|
}
|
2023-04-08 10:28:44 -04:00
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
def get_table_data(self):
|
2023-04-08 10:28:44 -04:00
|
|
|
unit_time = self.kwargs["unit_time"]
|
|
|
|
if unit_time not in self.UNIT_TIMES:
|
|
|
|
raise BadRequest("unit time must be one of day, week, month, or year")
|
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
return (
|
2023-04-08 10:28:44 -04:00
|
|
|
super()
|
2024-02-08 10:47:32 -05:00
|
|
|
.get_table_data()
|
2024-05-13 00:38:01 -04:00
|
|
|
.filter(event_type__in=HIDEvent.EventType.any_granted_access())
|
2024-02-09 11:59:52 -05:00
|
|
|
.with_member_id()
|
2023-04-08 10:28:44 -04:00
|
|
|
.values(unit_time=Trunc("timestamp", unit_time))
|
|
|
|
.annotate(
|
2024-02-09 11:59:52 -05:00
|
|
|
members=Count("member_id", distinct=True),
|
2023-12-01 11:53:16 -05:00
|
|
|
members_delta=(
|
|
|
|
F("members")
|
|
|
|
/ Window(
|
2024-08-29 13:15:50 -04:00
|
|
|
Lead(NullIf("members", 0.0)),
|
2023-12-01 11:53:16 -05:00
|
|
|
order_by="-unit_time",
|
|
|
|
output_field=FloatField(),
|
|
|
|
)
|
|
|
|
* 100
|
|
|
|
- 100
|
|
|
|
),
|
2023-04-08 10:28:44 -04:00
|
|
|
access_count=Count("cardholder_id"),
|
2023-12-01 11:53:16 -05:00
|
|
|
access_count_delta=(
|
|
|
|
F("access_count")
|
|
|
|
/ Window(
|
2024-08-29 13:15:50 -04:00
|
|
|
Lead(NullIf("access_count", 0.0)),
|
2023-12-01 11:53:16 -05:00
|
|
|
order_by="-unit_time",
|
|
|
|
output_field=FloatField(),
|
|
|
|
)
|
|
|
|
* 100
|
|
|
|
- 100
|
|
|
|
),
|
2023-04-08 10:28:44 -04:00
|
|
|
)
|
|
|
|
.order_by("-unit_time")
|
|
|
|
)
|
2024-01-22 22:58:07 -05:00
|
|
|
|
|
|
|
|
2023-04-08 10:28:44 -04:00
|
|
|
@register_report
|
|
|
|
class DeniedAccess(BaseAccessReport):
|
|
|
|
_report_name = "Denied Access"
|
2024-01-22 22:58:07 -05:00
|
|
|
table_class = DeniedAccessTable
|
2023-04-08 10:28:44 -04:00
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
def get_table_data(self):
|
2023-04-08 10:28:44 -04:00
|
|
|
denied_event_types = [
|
|
|
|
t for t in HIDEvent.EventType if t.name.startswith("DENIED_ACCESS")
|
|
|
|
]
|
2024-08-26 23:23:53 -04:00
|
|
|
return super().get_table_data().filter(event_type__in=denied_event_types)
|
2023-04-08 10:28:44 -04:00
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
|
2023-04-08 10:28:44 -04:00
|
|
|
@register_report
|
|
|
|
class MostActiveMembers(BaseAccessReport):
|
|
|
|
_report_name = "Most Active Members"
|
2024-01-22 22:58:07 -05:00
|
|
|
table_class = MostActiveMembersTable
|
2023-04-08 10:28:44 -04:00
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
def get_table_data(self):
|
2024-01-22 22:58:07 -05:00
|
|
|
return (
|
2023-04-08 10:28:44 -04:00
|
|
|
super()
|
2024-02-08 10:47:32 -05:00
|
|
|
.get_table_data()
|
2024-02-09 11:59:52 -05:00
|
|
|
.with_member_id()
|
|
|
|
.filter(member_id__isnull=False)
|
|
|
|
.values("member_id")
|
|
|
|
.annotate(
|
|
|
|
access_count=Count("member_id"),
|
2024-08-26 23:45:39 -04:00
|
|
|
name=StringAgg(
|
|
|
|
Func(Value(" "), "forename", "surname", function="concat_ws"),
|
|
|
|
", ",
|
|
|
|
distinct=True,
|
2024-02-09 11:59:52 -05:00
|
|
|
),
|
|
|
|
)
|
2023-04-08 10:28:44 -04:00
|
|
|
.order_by("-access_count")
|
|
|
|
)
|
|
|
|
|
2024-01-22 22:58:07 -05:00
|
|
|
|
2024-02-09 12:16:30 -05:00
|
|
|
@register_report
|
|
|
|
class DetailByDay(BaseAccessReport):
|
|
|
|
_report_name = "Detail by Day"
|
|
|
|
table_class = DetailByDayTable
|
|
|
|
|
|
|
|
def get_table_data(self):
|
|
|
|
return (
|
|
|
|
super()
|
|
|
|
.get_table_data()
|
|
|
|
.with_member_id()
|
|
|
|
.values("timestamp__date", "member_id")
|
|
|
|
.filter(member_id__isnull=False)
|
|
|
|
.annotate(
|
|
|
|
access_count=Count("member_id"),
|
2024-05-13 00:38:01 -04:00
|
|
|
granted_access_count=Count(
|
|
|
|
"member_id",
|
|
|
|
filter=Q(event_type__in=HIDEvent.EventType.any_granted_access()),
|
|
|
|
),
|
2024-08-26 23:45:39 -04:00
|
|
|
name=StringAgg(
|
|
|
|
Func(Value(" "), "forename", "surname", function="concat_ws"),
|
|
|
|
", ",
|
|
|
|
distinct=True,
|
2024-02-09 12:16:30 -05:00
|
|
|
),
|
|
|
|
)
|
|
|
|
.order_by("-timestamp__date")
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2023-11-30 12:06:16 -05:00
|
|
|
@register_report
|
|
|
|
class BusiestDayOfWeek(BaseAccessReport):
|
|
|
|
_report_name = "Busiest Day of the Week"
|
2024-01-22 22:58:07 -05:00
|
|
|
table_pagination = False
|
|
|
|
table_class = BusiestDayOfWeekTable
|
2023-11-30 12:06:16 -05:00
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
def get_table_data(self):
|
2024-01-22 22:58:07 -05:00
|
|
|
return (
|
|
|
|
super()
|
2024-02-08 10:47:32 -05:00
|
|
|
.get_table_data()
|
2024-02-09 12:20:01 -05:00
|
|
|
.with_member_id()
|
2023-11-30 12:06:16 -05:00
|
|
|
.values("timestamp__week_day")
|
2024-02-09 12:20:01 -05:00
|
|
|
.annotate(
|
|
|
|
events=Count("timestamp"), members=Count("member_id", distinct=True)
|
|
|
|
)
|
2024-01-22 22:58:07 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2023-11-30 12:06:16 -05:00
|
|
|
@register_report
|
|
|
|
class BusiestTimeOfDay(BaseAccessReport):
|
|
|
|
_report_name = "Busiest Time of Day"
|
2024-01-22 22:58:07 -05:00
|
|
|
table_pagination = False
|
|
|
|
table_class = BusiestTimeOfDayTable
|
2023-11-30 12:06:16 -05:00
|
|
|
|
2024-02-08 10:47:32 -05:00
|
|
|
def get_table_data(self):
|
2024-01-22 22:58:07 -05:00
|
|
|
return (
|
|
|
|
super()
|
2024-02-08 10:47:32 -05:00
|
|
|
.get_table_data()
|
2024-02-09 12:20:01 -05:00
|
|
|
.with_member_id()
|
2023-11-30 12:06:16 -05:00
|
|
|
.values("timestamp__hour")
|
2024-02-09 12:20:01 -05:00
|
|
|
.annotate(
|
|
|
|
events=Count("timestamp"), members=Count("member_id", distinct=True)
|
|
|
|
)
|
2024-01-22 22:58:07 -05:00
|
|
|
)
|
2024-12-11 13:03:37 -05:00
|
|
|
|
|
|
|
|
|
|
|
def update_access_users() -> list[FullUser]:
|
|
|
|
access_client = AccessClient(
|
|
|
|
settings.UNIFI_ACCESS_HOST, settings.UNIFI_ACCESS_API_TOKEN, verify=False
|
|
|
|
)
|
|
|
|
return list(access_client.fetch_all_users__unpaged())
|
|
|
|
|
|
|
|
|
|
|
|
def assign_nfc_card_user_selector(request: HttpRequest):
|
|
|
|
template_name = "doorcontrol/assign_nfc_card_user_selector.dj.html"
|
|
|
|
task_group = "update_access_users"
|
|
|
|
|
|
|
|
all_users: list[FullUser] | None = None
|
|
|
|
refresh_task_id = None
|
|
|
|
update_users_results = q2_tasks.result_group(task_group, cached=True)
|
|
|
|
if (
|
|
|
|
update_users_results
|
|
|
|
and len(update_users_results) > 0
|
|
|
|
and not request.POST.get("force_refresh")
|
|
|
|
):
|
|
|
|
all_users = update_users_results[0]
|
|
|
|
else:
|
|
|
|
q2_tasks.delete_group(task_group)
|
|
|
|
refresh_task_id = q2_tasks.async_task(
|
|
|
|
update_access_users, group=task_group, cached=5 * 60
|
|
|
|
)
|
|
|
|
|
|
|
|
filtered_users = []
|
|
|
|
|
|
|
|
if request.method == "POST":
|
|
|
|
if refresh_task_id:
|
|
|
|
all_users = q2_tasks.result(refresh_task_id, wait=-1, cached=True)
|
|
|
|
|
|
|
|
template_name += "#results"
|
|
|
|
all_filtered_users = (
|
|
|
|
user
|
|
|
|
for user in all_users or []
|
|
|
|
if user.status == UserStatus.ACTIVE
|
|
|
|
and request.POST.get("search", "").lower() in user.full_name.lower()
|
|
|
|
)
|
|
|
|
filtered_users = list(itertools.islice(all_filtered_users, 10))
|
|
|
|
|
|
|
|
return render(request, template_name, {"users": filtered_users})
|
|
|
|
|
|
|
|
|
|
|
|
class AssignNfcCardStatus(BaseModel):
|
|
|
|
class ErrorEntry(BaseModel):
|
|
|
|
count: int
|
|
|
|
code: ResponseCode | None
|
|
|
|
msg: str
|
|
|
|
extra_details: str | None
|
|
|
|
|
|
|
|
session_id: NfcCardEnrollmentSessionId | None = None
|
|
|
|
last_status: NfcCardEnrollmentStatus | None = None
|
|
|
|
errors: list[ErrorEntry] = Field(default_factory=list)
|
|
|
|
card: NfcCard | None = None
|
|
|
|
user: User
|
|
|
|
|
|
|
|
def append_error(
|
|
|
|
self, error: UnifiAccessError, extra_details: str | None = None
|
|
|
|
) -> None:
|
|
|
|
if self.errors and self.errors[-1].code == error.code:
|
|
|
|
self.errors[-1].count += 1
|
|
|
|
else:
|
|
|
|
self.errors.append(
|
|
|
|
self.ErrorEntry(
|
|
|
|
count=1,
|
|
|
|
code=error.code,
|
|
|
|
msg=error.msg,
|
|
|
|
extra_details=extra_details,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
def append_raw_error(self, msg: str, extra_details: str | None = None) -> None:
|
|
|
|
self.errors.append(
|
|
|
|
self.ErrorEntry(
|
|
|
|
count=1,
|
|
|
|
code=None,
|
|
|
|
msg=msg,
|
|
|
|
extra_details=extra_details,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class AssignNfcCardView(TemplateView):
|
|
|
|
# for storage in request.session
|
|
|
|
ENROLLMENT_STATUS_SESSION_KEY = "unifi_access_enrollment_status"
|
|
|
|
|
|
|
|
template_name = "doorcontrol/assign_nfc_card.dj.html"
|
|
|
|
|
|
|
|
def get_template_names(self) -> list[str]:
|
|
|
|
templates = super().get_template_names()
|
|
|
|
if (
|
|
|
|
self.request.method == "GET" and (part := self.request.GET.get("part"))
|
|
|
|
) or (
|
|
|
|
self.request.method == "POST" and (part := self.request.POST.get("part"))
|
|
|
|
):
|
|
|
|
return [f"{template_name}#{part}" for template_name in templates]
|
|
|
|
else:
|
|
|
|
return templates
|
|
|
|
|
|
|
|
def setup(self, request: HttpRequest, *args: Any, **kwargs: Any) -> None:
|
|
|
|
super().setup(request, *args, **kwargs)
|
|
|
|
|
|
|
|
self.access_client = AccessClient(
|
|
|
|
settings.UNIFI_ACCESS_HOST, settings.UNIFI_ACCESS_API_TOKEN, verify=False
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
status = AssignNfcCardStatus.model_validate(
|
|
|
|
request.session.get(self.ENROLLMENT_STATUS_SESSION_KEY, "{}")
|
|
|
|
)
|
|
|
|
except ValidationError:
|
|
|
|
status = None
|
|
|
|
|
|
|
|
if status is None or status.user.id != self.kwargs["user_id"]:
|
|
|
|
try:
|
|
|
|
user = self.access_client.fetch_user(UserId(self.kwargs["user_id"]))
|
|
|
|
except UnifiAccessError as e:
|
|
|
|
if e.code == ResponseCode.USER_ACCOUNT_NOT_EXIST:
|
|
|
|
raise Http404(
|
|
|
|
"No account with that id exists in UniFi Access"
|
|
|
|
) from e
|
|
|
|
else:
|
|
|
|
raise e
|
|
|
|
status = AssignNfcCardStatus(user=user)
|
|
|
|
self.status = status
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs: Any) -> dict[str, Any]:
|
|
|
|
self.request.session[self.ENROLLMENT_STATUS_SESSION_KEY] = (
|
|
|
|
self.status.model_dump()
|
|
|
|
)
|
|
|
|
return super().get_context_data(**kwargs) | self.status.model_dump()
|
|
|
|
|
|
|
|
def get(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
|
|
|
# poll an in-progress session
|
|
|
|
if self.status.session_id:
|
|
|
|
try:
|
|
|
|
self.status.last_status = self.access_client.fetch_enroll_card_status(
|
|
|
|
self.status.session_id
|
|
|
|
)
|
|
|
|
self.status.card = self.access_client.fetch_nfc_card(
|
|
|
|
self.status.last_status.token
|
|
|
|
)
|
|
|
|
|
|
|
|
self.access_client.remove_enrollment_session(self.status.session_id)
|
|
|
|
self.status.session_id = None
|
|
|
|
|
|
|
|
except UnifiAccessError as e:
|
|
|
|
match e.code:
|
|
|
|
case ResponseCode.CREDS_NFC_READ_SESSION_NOT_FOUND:
|
|
|
|
self.status.session_id = None
|
|
|
|
case ResponseCode.CREDS_NFC_READ_POLL_TOKEN_EMPTY:
|
|
|
|
# all is well, the reader just hasn't seen a card yet
|
|
|
|
pass
|
|
|
|
case ResponseCode.CREDS_NFC_CARD_IS_PROVISION:
|
|
|
|
self.status.session_id = None
|
|
|
|
self.status.append_error(
|
|
|
|
e,
|
|
|
|
"This card will need to be added by someone with admin access to the UniFi Access application",
|
|
|
|
)
|
|
|
|
case _:
|
|
|
|
self.status.append_error(e)
|
|
|
|
|
|
|
|
return super().get(request, *args, **kwargs)
|
|
|
|
|
|
|
|
def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
|
|
|
if "assign" in request.POST:
|
|
|
|
if not self.status.last_status:
|
|
|
|
self.status.append_raw_error(
|
|
|
|
"Missing session status. Please start a new session and try again."
|
|
|
|
)
|
|
|
|
elif request.POST.get("id") != self.status.last_status.id:
|
|
|
|
self.status.append_raw_error(
|
|
|
|
"Mismatched session status. Please start a new session and try again."
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
self.access_client.assign_nfc_card_to_user(
|
|
|
|
self.status.user.id, self.status.last_status.token
|
|
|
|
)
|
|
|
|
self.status.card = self.access_client.fetch_nfc_card(
|
|
|
|
self.status.last_status.token
|
|
|
|
)
|
|
|
|
except UnifiAccessError as e:
|
|
|
|
self.status.append_error(e)
|
|
|
|
|
|
|
|
else:
|
|
|
|
# remove old session, if it exists
|
|
|
|
if self.status.session_id:
|
|
|
|
self.access_client.remove_enrollment_session(self.status.session_id)
|
|
|
|
|
|
|
|
# start a new session
|
|
|
|
self.status = AssignNfcCardStatus(user=self.status.user)
|
|
|
|
self.status.session_id = self.access_client.begin_enroll_card(
|
|
|
|
settings.UNIFI_ACCESS_CARD_ASSIGNMENT_DEVICE
|
|
|
|
).session_id
|
|
|
|
|
|
|
|
return super().get(request, *args, **kwargs)
|