|
| 1 | +from datetime import datetime |
| 2 | +from typing import Any, Dict |
| 3 | + |
| 4 | +import api.utils as utils |
| 5 | +from api.helpers import calculate_total_charge |
| 6 | +from api.models import Reservation, Room |
| 7 | +from api.resolvers.constants import INVALID_DATE_CHECK_IN, INVALID_DATE_OVERLAP |
| 8 | + |
| 9 | + |
| 10 | +async def create_reservation( |
| 11 | + db, room_id: str, checkin_date: datetime, checkout_date: datetime |
| 12 | +) -> Dict[str, Any]: |
| 13 | + available = await is_room_available( |
| 14 | + db, room_id=room_id, checkin_date=checkin_date, checkout_date=checkout_date |
| 15 | + ) |
| 16 | + if not available["success"]: |
| 17 | + for message in available["errors"]: |
| 18 | + utils.log_api_message(__name__, message) |
| 19 | + return {"success": False, "errors": available["errors"]} |
| 20 | + |
| 21 | + room_result = await fetch_room(db, room_id) |
| 22 | + room = room_result["room"][0] |
| 23 | + daily_rate = room.daily_rate |
| 24 | + total_charge = calculate_total_charge(daily_rate, checkin_date, checkout_date) |
| 25 | + |
| 26 | + reservation_insert_query = """ |
| 27 | + INSERT INTO reservations |
| 28 | + (room_id, checkin_date, checkout_date, total_charge) |
| 29 | + VALUES ($1, $2, $3, $4) |
| 30 | + RETURNING id |
| 31 | + """ |
| 32 | + await db.fetchval( |
| 33 | + reservation_insert_query, room_id, checkin_date, checkout_date, total_charge |
| 34 | + ) |
| 35 | + reservations = await fetch_all_rows(db, Reservation) |
| 36 | + return reservations |
| 37 | + |
| 38 | + |
| 39 | +async def delete_reservation(db, reservation_id: str) -> Dict[str, Any]: |
| 40 | + reservation = await fetch_reservation(db, reservation_id) |
| 41 | + if reservation: |
| 42 | + await db.execute("DELETE FROM reservations WHERE id = $1", reservation_id) |
| 43 | + return await fetch_all_rows(db, Reservation) |
| 44 | + else: |
| 45 | + errors = ["Reservation not found"] |
| 46 | + return {"success": False, "errors": errors, "reservations": None} |
| 47 | + |
| 48 | + |
| 49 | +async def is_room_available( |
| 50 | + db, room_id: str, checkin_date: datetime, checkout_date: datetime |
| 51 | +) -> Dict[str, Any]: |
| 52 | + try: |
| 53 | + if checkin_date < datetime.now(): |
| 54 | + message: str = INVALID_DATE_CHECK_IN |
| 55 | + utils.log_api_message(__name__, message) |
| 56 | + return {"success": False, "errors": [message]} |
| 57 | + |
| 58 | + query = """ |
| 59 | + SELECT COUNT(*) FROM reservations |
| 60 | + WHERE room_id = $1 |
| 61 | + AND ( |
| 62 | + (checkin_date >= $2 AND checkin_date < $3) |
| 63 | + OR (checkout_date > $2 AND checkout_date <= $3) |
| 64 | + OR (checkin_date <= $2 AND checkout_date >= $3) |
| 65 | + ) |
| 66 | + """ |
| 67 | + count = await db.fetchval(query, room_id, checkin_date, checkout_date) |
| 68 | + |
| 69 | + if count == 0: |
| 70 | + return {"success": True, "errors": None} |
| 71 | + else: |
| 72 | + return {"success": False, "errors": [INVALID_DATE_OVERLAP]} |
| 73 | + |
| 74 | + except Exception as error: |
| 75 | + utils.log_api_message(__name__, str(error)) |
| 76 | + return {"success": False, "errors": [str(error)]} |
| 77 | + |
| 78 | + |
| 79 | +async def fetch_all_rows(db, entity_type) -> Dict[str, Any]: |
| 80 | + table_name = entity_type.__name__.lower() + "s" |
| 81 | + query = f"SELECT * FROM {table_name}" |
| 82 | + rows = await db.fetch(query) |
| 83 | + if rows: |
| 84 | + entities = [entity_type(**dict(row)) for row in rows] |
| 85 | + return {"success": True, f"{table_name}": entities} |
| 86 | + else: |
| 87 | + raise ValueError("No reserved rooms found") |
| 88 | + |
| 89 | + |
| 90 | +async def fetch_by_id(db, entity_type, id) -> Dict[str, Any]: |
| 91 | + table_name = entity_type.__name__.lower() + "s" |
| 92 | + query = f"SELECT * FROM {table_name} WHERE id = $1" |
| 93 | + rows = await db.fetch(query, id) |
| 94 | + if rows: |
| 95 | + entities = [entity_type(**dict(row)) for row in rows] |
| 96 | + return {"success": True, f"{entity_type.__name__.lower()}": entities} |
| 97 | + else: |
| 98 | + return {"success": False, f"{entity_type.__name__.lower()}": None} |
| 99 | + |
| 100 | + |
| 101 | +async def fetch_available_rooms(db, checkin_date, checkout_date) -> Dict[str, Any]: |
| 102 | + rooms = await fetch_all_rows(db, Room) |
| 103 | + available_rooms = [ |
| 104 | + room |
| 105 | + for room in rooms |
| 106 | + if await is_room_available(db, room.id, checkin_date, checkout_date) |
| 107 | + ] |
| 108 | + return {"success": True, "rooms": available_rooms} |
| 109 | + |
| 110 | + |
| 111 | +async def fetch_room(db, room_id: str) -> Room: |
| 112 | + result = await fetch_by_id(db, Room, id=room_id) |
| 113 | + if result["success"]: |
| 114 | + return result |
| 115 | + else: |
| 116 | + raise ValueError(f"Room with id {room_id} not found") |
| 117 | + |
| 118 | + |
| 119 | +async def fetch_reservation(db, reservation_id: id): |
| 120 | + result = await fetch_by_id(db, Reservation, id=reservation_id) |
| 121 | + if result["success"]: |
| 122 | + return result |
| 123 | + else: |
| 124 | + raise ValueError(f"Reservation with id of {reservation_id} not found") |
0 commit comments