From 2a105c1170066bf358fae151f88168c72b4979a8 Mon Sep 17 00:00:00 2001 From: Iliyan Angelov Date: Fri, 21 Nov 2025 17:32:29 +0200 Subject: [PATCH] updates --- .../booking_routes.cpython-312.pyc | Bin 76607 -> 93489 bytes Backend/src/routes/booking_routes.py | 524 ++++++++++++++++- .../components/admin/CreateBookingModal.tsx | 553 ++++++++++++++++++ .../src/pages/admin/BookingManagementPage.tsx | 39 +- .../pages/admin/ReceptionDashboardPage.tsx | 37 +- Frontend/src/services/api/bookingService.ts | 11 + 6 files changed, 1124 insertions(+), 40 deletions(-) create mode 100644 Frontend/src/components/admin/CreateBookingModal.tsx diff --git a/Backend/src/routes/__pycache__/booking_routes.cpython-312.pyc b/Backend/src/routes/__pycache__/booking_routes.cpython-312.pyc index 41c4675d864e614bccae38efd177a7786fc6a563..dcb492648163a8f493e952f8290ec652f8fe6e62 100644 GIT binary patch delta 17352 zcmcJ133yZ2mGFDotX;BJOSTs8mUkQP7=w+m4H&ay%u>hr39#`(o&_Z4DFTuvCeUE# zrLk#AFr7|;LMNnjikr3*=#r3WXGXF;k#NXgNIU;bJJYF>Fj+{ZnRA}>}PK7Gx$1s4{mMRp_=-MeexW5^DJq;!9D{ZB36# zTr1dr6dfWjvJK)tlCG;OBrAoa=ISZg*94^FYPQm0hTN*udLe0MPi16~7WVrY$+`qk zFeBg6(R0APf~NavTEqS}!%f=QwV6qzW3(uNOk#&JUncEWtFj(;fav8$8;JgWV{U#5 zh|;ejxQ^fi0viGb!3_jIL9hyegROk6Y_unVG>{3SM-xard+s#@`n&RzZe`?~t}v{N0P4yWhQ{q8E~eOay(mARX^S;)F=$D58_lD$ZO7 zVs-@g5d0S_f8rP9XY89#^r|n4>Cce%F@pQ-`Y-2z0`HfPE90O7T8cnHvbrbRpnT7h z2?7;)^~onwNh>F`4~6ttMup%wW)195pQ6E(vY}O=>F7|c@qL^kM~LgSuQ%UlK0?qd zAbXJw4*kl0Q9=7qhEvvz7}v$$LX05U>EmCqqFpn}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bj|xV*qYb{h^|6a6zrNb7;`-qp8TT zjOdIUm+?C(`<=SMKzyL_i`5%T9I;Sp1jxci(}7Q?VtyIeav~_VNLkQ|Sx59o$_Y>W zA}<@2_MnXmTR8~I5nd8q+)AdA3DMqGGIRb~)My8Ysk^*Vb1Ut|w$RlrQ9Q6Iz8RW> zP>CL90$kJ0g(r6VeWmp0Ab|f|=qJKk+BQ-x+*?M-+~=1Kb4cHSBLwN;d2u?>8oaD9 cz7RORnhf(O9G=HVpY)SL!zDhC%vGN9zgR#i-v9sr diff --git a/Backend/src/routes/booking_routes.py b/Backend/src/routes/booking_routes.py index d63a1de2..47fa224a 100644 --- a/Backend/src/routes/booking_routes.py +++ b/Backend/src/routes/booking_routes.py @@ -190,15 +190,15 @@ async def create_booking(booking_data: dict, current_user: User=Depends(get_curr if overlapping: raise HTTPException(status_code=409, detail='Room already booked for the selected dates') booking_number = generate_booking_number() - requires_deposit = payment_method == 'cash' - deposit_percentage = 20 if requires_deposit else 0 - deposit_amount = float(total_price) * deposit_percentage / 100 if requires_deposit else 0 - initial_status = BookingStatus.pending - if payment_method in ['stripe', 'paypal']: - initial_status = BookingStatus.pending + + # Calculate room price room_price = float(room.price) if room.price and room.price > 0 else float(room.room_type.base_price) if room.room_type else 0.0 number_of_nights = (check_out - check_in).days + if number_of_nights <= 0: + number_of_nights = 1 # Minimum 1 night room_total = room_price * number_of_nights + + # Calculate services total if any services = booking_data.get('services', []) services_total = 0.0 if services: @@ -210,13 +210,56 @@ async def create_booking(booking_data: dict, current_user: User=Depends(get_curr service = db.query(Service).filter(Service.id == service_id).first() if service and service.is_active: services_total += float(service.price) * quantity + original_price = room_total + services_total - discount_amount = max(0.0, original_price - float(total_price)) if promotion_code else 0.0 + + # Validate and use calculated price (same logic as admin booking) + calculated_total = original_price + provided_total = float(total_price) if total_price else 0.0 + + if promotion_code: + # With promotion, allow the provided price (it might include discount) + discount_amount = max(0.0, original_price - provided_total) + final_total_price = provided_total + else: + # Without promotion, use calculated price to ensure consistency + # Allow small differences (0.01) for rounding, but use calculated price + if abs(calculated_total - provided_total) > 0.01: + logger.warning(f'Price mismatch: calculated={calculated_total}, provided={provided_total}. Using calculated price.') + final_total_price = calculated_total + else: + final_total_price = provided_total + discount_amount = 0.0 + + requires_deposit = payment_method == 'cash' + deposit_percentage = 20 if requires_deposit else 0 + deposit_amount = final_total_price * deposit_percentage / 100 if requires_deposit else 0 + + initial_status = BookingStatus.pending + if payment_method in ['stripe', 'paypal']: + initial_status = BookingStatus.pending + final_notes = notes or '' if promotion_code: promotion_note = f'Promotion Code: {promotion_code}' final_notes = f'{promotion_note}\n{final_notes}'.strip() if final_notes else promotion_note - booking = Booking(booking_number=booking_number, user_id=current_user.id, room_id=room_id, check_in_date=check_in, check_out_date=check_out, num_guests=guest_count, total_price=total_price, original_price=original_price if promotion_code else None, discount_amount=discount_amount if promotion_code and discount_amount > 0 else None, promotion_code=promotion_code, special_requests=final_notes, status=initial_status, requires_deposit=requires_deposit, deposit_paid=False) + + booking = Booking( + booking_number=booking_number, + user_id=current_user.id, + room_id=room_id, + check_in_date=check_in, + check_out_date=check_out, + num_guests=guest_count, + total_price=final_total_price, + original_price=original_price if promotion_code else None, + discount_amount=discount_amount if promotion_code and discount_amount > 0 else None, + promotion_code=promotion_code, + special_requests=final_notes, + status=initial_status, + requires_deposit=requires_deposit, + deposit_paid=False + ) db.add(booking) db.flush() if payment_method in ['stripe', 'paypal']: @@ -229,7 +272,7 @@ async def create_booking(booking_data: dict, current_user: User=Depends(get_curr logger.warning(f'Unexpected payment_method: {payment_method}, defaulting to stripe') payment_method_enum = PaymentMethod.stripe logger.info(f'Creating payment for booking {booking.id} with payment_method: {payment_method} -> enum: {payment_method_enum.value}') - payment = Payment(booking_id=booking.id, amount=total_price, payment_method=payment_method_enum, payment_type=PaymentType.full, payment_status=PaymentStatus.pending, payment_date=None) + payment = Payment(booking_id=booking.id, amount=final_total_price, payment_method=payment_method_enum, payment_type=PaymentType.full, payment_status=PaymentStatus.pending, payment_date=None) db.add(payment) db.flush() logger.info(f'Payment created: ID={payment.id}, method={(payment.payment_method.value if hasattr(payment.payment_method, 'value') else payment.payment_method)}') @@ -292,8 +335,8 @@ async def create_booking(booking_data: dict, current_user: User=Depends(get_curr invoice_notes = f'{promotion_note}\n{invoice_notes}'.strip() if invoice_notes else promotion_note invoice_kwargs['notes'] = invoice_notes if payment_method == 'cash': - deposit_amount = float(total_price) * 0.2 - remaining_amount = float(total_price) * 0.8 + deposit_amount = final_total_price * 0.2 + remaining_amount = final_total_price * 0.8 deposit_discount = booking_discount * 0.2 if booking_discount > 0 else 0.0 proforma_discount = booking_discount * 0.8 if booking_discount > 0 else 0.0 deposit_invoice = InvoiceService.create_invoice_from_booking(booking_id=booking.id, db=db, created_by_id=current_user.id, tax_rate=tax_rate, discount_amount=deposit_discount, due_days=30, is_proforma=False, invoice_amount=deposit_amount, **invoice_kwargs) @@ -485,7 +528,10 @@ async def cancel_booking(id: int, current_user: User=Depends(get_current_user), @router.put('/{id}', dependencies=[Depends(authorize_roles('admin'))]) async def update_booking(id: int, booking_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)): try: - booking = db.query(Booking).options(selectinload(Booking.payments)).filter(Booking.id == id).first() + booking = db.query(Booking).options( + selectinload(Booking.payments), + joinedload(Booking.user) + ).filter(Booking.id == id).first() if not booking: raise HTTPException(status_code=404, detail='Booking not found') old_status = booking.status @@ -506,7 +552,17 @@ async def update_booking(id: int, booking_data: dict, current_user: User=Depends except ValueError: raise HTTPException(status_code=400, detail='Invalid status') db.commit() - db.refresh(booking) + + # Reload booking with all relationships after commit + booking = db.query(Booking).options( + selectinload(Booking.payments), + joinedload(Booking.user), + joinedload(Booking.room).joinedload(Room.room_type) + ).filter(Booking.id == id).first() + + if not booking: + raise HTTPException(status_code=404, detail='Booking not found after update') + payment_warning = None if status_value and old_status != booking.status and (booking.status == BookingStatus.checked_in): payment_balance = calculate_booking_payment_balance(booking) @@ -516,29 +572,41 @@ async def update_booking(id: int, booking_data: dict, current_user: User=Depends if booking.status in [BookingStatus.confirmed, BookingStatus.cancelled]: try: from ..models.system_settings import SystemSettings - from ..services.room_service import get_base_url - from fastapi import Request client_url_setting = db.query(SystemSettings).filter(SystemSettings.key == 'client_url').first() client_url = client_url_setting.value if client_url_setting and client_url_setting.value else settings.CLIENT_URL or os.getenv('CLIENT_URL', 'http://localhost:5173') if booking.status == BookingStatus.confirmed: - from sqlalchemy.orm import selectinload - booking_with_room = db.query(Booking).options(selectinload(Booking.room).selectinload(Room.room_type)).filter(Booking.id == booking.id).first() - room = booking_with_room.room if booking_with_room else None + room = booking.room room_type_name = room.room_type.name if room and room.room_type else 'Room' currency_setting = db.query(SystemSettings).filter(SystemSettings.key == 'platform_currency').first() currency = currency_setting.value if currency_setting and currency_setting.value else 'USD' currency_symbols = {'USD': '$', 'EUR': '€', 'GBP': '£', 'JPY': '¥', 'CNY': '¥', 'KRW': '₩', 'SGD': 'S$', 'THB': '฿', 'AUD': 'A$', 'CAD': 'C$', 'VND': '₫', 'INR': '₹', 'CHF': 'CHF', 'NZD': 'NZ$'} currency_symbol = currency_symbols.get(currency, currency) - email_html = booking_confirmation_email_template(booking_number=booking.booking_number, guest_name=booking.user.full_name if booking.user else 'Guest', room_number=room.room_number if room else 'N/A', room_type=room_type_name, check_in=booking.check_in_date.strftime('%B %d, %Y') if booking.check_in_date else 'N/A', check_out=booking.check_out_date.strftime('%B %d, %Y') if booking.check_out_date else 'N/A', num_guests=booking.num_guests, total_price=float(booking.total_price), requires_deposit=booking.requires_deposit, deposit_amount=float(booking.total_price) * 0.2 if booking.requires_deposit else None, original_price=float(booking.original_price) if booking.original_price else None, discount_amount=float(booking.discount_amount) if booking.discount_amount else None, promotion_code=booking.promotion_code, client_url=client_url, currency_symbol=currency_symbol) - await send_email(to=booking.user.email if booking.user else None, subject=f'Booking Confirmed - {booking.booking_number}', html=email_html) + guest_name = booking.user.full_name if booking.user else 'Guest' + guest_email = booking.user.email if booking.user else None + email_html = booking_confirmation_email_template(booking_number=booking.booking_number, guest_name=guest_name, room_number=room.room_number if room else 'N/A', room_type=room_type_name, check_in=booking.check_in_date.strftime('%B %d, %Y') if booking.check_in_date else 'N/A', check_out=booking.check_out_date.strftime('%B %d, %Y') if booking.check_out_date else 'N/A', num_guests=booking.num_guests, total_price=float(booking.total_price), requires_deposit=booking.requires_deposit, deposit_amount=float(booking.total_price) * 0.2 if booking.requires_deposit else None, original_price=float(booking.original_price) if booking.original_price else None, discount_amount=float(booking.discount_amount) if booking.discount_amount else None, promotion_code=booking.promotion_code, client_url=client_url, currency_symbol=currency_symbol) + if guest_email: + await send_email(to=guest_email, subject=f'Booking Confirmed - {booking.booking_number}', html=email_html) elif booking.status == BookingStatus.cancelled: - email_html = booking_status_changed_email_template(booking_number=booking.booking_number, guest_name=booking.user.full_name if booking.user else 'Guest', status='cancelled', client_url=client_url) - await send_email(to=booking.user.email if booking.user else None, subject=f'Booking Cancelled - {booking.booking_number}', html=email_html) + guest_name = booking.user.full_name if booking.user else 'Guest' + guest_email = booking.user.email if booking.user else None + email_html = booking_status_changed_email_template(booking_number=booking.booking_number, guest_name=guest_name, status='cancelled', client_url=client_url) + if guest_email: + await send_email(to=guest_email, subject=f'Booking Cancelled - {booking.booking_number}', html=email_html) except Exception as e: import logging logger = logging.getLogger(__name__) logger.error(f'Failed to send status change email: {e}') - response_data = {'status': 'success', 'message': 'Booking updated successfully', 'data': {'booking': booking}} + import traceback + logger.error(traceback.format_exc()) + + # Build response with booking data + booking_dict = { + 'id': booking.id, + 'booking_number': booking.booking_number, + 'status': booking.status.value if isinstance(booking.status, BookingStatus) else booking.status, + } + + response_data = {'status': 'success', 'message': 'Booking updated successfully', 'data': {'booking': booking_dict}} if payment_warning: response_data['warning'] = payment_warning response_data['message'] = 'Booking updated successfully. ⚠️ Payment reminder: Guest has remaining balance.' @@ -546,8 +614,13 @@ async def update_booking(id: int, booking_data: dict, current_user: User=Depends except HTTPException: raise except Exception as e: + import logging + import traceback + logger = logging.getLogger(__name__) + logger.error(f'Error updating booking {id}: {str(e)}') + logger.error(traceback.format_exc()) db.rollback() - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail=f'Failed to update booking: {str(e)}') @router.get('/check/{booking_number}') async def check_booking_by_number(booking_number: str, db: Session=Depends(get_db)): @@ -589,4 +662,407 @@ async def check_booking_by_number(booking_number: str, db: Session=Depends(get_d except HTTPException: raise except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + +@router.post('/admin-create', dependencies=[Depends(authorize_roles('admin', 'staff'))]) +async def admin_create_booking(booking_data: dict, current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)): + """Create a booking on behalf of a user (admin/staff only)""" + try: + import logging + logger = logging.getLogger(__name__) + if not isinstance(booking_data, dict): + logger.error(f'Invalid booking_data type: {type(booking_data)}, value: {booking_data}') + raise HTTPException(status_code=400, detail='Invalid request body. Expected JSON object.') + + # Get user_id from booking_data (required for admin/staff bookings) + user_id = booking_data.get('user_id') + if not user_id: + raise HTTPException(status_code=400, detail='user_id is required for admin/staff bookings') + + # Verify user exists + target_user = db.query(User).filter(User.id == user_id).first() + if not target_user: + raise HTTPException(status_code=404, detail='User not found') + + logger.info(f'Admin/Staff {current_user.id} creating booking for user {user_id}: {booking_data}') + + room_id = booking_data.get('room_id') + check_in_date = booking_data.get('check_in_date') + check_out_date = booking_data.get('check_out_date') + total_price = booking_data.get('total_price') + guest_count = booking_data.get('guest_count', 1) + notes = booking_data.get('notes') + payment_method = booking_data.get('payment_method', 'cash') + payment_status = booking_data.get('payment_status', 'unpaid') # 'full', 'deposit', or 'unpaid' + promotion_code = booking_data.get('promotion_code') + status = booking_data.get('status', 'confirmed') # Default to confirmed for admin bookings + invoice_info = booking_data.get('invoice_info', {}) + + missing_fields = [] + if not room_id: + missing_fields.append('room_id') + if not check_in_date: + missing_fields.append('check_in_date') + if not check_out_date: + missing_fields.append('check_out_date') + if total_price is None: + missing_fields.append('total_price') + if missing_fields: + error_msg = f'Missing required booking fields: {', '.join(missing_fields)}' + logger.error(error_msg) + raise HTTPException(status_code=400, detail=error_msg) + + room = db.query(Room).filter(Room.id == room_id).first() + if not room: + raise HTTPException(status_code=404, detail='Room not found') + + # Parse dates + if 'T' in check_in_date or 'Z' in check_in_date or '+' in check_in_date: + check_in = datetime.fromisoformat(check_in_date.replace('Z', '+00:00')) + else: + check_in = datetime.strptime(check_in_date, '%Y-%m-%d') + if 'T' in check_out_date or 'Z' in check_out_date or '+' in check_out_date: + check_out = datetime.fromisoformat(check_out_date.replace('Z', '+00:00')) + else: + check_out = datetime.strptime(check_out_date, '%Y-%m-%d') + + # Check for overlapping bookings + overlapping = db.query(Booking).filter( + and_( + Booking.room_id == room_id, + Booking.status != BookingStatus.cancelled, + Booking.check_in_date < check_out, + Booking.check_out_date > check_in + ) + ).first() + if overlapping: + raise HTTPException(status_code=409, detail='Room already booked for the selected dates') + + booking_number = generate_booking_number() + # Calculate room price first (needed for deposit calculation) + room_price = float(room.price) if room.price and room.price > 0 else float(room.room_type.base_price) if room.room_type else 0.0 + number_of_nights = (check_out - check_in).days + if number_of_nights <= 0: + number_of_nights = 1 + room_total = room_price * number_of_nights + + # Calculate services total if any + services = booking_data.get('services', []) + services_total = 0.0 + if services: + from ..models.service import Service + for service_item in services: + service_id = service_item.get('service_id') + quantity = service_item.get('quantity', 1) + if service_id: + service = db.query(Service).filter(Service.id == service_id).first() + if service and service.is_active: + services_total += float(service.price) * quantity + + original_price = room_total + services_total + + # Validate and use calculated price + calculated_total = original_price + provided_total = float(total_price) if total_price else 0.0 + + if promotion_code: + discount_amount = max(0.0, original_price - provided_total) + final_total_price = provided_total + else: + if abs(calculated_total - provided_total) > 0.01: + logger.warning(f'Price mismatch: calculated={calculated_total}, provided={provided_total}. Using calculated price.') + final_total_price = calculated_total + else: + final_total_price = provided_total + discount_amount = 0.0 + + # Determine deposit requirements based on payment_status (use final_total_price) + if payment_status == 'deposit': + requires_deposit = True + deposit_percentage = 20 + deposit_amount = final_total_price * 0.2 + elif payment_status == 'full': + requires_deposit = False + deposit_percentage = 0 + deposit_amount = 0 + else: # unpaid + requires_deposit = payment_method == 'cash' + deposit_percentage = 20 if requires_deposit else 0 + deposit_amount = final_total_price * deposit_percentage / 100 if requires_deposit else 0 + + # Set initial status (admin can set it directly) + try: + initial_status = BookingStatus(status) if status else BookingStatus.confirmed + except ValueError: + initial_status = BookingStatus.confirmed + + final_notes = notes or '' + if promotion_code: + promotion_note = f'Promotion Code: {promotion_code}' + final_notes = f'{promotion_note}\n{final_notes}'.strip() if final_notes else promotion_note + + # Add admin note + admin_note = f'Created by {current_user.full_name} (Admin/Staff)' + final_notes = f'{admin_note}\n{final_notes}'.strip() if final_notes else admin_note + + # Determine deposit_paid status + deposit_paid = payment_status == 'deposit' or payment_status == 'full' + + # Create booking + booking = Booking( + booking_number=booking_number, + user_id=user_id, + room_id=room_id, + check_in_date=check_in, + check_out_date=check_out, + num_guests=guest_count, + total_price=final_total_price, + original_price=original_price if promotion_code else None, + discount_amount=discount_amount if promotion_code and discount_amount > 0 else None, + promotion_code=promotion_code, + special_requests=final_notes, + status=initial_status, + requires_deposit=requires_deposit, + deposit_paid=deposit_paid + ) + db.add(booking) + db.flush() + + # Create payment records based on payment_status + from ..models.payment import Payment, PaymentMethod, PaymentStatus, PaymentType + from datetime import datetime as dt + + # Determine payment method enum + if payment_method == 'stripe': + payment_method_enum = PaymentMethod.stripe + elif payment_method == 'paypal': + payment_method_enum = PaymentMethod.paypal + else: + payment_method_enum = PaymentMethod.cash + + # Handle payment creation based on payment_status + if payment_status == 'full': + # Fully paid - create a single completed payment + full_payment = Payment( + booking_id=booking.id, + amount=final_total_price, + payment_method=payment_method_enum, + payment_type=PaymentType.full, + payment_status=PaymentStatus.completed, + payment_date=dt.utcnow(), + notes=f'Payment received at booking creation by {current_user.full_name}' + ) + db.add(full_payment) + db.flush() + elif payment_status == 'deposit': + # Deposit only - create completed deposit payment and pending remaining payment + deposit_payment = Payment( + booking_id=booking.id, + amount=deposit_amount, + payment_method=payment_method_enum, + payment_type=PaymentType.deposit, + deposit_percentage=deposit_percentage, + payment_status=PaymentStatus.completed, + payment_date=dt.utcnow(), + notes=f'Deposit received at booking creation by {current_user.full_name}' + ) + db.add(deposit_payment) + db.flush() + + # Create pending payment for remaining amount + remaining_amount = final_total_price - deposit_amount + if remaining_amount > 0: + remaining_payment = Payment( + booking_id=booking.id, + amount=remaining_amount, + payment_method=payment_method_enum, + payment_type=PaymentType.remaining, + payment_status=PaymentStatus.pending, + payment_date=None, + notes='Remaining balance to be paid at check-in' + ) + db.add(remaining_payment) + db.flush() + else: + # Unpaid - create pending payment(s) + if requires_deposit and deposit_amount > 0: + # Create pending deposit payment + deposit_payment = Payment( + booking_id=booking.id, + amount=deposit_amount, + payment_method=payment_method_enum, + payment_type=PaymentType.deposit, + deposit_percentage=deposit_percentage, + payment_status=PaymentStatus.pending, + payment_date=None, + notes='Deposit to be paid at check-in' + ) + db.add(deposit_payment) + db.flush() + + # Create pending payment for remaining amount + remaining_amount = final_total_price - deposit_amount + if remaining_amount > 0: + remaining_payment = Payment( + booking_id=booking.id, + amount=remaining_amount, + payment_method=payment_method_enum, + payment_type=PaymentType.remaining, + payment_status=PaymentStatus.pending, + payment_date=None, + notes='Remaining balance to be paid at check-in' + ) + db.add(remaining_payment) + db.flush() + else: + # Create single pending full payment + full_payment = Payment( + booking_id=booking.id, + amount=final_total_price, + payment_method=payment_method_enum, + payment_type=PaymentType.full, + payment_status=PaymentStatus.pending, + payment_date=None, + notes='Payment to be made at check-in' + ) + db.add(full_payment) + db.flush() + + # Add service usages if any + if services: + from ..models.service import Service + for service_item in services: + service_id = service_item.get('service_id') + quantity = service_item.get('quantity', 1) + if not service_id: + continue + service = db.query(Service).filter(Service.id == service_id).first() + if not service or not service.is_active: + continue + unit_price = float(service.price) + total_price_service = unit_price * quantity + service_usage = ServiceUsage( + booking_id=booking.id, + service_id=service_id, + quantity=quantity, + unit_price=unit_price, + total_price=total_price_service + ) + db.add(service_usage) + + db.commit() + db.refresh(booking) + + # Load booking with relationships + from sqlalchemy.orm import joinedload, selectinload + booking = db.query(Booking).options( + joinedload(Booking.payments), + selectinload(Booking.service_usages).selectinload(ServiceUsage.service), + joinedload(Booking.user), + joinedload(Booking.room).joinedload(Room.room_type) + ).filter(Booking.id == booking.id).first() + + # Build response + payment_method_from_payments = None + payment_status_from_payments = 'unpaid' + if booking.payments: + latest_payment = sorted(booking.payments, key=lambda p: p.created_at, reverse=True)[0] + if isinstance(latest_payment.payment_method, PaymentMethod): + payment_method_from_payments = latest_payment.payment_method.value + elif hasattr(latest_payment.payment_method, 'value'): + payment_method_from_payments = latest_payment.payment_method.value + else: + payment_method_from_payments = str(latest_payment.payment_method) + if latest_payment.payment_status == PaymentStatus.completed: + payment_status_from_payments = 'paid' + elif latest_payment.payment_status == PaymentStatus.refunded: + payment_status_from_payments = 'refunded' + + final_payment_method = payment_method_from_payments if payment_method_from_payments else payment_method + + booking_dict = { + 'id': booking.id, + 'booking_number': booking.booking_number, + 'user_id': booking.user_id, + 'room_id': booking.room_id, + 'check_in_date': booking.check_in_date.strftime('%Y-%m-%d') if booking.check_in_date else None, + 'check_out_date': booking.check_out_date.strftime('%Y-%m-%d') if booking.check_out_date else None, + 'guest_count': booking.num_guests, + 'total_price': float(booking.total_price) if booking.total_price else 0.0, + 'status': booking.status.value if isinstance(booking.status, BookingStatus) else booking.status, + 'payment_method': final_payment_method, + 'payment_status': payment_status_from_payments, + 'deposit_paid': booking.deposit_paid, + 'requires_deposit': booking.requires_deposit, + 'notes': booking.special_requests, + 'guest_info': { + 'full_name': booking.user.full_name if booking.user else '', + 'email': booking.user.email if booking.user else '', + 'phone': booking.user.phone if booking.user else '' + }, + 'createdAt': booking.created_at.isoformat() if booking.created_at else None, + 'updatedAt': booking.updated_at.isoformat() if booking.updated_at else None, + 'created_at': booking.created_at.isoformat() if booking.created_at else None + } + + if booking.payments: + booking_dict['payments'] = [ + { + 'id': p.id, + 'booking_id': p.booking_id, + 'amount': float(p.amount) if p.amount else 0.0, + 'payment_method': p.payment_method.value if isinstance(p.payment_method, PaymentMethod) else p.payment_method.value if hasattr(p.payment_method, 'value') else str(p.payment_method), + 'payment_type': p.payment_type.value if isinstance(p.payment_type, PaymentType) else p.payment_type, + 'deposit_percentage': p.deposit_percentage, + 'payment_status': p.payment_status.value if isinstance(p.payment_status, PaymentStatus) else p.payment_status, + 'transaction_id': p.transaction_id, + 'payment_date': p.payment_date.isoformat() if p.payment_date else None, + 'notes': p.notes, + 'created_at': p.created_at.isoformat() if p.created_at else None + } for p in booking.payments + ] + + service_usages = getattr(booking, 'service_usages', None) + if service_usages and len(service_usages) > 0: + booking_dict['service_usages'] = [ + { + 'id': su.id, + 'service_id': su.service_id, + 'service_name': su.service.name if hasattr(su, 'service') and su.service else 'Unknown Service', + 'quantity': su.quantity, + 'unit_price': float(su.unit_price) if su.unit_price else 0.0, + 'total_price': float(su.total_price) if su.total_price else 0.0 + } for su in service_usages + ] + else: + booking_dict['service_usages'] = [] + + if booking.room: + booking_dict['room'] = { + 'id': booking.room.id, + 'room_number': booking.room.room_number, + 'floor': booking.room.floor + } + if booking.room.room_type: + booking_dict['room']['room_type'] = { + 'id': booking.room.room_type.id, + 'name': booking.room.room_type.name, + 'base_price': float(booking.room.room_type.base_price) if booking.room.room_type.base_price else 0.0, + 'capacity': booking.room.room_type.capacity + } + + return { + 'success': True, + 'data': {'booking': booking_dict}, + 'message': f'Booking created successfully by {current_user.full_name}' + } + except HTTPException: + raise + except Exception as e: + import logging + import traceback + logger = logging.getLogger(__name__) + logger.error(f'Error creating booking (admin/staff): {str(e)}') + logger.error(f'Traceback: {traceback.format_exc()}') + db.rollback() raise HTTPException(status_code=500, detail=str(e)) \ No newline at end of file diff --git a/Frontend/src/components/admin/CreateBookingModal.tsx b/Frontend/src/components/admin/CreateBookingModal.tsx new file mode 100644 index 00000000..108bf64c --- /dev/null +++ b/Frontend/src/components/admin/CreateBookingModal.tsx @@ -0,0 +1,553 @@ +import React, { useState, useEffect } from 'react'; +import { X, Search, Calendar, Users, DollarSign, CreditCard, FileText, User } from 'lucide-react'; +import { bookingService, roomService, userService } from '../../services/api'; +import type { Room } from '../../services/api/roomService'; +import type { User as UserType } from '../../services/api/userService'; +import { toast } from 'react-toastify'; +import { useFormatCurrency } from '../../hooks/useFormatCurrency'; +import DatePicker from 'react-datepicker'; +import 'react-datepicker/dist/react-datepicker.css'; + +interface CreateBookingModalProps { + isOpen: boolean; + onClose: () => void; + onSuccess: () => void; +} + +const CreateBookingModal: React.FC = ({ + isOpen, + onClose, + onSuccess, +}) => { + const { formatCurrency } = useFormatCurrency(); + const [loading, setLoading] = useState(false); + const [searchingRooms, setSearchingRooms] = useState(false); + const [searchingUsers, setSearchingUsers] = useState(false); + + // Form state + const [selectedUser, setSelectedUser] = useState(null); + const [userSearch, setUserSearch] = useState(''); + const [userSearchResults, setUserSearchResults] = useState([]); + const [showUserResults, setShowUserResults] = useState(false); + + const [selectedRoom, setSelectedRoom] = useState(null); + const [checkInDate, setCheckInDate] = useState(null); + const [checkOutDate, setCheckOutDate] = useState(null); + const [guestCount, setGuestCount] = useState(1); + const [totalPrice, setTotalPrice] = useState(0); + const [paymentMethod, setPaymentMethod] = useState<'cash' | 'stripe' | 'paypal'>('cash'); + const [paymentStatus, setPaymentStatus] = useState<'full' | 'deposit' | 'unpaid'>('unpaid'); + const [bookingStatus, setBookingStatus] = useState<'pending' | 'confirmed'>('confirmed'); + const [specialRequests, setSpecialRequests] = useState(''); + const [availableRooms, setAvailableRooms] = useState([]); + + // Search for users + useEffect(() => { + if (userSearch.length >= 2) { + const timeoutId = setTimeout(async () => { + try { + setSearchingUsers(true); + const response = await userService.getUsers({ + search: userSearch, + role: 'customer', + limit: 10, + }); + setUserSearchResults(response.data.users || []); + setShowUserResults(true); + } catch (error: any) { + console.error('Error searching users:', error); + } finally { + setSearchingUsers(false); + } + }, 300); + + return () => clearTimeout(timeoutId); + } else { + setUserSearchResults([]); + setShowUserResults(false); + } + }, [userSearch]); + + // Search for available rooms when dates are selected + useEffect(() => { + if (checkInDate && checkOutDate && checkInDate < checkOutDate) { + const searchRooms = async () => { + try { + setSearchingRooms(true); + const checkInStr = checkInDate.toISOString().split('T')[0]; + const checkOutStr = checkOutDate.toISOString().split('T')[0]; + + const response = await roomService.searchAvailableRooms({ + from: checkInStr, + to: checkOutStr, + limit: 50, + }); + + setAvailableRooms(response.data.rooms || []); + + // Auto-calculate price if room is selected + if (selectedRoom) { + const nights = Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24)); + const roomPrice = selectedRoom.room_type?.base_price || selectedRoom.price || 0; + setTotalPrice(roomPrice * nights); + } + } catch (error: any) { + console.error('Error searching rooms:', error); + toast.error('Failed to search available rooms'); + } finally { + setSearchingRooms(false); + } + }; + + searchRooms(); + } else { + setAvailableRooms([]); + } + }, [checkInDate, checkOutDate, selectedRoom]); + + // Calculate price when room or dates change + useEffect(() => { + if (selectedRoom && checkInDate && checkOutDate && checkInDate < checkOutDate) { + const nights = Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24)); + const roomPrice = selectedRoom.room_type?.base_price || selectedRoom.price || 0; + setTotalPrice(roomPrice * nights); + } + }, [selectedRoom, checkInDate, checkOutDate]); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + + if (!selectedUser) { + toast.error('Please select a guest'); + return; + } + + if (!selectedRoom) { + toast.error('Please select a room'); + return; + } + + if (!checkInDate || !checkOutDate) { + toast.error('Please select check-in and check-out dates'); + return; + } + + if (checkInDate >= checkOutDate) { + toast.error('Check-out date must be after check-in date'); + return; + } + + if (totalPrice <= 0) { + toast.error('Total price must be greater than 0'); + return; + } + + try { + setLoading(true); + + const bookingData = { + user_id: selectedUser.id, + room_id: selectedRoom.id, + check_in_date: checkInDate.toISOString().split('T')[0], + check_out_date: checkOutDate.toISOString().split('T')[0], + guest_count: guestCount, + total_price: totalPrice, + payment_method: paymentMethod, + payment_status: paymentStatus, // 'full', 'deposit', or 'unpaid' + notes: specialRequests, + status: bookingStatus, + }; + + await bookingService.adminCreateBooking(bookingData); + toast.success('Booking created successfully!'); + handleClose(); + onSuccess(); + } catch (error: any) { + toast.error(error.response?.data?.detail || error.response?.data?.message || 'Failed to create booking'); + } finally { + setLoading(false); + } + }; + + const handleClose = () => { + setSelectedUser(null); + setUserSearch(''); + setUserSearchResults([]); + setShowUserResults(false); + setSelectedRoom(null); + setCheckInDate(null); + setCheckOutDate(null); + setGuestCount(1); + setTotalPrice(0); + setPaymentMethod('cash'); + setPaymentStatus('unpaid'); + setBookingStatus('confirmed'); + setSpecialRequests(''); + setAvailableRooms([]); + onClose(); + }; + + const handleSelectUser = (user: UserType) => { + setSelectedUser(user); + setUserSearch(user.full_name); + setShowUserResults(false); + }; + + if (!isOpen) return null; + + return ( +
+
+ {/* Header */} +
+
+
+

