~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/byceps/services/orga/birthday_service.py -rw-r--r-- 1.9 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 1 year, 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
byceps.services.orga.birthday_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from itertools import islice
from typing import Iterator, Sequence, Tuple

from ...database import db

from ..user_avatar import service as user_avatar_service
from ..user.models.detail import UserDetail
from ..user.models.user import User as DbUser
from ..user.transfer.models import User

from .models import OrgaFlag


def collect_orgas_with_next_birthdays(
    *, limit: int = None
) -> Iterator[Tuple[User, UserDetail]]:
    """Yield the next birthdays of organizers, sorted by month and day."""
    orgas_with_birthdays = _collect_orgas_with_birthdays()

    sorted_orgas = sort_users_by_next_birthday(orgas_with_birthdays)

    if limit is not None:
        sorted_orgas = list(islice(sorted_orgas, limit))

    orgas = sorted_orgas

    user_ids = {user.id for user in orgas}

    avatar_urls_by_user_id = user_avatar_service.get_avatar_urls_for_users(
        user_ids
    )

    for user in orgas:
        avatar_url = avatar_urls_by_user_id.get(user.id)

        user_dto = User(
            user.id,
            user.screen_name,
            user.suspended,
            user.deleted,
            avatar_url,
            True,  # is_orga
        )

        yield user_dto, user.detail


def _collect_orgas_with_birthdays() -> Sequence[DbUser]:
    """Return all organizers whose birthday is known."""
    return DbUser.query \
        .join(OrgaFlag) \
        .join(UserDetail) \
        .filter(UserDetail.date_of_birth != None) \
        .options(db.joinedload('detail')) \
        .all()


def sort_users_by_next_birthday(users: Sequence[DbUser]) -> Sequence[DbUser]:
    return sorted(
        users,
        key=lambda user: (
            user.detail.days_until_next_birthday,
            -user.detail.age,
        ),
    )