~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/byceps/services/ticketing/ticket_service.py -rw-r--r-- 8.3 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""
byceps.services.ticketing.ticket_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

from typing import Dict, Optional, Sequence, Set

from ...database import db, Pagination
from ...typing import PartyID, UserID

from ..party.models.party import Party as DbParty
from ..party import service as party_service
from ..seating.models.seat import Seat as DbSeat
from ..shop.order.transfer.models import OrderNumber
from ..user.models.user import User as DbUser

from .models.category import Category as DbCategory
from .models.ticket import Ticket as DbTicket
from .models.ticket_event import TicketEvent as DbTicketEvent
from .transfer.models import TicketCode, TicketID, TicketSaleStats


def delete_ticket(ticket_id: TicketID) -> None:
    """Delete a ticket and its events."""
    db.session.query(DbTicketEvent) \
        .filter_by(ticket_id=ticket_id) \
        .delete()

    db.session.query(DbTicket) \
        .filter_by(id=ticket_id) \
        .delete()

    db.session.commit()


def find_ticket(ticket_id: TicketID) -> Optional[DbTicket]:
    """Return the ticket with that id, or `None` if not found."""
    return DbTicket.query.get(ticket_id)


def find_ticket_by_code(code: TicketCode) -> Optional[DbTicket]:
    """Return the ticket with that code, or `None` if not found."""
    return DbTicket.query \
        .filter_by(code=code) \
        .one_or_none()


def find_tickets(ticket_ids: Set[TicketID]) -> Sequence[DbTicket]:
    """Return the tickets with those ids."""
    if not ticket_ids:
        return []

    return DbTicket.query \
        .filter(DbTicket.id.in_(ticket_ids)) \
        .all()


def find_tickets_created_by_order(
    order_number: OrderNumber,
) -> Sequence[DbTicket]:
    """Return the tickets created by this order (as it was marked as paid)."""
    return DbTicket.query \
        .filter_by(order_number=order_number) \
        .order_by(DbTicket.created_at) \
        .all()


def find_tickets_for_seat_manager(
    user_id: UserID, party_id: PartyID
) -> Sequence[DbTicket]:
    """Return the tickets for that party whose respective seats the user
    is entitled to manage.
    """
    return DbTicket.query \
        .for_party(party_id) \
        .filter(DbTicket.revoked == False) \
        .filter(
            (
                (DbTicket.seat_managed_by_id == None) &
                (DbTicket.owned_by_id == user_id)
            ) |
            (DbTicket.seat_managed_by_id == user_id)
        ) \
        .options(
            db.joinedload('occupied_seat'),
        ) \
        .all()


def find_tickets_related_to_user(user_id: UserID) -> Sequence[DbTicket]:
    """Return tickets related to the user."""
    return DbTicket.query \
        .filter(
            (DbTicket.owned_by_id == user_id) |
            (DbTicket.seat_managed_by_id == user_id) |
            (DbTicket.user_managed_by_id == user_id) |
            (DbTicket.used_by_id == user_id)
        ) \
        .options(
            db.joinedload('occupied_seat').joinedload('area'),
            db.joinedload('occupied_seat').joinedload('category'),
            db.joinedload('seat_managed_by'),
            db.joinedload('user_managed_by'),
            db.joinedload('used_by'),
        ) \
        .order_by(DbTicket.created_at) \
        .all()


def find_tickets_related_to_user_for_party(
    user_id: UserID, party_id: PartyID
) -> Sequence[DbTicket]:
    """Return tickets related to the user for the party."""
    return DbTicket.query \
        .for_party(party_id) \
        .filter(
            (DbTicket.owned_by_id == user_id) |
            (DbTicket.seat_managed_by_id == user_id) |
            (DbTicket.user_managed_by_id == user_id) |
            (DbTicket.used_by_id == user_id)
        ) \
        .options(
            db.joinedload('occupied_seat').joinedload('area'),
            db.joinedload('occupied_seat').joinedload('category'),
            db.joinedload('seat_managed_by'),
            db.joinedload('user_managed_by'),
            db.joinedload('used_by'),
        ) \
        .order_by(DbTicket.created_at) \
        .all()


