def __get_customer_budget(self, customer_id, year): """Get customer budget for a specific year.""" try: customer_model = CustomerModel.get(CustomerModel.id == customer_id) events = (EventModel.select( EventModel.id, EventModel.ticket_price, (fn.COUNT(TicketModel.id) * EventModel.ticket_price).alias('total_costs')).join( TicketModel).join(CustomerModel).where( CustomerModel.id == customer_id, EventModel.date.year == year).group_by(EventModel.id)) costs = 0 for event in events: costs = costs + event.total_costs return customer_model.budget - costs except DoesNotExist: raise DbActorError("Customer not found.", 404) from DoesNotExist
def __purchase_event_ticket(self, customer_id, event_id, quantity): """Purchase of a certain number of tickets for a specific event.""" try: event_model = EventModel.get(EventModel.id == event_id) except DoesNotExist: raise DbActorError("Event not found.", 404) from DoesNotExist customer_model = CustomerModel.get(CustomerModel.id == customer_id) event_customer_ticket_models = (TicketModel.select().join( CustomerModel).switch(TicketModel).join(EventModel).where( CustomerModel.id == customer_id, EventModel.id == event_id)) event_ticket_models = (TicketModel.select().join(EventModel).where( EventModel.id == event_id)) total_price = event_model.ticket_price * quantity available_budget = self.__get_customer_budget(customer_model.id, event_model.date.year) if available_budget - total_price < 0: raise DbActorError("The budget of the customer is not sufficient.", 400) if event_model.max_tickets_per_customer < len( event_customer_ticket_models) + quantity: raise DbActorError( ("With this purchase the maximum number of tickets per " "customer for this event would be exceeded."), 400) if event_model.max_tickets < len(event_ticket_models) + quantity: raise DbActorError(("With this purchase the maximum number of " "tickets for this event would be exceeded."), 400) sale_not_started = event_model.sale_start_date > date.today() sale_end_date = event_model.sale_start_date + \ timedelta(days=event_model.sale_period) sale_over = sale_end_date < date.today() if sale_not_started or sale_over: raise DbActorError( "Currently no tickets can be purchased for this event.", 400) for _ in range(quantity): ticket_model = TicketModel(order_date=date.today(), customer=customer_model, event=event_model) ticket_model.save()
def __check_customer_id(self, customer_id): """Check if customer exists.""" try: CustomerModel.get(CustomerModel.id == customer_id) except DoesNotExist: raise DbActorError("Customer not found.", 404) from DoesNotExist