resa-padel/resa_padel/booking.py
Stanislas Jouffroy 0938fb98b7 Big refactoring.
- clubs, booking platforms and user are now defined in customization files -> there are less environment variables
- the responsibility of the session moved
- booking cancellation is available
2024-03-17 23:58:03 +01:00

87 lines
2.9 KiB
Python

import asyncio
import logging
import config
from connectors import Connector, GestionSportsConnector
from models import Action, BookingFilter, Club, Court, User
LOGGER = logging.getLogger(__name__)
def get_connector(club: Club) -> Connector:
if club.booking_platform.id == "gestion-sports":
return GestionSportsConnector(club)
async def book_court(
club: Club, users: list[User], booking_filter: BookingFilter
) -> tuple[Court, User]:
"""
Book any court that meets the condition from the filter. IThe user that will make
the booking is chosen among a list of users and should not have any ongoing bookings
:param club: the club in which the booking will be made
:param users: the list of users who have an account in the club
:param booking_filter: the conditions the court to book should meet
:return: a tuple containing the court that was booked and the user who made the
booking
"""
connector = get_connector(club)
for user in users:
if not await connector.has_user_ongoing_booking(user):
return await connector.book(user, booking_filter), user
async def cancel_booking(club: Club, user: User, booking_filter: BookingFilter) -> None:
"""
Cancel the booking that matches the specified filter
:param club: the club in which the booking was made
:param user: the user who made the booking
:param booking_filter: the conditions to meet to cancel the booking
"""
connector = get_connector(club)
await connector.cancel_booking(user, booking_filter)
async def cancel_booking_id(club: Club, user: User, booking_id: int) -> None:
"""
Cancel a booking that matches the booking id
:param club: the club in which the booking was made
:param user: the user who made the booking
:param booking_id: the id of the booking to cancel
"""
connector = get_connector(club)
await connector.cancel_booking_id(user, booking_id)
def main() -> tuple[Court, User] | None:
"""
Main function used to book a court
:return: the id of the booked court, or None if no court was booked
"""
action = config.get_action()
if action == Action.BOOK:
club = config.get_club()
users = config.get_users(club.id)
booking_filter = config.get_booking_filter()
court_booked, user = asyncio.run(book_court(club, users, booking_filter))
if court_booked:
LOGGER.info(
"Court %s booked successfully at %s for user %s",
court_booked,
booking_filter.date,
user,
)
return court_booked, user
else:
LOGGER.info("Booking did not work")
elif action == Action.CANCEL:
user = config.get_user()
club = config.get_club()
booking_filter = config.get_booking_filter()
asyncio.run(cancel_booking(club, user, booking_filter))