def find_tickets_used_by_user(
    user_id: UserID, party_id: PartyID
) -> Sequence[DbTicket]:
    """Return the tickets (if any) used by the user for that party."""
    return DbTicket.query \
        .for_party(party_id) \
        .filter(DbTicket.used_by_id == user_id) \
        .filter(DbTicket.revoked == False) \
        .outerjoin(DbSeat) \
        .options(
            db.joinedload('occupied_seat').joinedload('area'),
        ) \
        .order_by(DbSeat.coord_x, DbSeat.coord_y) \
        .all()


def uses_any_ticket_for_party(user_id: UserID, party_id: PartyID) -> bool:
    """Return `True` if the user uses any ticket for that party."""
    q = DbTicket.query \
        .for_party(party_id) \
        .filter(DbTicket.used_by_id == user_id) \
        .filter(DbTicket.revoked == False)

    return db.session.query(q.exists()).scalar()


def select_ticket_users_for_party(
    user_ids: Set[UserID], party_id: PartyID
) -> Set[UserID]:
    """Return the IDs of those users that use a ticket for that party."""
    if not user_ids:
        return set()

    q = DbTicket.query \
        .for_party(party_id) \
        .filter(DbTicket.used_by_id == DbUser.id) \
        .filter(DbTicket.revoked == False)

    rows = db.session.query(DbUser.id) \
        .filter(q.exists()) \
        .filter(DbUser.id.in_(user_ids)) \
        .all()

    return {row[0] for row in rows}


def get_ticket_with_details(ticket_id: TicketID) -> Optional[DbTicket]:
    """Return the ticket with that id, or `None` if not found."""
    return DbTicket.query \
        .options(
            db.joinedload('category'),
            db.joinedload('occupied_seat').joinedload('area'),
            db.joinedload('owned_by'),
            db.joinedload('seat_managed_by'),
            db.joinedload('user_managed_by'),
        ) \
        .get(ticket_id)


def get_tickets_with_details_for_party_paginated(
    party_id: PartyID, page: int, per_page: int, *, search_term=None
) -> Pagination:
    """Return the party's tickets to show on the specified page."""
    query = DbTicket.query \
        .for_party(party_id) \
        .options(
            db.joinedload('category'),
            db.joinedload('owned_by'),
            db.joinedload('occupied_seat').joinedload('area'),
        )

    if search_term:
        ilike_pattern = f'%{search_term}%'
        query = query \
            .filter(DbTicket.code.ilike(ilike_pattern))

    return query \
        .order_by(DbTicket.created_at) \
        .paginate(page, per_page)


def get_ticket_count_by_party_id() -> Dict[PartyID, int]:
    """Return ticket count (including 0) per party, indexed by party ID."""
    party = db.aliased(DbParty)

    subquery = db.session \
        .query(
            db.func.count(DbTicket.id)
        ) \
        .join(DbCategory) \
        .filter(DbCategory.party_id == party.id) \
        .filter(DbTicket.revoked == False) \
        .subquery() \
        .as_scalar()

    party_ids_and_ticket_counts = db.session \
        .query(
            party.id,
            subquery
        ) \
        .all()

    return dict(party_ids_and_ticket_counts)


def count_revoked_tickets_for_party(party_id: PartyID) -> int:
    """Return the number of revoked tickets for that party."""
    return DbTicket.query \
        .for_party(party_id) \
        .filter(DbTicket.revoked == True) \
        .count()


def count_sold_tickets_for_party(party_id: PartyID) -> int:
    """Return the number of "sold" (i.e. generated and not revoked)
    tickets for that party.
    """
    return DbTicket.query \
        .for_party(party_id) \
        .filter(DbTicket.revoked == False) \
        .count()


def count_tickets_checked_in_for_party(party_id: PartyID) -> int:
    """Return the number tickets for that party that were used to check
    in their respective user.
    """
    return DbTicket.query \
        .for_party(party_id) \
        .filter(DbTicket.user_checked_in == True) \
        .count()


def get_ticket_sale_stats(party_id: PartyID) -> TicketSaleStats:
    """Return the number of maximum and sold tickets, respectively."""
    party = party_service.get_party(party_id)

    sold = count_sold_tickets_for_party(party.id)

    return TicketSaleStats(
        tickets_max=party.max_ticket_quantity,
        tickets_sold=sold,
    )