diff --git a/Backend/src/routes/__pycache__/booking_routes.cpython-312.pyc b/Backend/src/routes/__pycache__/booking_routes.cpython-312.pyc index 41c4675d..dcb49264 100644 Binary files a/Backend/src/routes/__pycache__/booking_routes.cpython-312.pyc and b/Backend/src/routes/__pycache__/booking_routes.cpython-312.pyc differ 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 */} +
+ +