from decimal import Decimal from django.db.models import Sum from django.utils import timezone from .models import FanMembership, SupportCredit MENU = ( ('read', 'Read', 'chapters'), ('blog', 'Blog', 'blog'), ('reviews', 'Reviews', 'slx-series-reviews'), ('upcoming', 'Upcoming', 'upcoming'), ('live', 'SLX Live', 'stream'), ('cast', 'Cast', 'entries'), ('world', 'World archive', 'entries'), ('books', 'Shop', 'books'), ('shop', 'Shop', None), ('search', 'Search', 'search'), ('community', 'Community', 'slx-community'), ('membership', 'Membership', 'membership'), ('library', 'My library', 'library'), ('notices', 'Fan notifications', 'fan-notices'), ('account', 'Fan corner', 'fan-login'), ) RANKS = ( ('djinn', 'Djinn'), ('scout', 'Sol-Scout'), ('caster', 'Sol-Caster'), ('striker', 'Sol-Striker'), ('seat', 'Sol Seat'), ) def rank_for(membership, total, config, now): if (membership and membership.sol_seat) or (config.seat_threshold is not None and total >= config.seat_threshold): return RANKS[4] if total >= config.striker_threshold: return RANKS[3] if total >= config.caster_threshold: return RANKS[2] if membership and membership.subscriber_until and membership.subscriber_until > now: return RANKS[1] return RANKS[0] def load_ranks(ids, config): ids = set(ids) if not ids: return {} memberships = {row.user_id: row for row in FanMembership.objects.filter(user_id__in=ids)} sums = dict(SupportCredit.objects.filter(user_id__in=ids, voided=False).values('user_id') .annotate(total=Sum('amount')).values_list('user_id', 'total')) now = timezone.now() return {pk: rank_for(memberships.get(pk), sums.get(pk, Decimal(0)), config, now) for pk in ids}