doorcontrol: Add change vs previous unit time to "Access per x" reports

This commit is contained in:
Adam Goldsmith 2023-12-01 11:53:16 -05:00
parent a177ff1ed6
commit 654d5e34bd

View File

@ -12,6 +12,9 @@ from django.utils.formats import date_format
from django.utils.text import slugify
from django.utils.timezone import localtime
from django.views.generic.list import ListView
from django.db.models import Window, F, FloatField
from django.db.models.functions import Lead
from .models import HIDEvent
@ -149,16 +152,45 @@ class AccessPerUnitTime(BaseAccessReport):
.values(unit_time=Trunc("timestamp", unit_time))
.annotate(
members=Count("cardholder_id", distinct=True),
members_delta=(
F("members")
/ Window(
Lead("members"),
order_by="-unit_time",
output_field=FloatField(),
)
* 100
- 100
),
access_count=Count("cardholder_id"),
access_count_delta=(
F("access_count")
/ Window(
Lead("access_count"),
order_by="-unit_time",
output_field=FloatField(),
)
* 100
- 100
),
)
.order_by("-unit_time")
.values("unit_time", "members", "access_count")
)
return [
{
unit_time: self._format_date(event["unit_time"]),
"members": event["members"],
"Δ members": (
f'{event["members_delta"]:.2f}%'
if event["members_delta"] is not None
else ""
),
"access count": event["access_count"],
"Δ access count": (
f'{event["access_count_delta"]:.2f}%'
if event["access_count_delta"] is not None
else ""
),
}
for event in events
]