Create New Booking

+

Mark a room as booked for specific dates

+
+ +
+
+ + {/* Form */} +
+
+ {/* Guest Selection */} +
+ +
+ + setUserSearch(e.target.value)} + onFocus={() => setShowUserResults(userSearchResults.length > 0)} + className="w-full pl-10 pr-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all" + /> + {showUserResults && userSearchResults.length > 0 && ( +
+ {userSearchResults.map((user) => ( + + ))} +
+ )} + {searchingUsers && ( +
+
+
+ )} +
+ {selectedUser && ( +
+
{selectedUser.full_name}
+
{selectedUser.email}
+
+ )} +
+ + {/* Date Selection */} +
+
+ + setCheckInDate(date)} + minDate={new Date()} + dateFormat="yyyy-MM-dd" + className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all" + placeholderText="Select check-in date" + /> +
+
+ + setCheckOutDate(date)} + minDate={checkInDate || new Date()} + dateFormat="yyyy-MM-dd" + className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all" + placeholderText="Select check-out date" + /> +
+
+ + {/* Room Selection */} +
+ + {searchingRooms && checkInDate && checkOutDate ? ( +
+
+ Searching available rooms... +
+ ) : availableRooms.length > 0 ? ( + + ) : checkInDate && checkOutDate ? ( +
+ No available rooms found for the selected dates. Please try different dates. +
+ ) : ( +
+ Please select check-in and check-out dates to see available rooms +
+ )} +
+ + {/* Guest Count and Price */} +
+
+ + setGuestCount(parseInt(e.target.value) || 1)} + className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all" + /> +
+
+ + setTotalPrice(parseFloat(e.target.value) || 0)} + className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all" + /> + {selectedRoom && checkInDate && checkOutDate && ( +

