2023-01-03 20:36:34 +00:00
|
|
|
import contextlib
|
|
|
|
|
2023-01-14 22:33:58 +00:00
|
|
|
from django.db.models import Exists
|
|
|
|
from django.db.models import OuterRef
|
2023-01-03 20:36:34 +00:00
|
|
|
from django.utils import timezone
|
2023-01-02 22:06:00 +00:00
|
|
|
|
2023-01-03 20:36:34 +00:00
|
|
|
from membership.models import Member
|
2023-01-02 22:06:00 +00:00
|
|
|
from membership.models import Membership
|
|
|
|
from membership.models import SubscriptionPeriod
|
|
|
|
|
|
|
|
|
2023-01-14 22:33:58 +00:00
|
|
|
def get_subscription_periods(member: Member | None = None) -> list[SubscriptionPeriod]:
|
2023-01-02 22:06:00 +00:00
|
|
|
subscription_periods = SubscriptionPeriod.objects.prefetch_related(
|
|
|
|
"membership_set",
|
|
|
|
"membership_set__user",
|
|
|
|
).all()
|
2023-01-14 22:33:58 +00:00
|
|
|
|
|
|
|
if member:
|
|
|
|
subscription_periods = subscription_periods.annotate(
|
|
|
|
membership_exists=Exists(
|
|
|
|
Membership.objects.filter(
|
|
|
|
user=member,
|
|
|
|
period=OuterRef("pk"),
|
|
|
|
),
|
|
|
|
),
|
2023-09-30 06:14:02 +00:00
|
|
|
).filter(membership_exists=True)
|
2023-01-14 22:33:58 +00:00
|
|
|
|
2023-01-02 22:06:00 +00:00
|
|
|
return list(subscription_periods)
|
|
|
|
|
|
|
|
|
2023-01-03 20:36:34 +00:00
|
|
|
def get_current_subscription_period() -> SubscriptionPeriod | None:
|
|
|
|
with contextlib.suppress(SubscriptionPeriod.DoesNotExist):
|
|
|
|
return SubscriptionPeriod.objects.prefetch_related(
|
2023-01-11 20:55:58 +00:00
|
|
|
"membership_set",
|
|
|
|
"membership_set__user",
|
2023-01-03 20:36:34 +00:00
|
|
|
).get(period__contains=timezone.now())
|
|
|
|
|
|
|
|
|
2023-01-02 22:06:00 +00:00
|
|
|
def get_memberships(
|
2023-01-11 20:55:58 +00:00
|
|
|
*,
|
2023-01-14 22:33:58 +00:00
|
|
|
member: Member | None = None,
|
2023-01-11 20:55:58 +00:00
|
|
|
period: SubscriptionPeriod | None = None,
|
2023-01-02 22:06:00 +00:00
|
|
|
) -> Membership.QuerySet:
|
|
|
|
memberships = Membership.objects.select_related("membership_type").all()
|
|
|
|
|
2023-01-14 22:33:58 +00:00
|
|
|
if member:
|
|
|
|
memberships = memberships.for_member(member=member)
|
2023-01-02 22:06:00 +00:00
|
|
|
|
|
|
|
if period:
|
|
|
|
memberships = memberships.filter(period=period)
|
|
|
|
|
|
|
|
return memberships
|
2023-01-03 16:00:07 +00:00
|
|
|
|
|
|
|
|
2023-01-03 20:36:34 +00:00
|
|
|
def get_members():
|
2023-01-12 16:31:34 +00:00
|
|
|
return Member.objects.all().annotate_membership().order_by("username")
|
2023-01-03 20:36:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_member(*, member_id: int) -> Member:
|
|
|
|
return get_members().get(id=member_id)
|