+ {formatCurrency(totalPrice)} for{' '} + {Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))} night(s) +

+ )} +
+
+ + {/* Payment Method and Payment Status */} +
+
+ + +
+
+ + +
+
+ + {/* Booking Summary */} + {totalPrice > 0 && ( +
+

+ + Booking Summary +

+ + {selectedRoom && checkInDate && checkOutDate && ( +
+
+ Room: + + {selectedRoom.room_type?.name || 'Standard Room'} - Room {selectedRoom.room_number} + +
+
+ Room price/night: + + {formatCurrency(selectedRoom.room_type?.base_price || selectedRoom.price || 0)} + +
+
+ Nights: + + {Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))} night(s) + +
+
+ Room Total: + + {formatCurrency((selectedRoom.room_type?.base_price || selectedRoom.price || 0) * Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24)))} + +
+
+ )} + +
+
+ Subtotal: + {formatCurrency(totalPrice)} +
+
+ Total: + {formatCurrency(totalPrice)} +
+
+ + {paymentStatus === 'deposit' && ( +
+
+ Deposit to pay (20%): + {formatCurrency(totalPrice * 0.2)} +
+
+ Remaining balance: + {formatCurrency(totalPrice * 0.8)} +
+

+ Pay 20% deposit to secure booking, remaining balance on arrival +

+
+ )} + + {paymentStatus === 'full' && ( +
+
+ Amount to pay: + {formatCurrency(totalPrice)} +
+

+ Full payment will be marked as completed +

+
+ )} + + {paymentStatus === 'unpaid' && ( +
+
+ Payment due at check-in: + {formatCurrency(totalPrice)} +
+

+ Guest will pay the full amount upon arrival +

+
+ )} +
+ )} + + {/* Booking Status */} +
+ + +
+ + {/* Special Requests */} +
+ +