updates
This commit is contained in:
Binary file not shown.
@@ -190,15 +190,15 @@ async def create_booking(booking_data: dict, current_user: User=Depends(get_curr
|
|||||||
if overlapping:
|
if overlapping:
|
||||||
raise HTTPException(status_code=409, detail='Room already booked for the selected dates')
|
raise HTTPException(status_code=409, detail='Room already booked for the selected dates')
|
||||||
booking_number = generate_booking_number()
|
booking_number = generate_booking_number()
|
||||||
requires_deposit = payment_method == 'cash'
|
|
||||||
deposit_percentage = 20 if requires_deposit else 0
|
# Calculate room price
|
||||||
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
|
|
||||||
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
|
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
|
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
|
room_total = room_price * number_of_nights
|
||||||
|
|
||||||
|
# Calculate services total if any
|
||||||
services = booking_data.get('services', [])
|
services = booking_data.get('services', [])
|
||||||
services_total = 0.0
|
services_total = 0.0
|
||||||
if services:
|
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()
|
service = db.query(Service).filter(Service.id == service_id).first()
|
||||||
if service and service.is_active:
|
if service and service.is_active:
|
||||||
services_total += float(service.price) * quantity
|
services_total += float(service.price) * quantity
|
||||||
|
|
||||||
original_price = room_total + services_total
|
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 ''
|
final_notes = notes or ''
|
||||||
if promotion_code:
|
if promotion_code:
|
||||||
promotion_note = f'Promotion Code: {promotion_code}'
|
promotion_note = f'Promotion Code: {promotion_code}'
|
||||||
final_notes = f'{promotion_note}\n{final_notes}'.strip() if final_notes else promotion_note
|
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.add(booking)
|
||||||
db.flush()
|
db.flush()
|
||||||
if payment_method in ['stripe', 'paypal']:
|
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')
|
logger.warning(f'Unexpected payment_method: {payment_method}, defaulting to stripe')
|
||||||
payment_method_enum = PaymentMethod.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}')
|
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.add(payment)
|
||||||
db.flush()
|
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)}')
|
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_notes = f'{promotion_note}\n{invoice_notes}'.strip() if invoice_notes else promotion_note
|
||||||
invoice_kwargs['notes'] = invoice_notes
|
invoice_kwargs['notes'] = invoice_notes
|
||||||
if payment_method == 'cash':
|
if payment_method == 'cash':
|
||||||
deposit_amount = float(total_price) * 0.2
|
deposit_amount = final_total_price * 0.2
|
||||||
remaining_amount = float(total_price) * 0.8
|
remaining_amount = final_total_price * 0.8
|
||||||
deposit_discount = booking_discount * 0.2 if booking_discount > 0 else 0.0
|
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
|
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)
|
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'))])
|
@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)):
|
async def update_booking(id: int, booking_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
|
||||||
try:
|
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:
|
if not booking:
|
||||||
raise HTTPException(status_code=404, detail='Booking not found')
|
raise HTTPException(status_code=404, detail='Booking not found')
|
||||||
old_status = booking.status
|
old_status = booking.status
|
||||||
@@ -506,7 +552,17 @@ async def update_booking(id: int, booking_data: dict, current_user: User=Depends
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
raise HTTPException(status_code=400, detail='Invalid status')
|
raise HTTPException(status_code=400, detail='Invalid status')
|
||||||
db.commit()
|
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
|
payment_warning = None
|
||||||
if status_value and old_status != booking.status and (booking.status == BookingStatus.checked_in):
|
if status_value and old_status != booking.status and (booking.status == BookingStatus.checked_in):
|
||||||
payment_balance = calculate_booking_payment_balance(booking)
|
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]:
|
if booking.status in [BookingStatus.confirmed, BookingStatus.cancelled]:
|
||||||
try:
|
try:
|
||||||
from ..models.system_settings import SystemSettings
|
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_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')
|
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:
|
if booking.status == BookingStatus.confirmed:
|
||||||
from sqlalchemy.orm import selectinload
|
room = booking.room
|
||||||
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_type_name = room.room_type.name if room and room.room_type else '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_setting = db.query(SystemSettings).filter(SystemSettings.key == 'platform_currency').first()
|
||||||
currency = currency_setting.value if currency_setting and currency_setting.value else 'USD'
|
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_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)
|
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)
|
guest_name = booking.user.full_name if booking.user else 'Guest'
|
||||||
await send_email(to=booking.user.email if booking.user else None, subject=f'Booking Confirmed - {booking.booking_number}', html=email_html)
|
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:
|
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)
|
guest_name = booking.user.full_name if booking.user else 'Guest'
|
||||||
await send_email(to=booking.user.email if booking.user else None, subject=f'Booking Cancelled - {booking.booking_number}', html=email_html)
|
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:
|
except Exception as e:
|
||||||
import logging
|
import logging
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.error(f'Failed to send status change email: {e}')
|
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:
|
if payment_warning:
|
||||||
response_data['warning'] = payment_warning
|
response_data['warning'] = payment_warning
|
||||||
response_data['message'] = 'Booking updated successfully. ⚠️ Payment reminder: Guest has remaining balance.'
|
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:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
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()
|
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}')
|
@router.get('/check/{booking_number}')
|
||||||
async def check_booking_by_number(booking_number: str, db: Session=Depends(get_db)):
|
async def check_booking_by_number(booking_number: str, db: Session=Depends(get_db)):
|
||||||
@@ -590,3 +663,406 @@ async def check_booking_by_number(booking_number: str, db: Session=Depends(get_d
|
|||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(status_code=500, detail=str(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))
|
||||||
553
Frontend/src/components/admin/CreateBookingModal.tsx
Normal file
553
Frontend/src/components/admin/CreateBookingModal.tsx
Normal file
@@ -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<CreateBookingModalProps> = ({
|
||||||
|
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<UserType | null>(null);
|
||||||
|
const [userSearch, setUserSearch] = useState('');
|
||||||
|
const [userSearchResults, setUserSearchResults] = useState<UserType[]>([]);
|
||||||
|
const [showUserResults, setShowUserResults] = useState(false);
|
||||||
|
|
||||||
|
const [selectedRoom, setSelectedRoom] = useState<Room | null>(null);
|
||||||
|
const [checkInDate, setCheckInDate] = useState<Date | null>(null);
|
||||||
|
const [checkOutDate, setCheckOutDate] = useState<Date | null>(null);
|
||||||
|
const [guestCount, setGuestCount] = useState(1);
|
||||||
|
const [totalPrice, setTotalPrice] = useState<number>(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<Room[]>([]);
|
||||||
|
|
||||||
|
// 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 (
|
||||||
|
<div className="fixed inset-0 bg-black/70 backdrop-blur-md flex items-center justify-center z-50 p-4 animate-fade-in">
|
||||||
|
<div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden animate-scale-in border border-slate-200">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 px-8 py-6 border-b border-slate-700">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-3xl font-bold text-amber-100 mb-1">Create New Booking</h2>
|
||||||
|
<p className="text-amber-200/80 text-sm font-light">Mark a room as booked for specific dates</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleClose}
|
||||||
|
className="w-10 h-10 flex items-center justify-center rounded-xl text-amber-100 hover:text-white hover:bg-slate-700/50 transition-all duration-200 border border-slate-600 hover:border-amber-400"
|
||||||
|
>
|
||||||
|
<X className="w-6 h-6" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Form */}
|
||||||
|
<form onSubmit={handleSubmit} className="p-8 overflow-y-auto max-h-[calc(90vh-120px)]">
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Guest Selection */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<User className="w-5 h-5 text-amber-600" />
|
||||||
|
Guest / Customer *
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search for customer by name or email..."
|
||||||
|
value={userSearch}
|
||||||
|
onChange={(e) => 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 && (
|
||||||
|
<div className="absolute z-10 w-full mt-2 bg-white border-2 border-slate-200 rounded-xl shadow-lg max-h-60 overflow-y-auto">
|
||||||
|
{userSearchResults.map((user) => (
|
||||||
|
<button
|
||||||
|
key={user.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleSelectUser(user)}
|
||||||
|
className="w-full text-left px-4 py-3 hover:bg-amber-50 transition-colors border-b border-slate-100 last:border-0"
|
||||||
|
>
|
||||||
|
<div className="font-semibold text-slate-900">{user.full_name}</div>
|
||||||
|
<div className="text-sm text-slate-500">{user.email}</div>
|
||||||
|
{user.phone_number && (
|
||||||
|
<div className="text-xs text-slate-400">{user.phone_number}</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{searchingUsers && (
|
||||||
|
<div className="absolute right-3 top-1/2 transform -translate-y-1/2">
|
||||||
|
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-amber-600"></div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{selectedUser && (
|
||||||
|
<div className="mt-2 p-3 bg-amber-50 rounded-lg border border-amber-200">
|
||||||
|
<div className="font-semibold text-slate-900">{selectedUser.full_name}</div>
|
||||||
|
<div className="text-sm text-slate-600">{selectedUser.email}</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Date Selection */}
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<Calendar className="w-5 h-5 text-amber-600" />
|
||||||
|
Check-in Date *
|
||||||
|
</label>
|
||||||
|
<DatePicker
|
||||||
|
selected={checkInDate}
|
||||||
|
onChange={(date: Date | null) => 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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<Calendar className="w-5 h-5 text-amber-600" />
|
||||||
|
Check-out Date *
|
||||||
|
</label>
|
||||||
|
<DatePicker
|
||||||
|
selected={checkOutDate}
|
||||||
|
onChange={(date: Date | null) => 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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Room Selection */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2">
|
||||||
|
Room *
|
||||||
|
</label>
|
||||||
|
{searchingRooms && checkInDate && checkOutDate ? (
|
||||||
|
<div className="p-4 text-center text-slate-500">
|
||||||
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto mb-2"></div>
|
||||||
|
Searching available rooms...
|
||||||
|
</div>
|
||||||
|
) : availableRooms.length > 0 ? (
|
||||||
|
<select
|
||||||
|
value={selectedRoom?.id || ''}
|
||||||
|
onChange={(e) => {
|
||||||
|
const room = availableRooms.find((r) => r.id === parseInt(e.target.value));
|
||||||
|
setSelectedRoom(room || null);
|
||||||
|
}}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<option value="">Select a room</option>
|
||||||
|
{availableRooms.map((room) => (
|
||||||
|
<option key={room.id} value={room.id}>
|
||||||
|
Room {room.room_number} - {room.room_type?.name || 'Standard'} - {formatCurrency(room.room_type?.base_price || room.price || 0)}/night
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : checkInDate && checkOutDate ? (
|
||||||
|
<div className="p-4 bg-yellow-50 border border-yellow-200 rounded-xl text-yellow-800">
|
||||||
|
No available rooms found for the selected dates. Please try different dates.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="p-4 bg-slate-50 border border-slate-200 rounded-xl text-slate-500">
|
||||||
|
Please select check-in and check-out dates to see available rooms
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Guest Count and Price */}
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<Users className="w-5 h-5 text-amber-600" />
|
||||||
|
Number of Guests *
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
value={guestCount}
|
||||||
|
onChange={(e) => 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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<DollarSign className="w-5 h-5 text-amber-600" />
|
||||||
|
Total Price *
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
value={totalPrice}
|
||||||
|
onChange={(e) => 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 && (
|
||||||
|
<p className="text-xs text-slate-500 mt-1">
|
||||||
|
{formatCurrency(totalPrice)} for{' '}
|
||||||
|
{Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))} night(s)
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Payment Method and Payment Status */}
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<CreditCard className="w-5 h-5 text-amber-600" />
|
||||||
|
Payment Method *
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={paymentMethod}
|
||||||
|
onChange={(e) => setPaymentMethod(e.target.value as 'cash' | 'stripe' | 'paypal')}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<option value="cash">Cash</option>
|
||||||
|
<option value="stripe">Card (Stripe)</option>
|
||||||
|
<option value="paypal">PayPal</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<DollarSign className="w-5 h-5 text-amber-600" />
|
||||||
|
Payment Status *
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={paymentStatus}
|
||||||
|
onChange={(e) => setPaymentStatus(e.target.value as 'full' | 'deposit' | 'unpaid')}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<option value="unpaid">Unpaid (Pay at Check-in)</option>
|
||||||
|
<option value="deposit">20% Deposit Only (Rest at Check-in)</option>
|
||||||
|
<option value="full">Fully Paid</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Booking Summary */}
|
||||||
|
{totalPrice > 0 && (
|
||||||
|
<div className="bg-gradient-to-br from-slate-50 to-amber-50/30 rounded-xl border-2 border-amber-200/50 p-6 space-y-3">
|
||||||
|
<h3 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
|
||||||
|
<FileText className="w-5 h-5 text-amber-600" />
|
||||||
|
Booking Summary
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
{selectedRoom && checkInDate && checkOutDate && (
|
||||||
|
<div className="space-y-2 text-sm">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-slate-600">Room:</span>
|
||||||
|
<span className="font-semibold text-slate-900">
|
||||||
|
{selectedRoom.room_type?.name || 'Standard Room'} - Room {selectedRoom.room_number}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-slate-600">Room price/night:</span>
|
||||||
|
<span className="font-semibold text-slate-900">
|
||||||
|
{formatCurrency(selectedRoom.room_type?.base_price || selectedRoom.price || 0)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-slate-600">Nights:</span>
|
||||||
|
<span className="font-semibold text-slate-900">
|
||||||
|
{Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))} night(s)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center border-t border-amber-200 pt-2">
|
||||||
|
<span className="text-slate-600">Room Total:</span>
|
||||||
|
<span className="font-semibold text-slate-900">
|
||||||
|
{formatCurrency((selectedRoom.room_type?.base_price || selectedRoom.price || 0) * Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24)))}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="border-t border-amber-200 pt-3 space-y-2">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-slate-600">Subtotal:</span>
|
||||||
|
<span className="font-semibold text-slate-900">{formatCurrency(totalPrice)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-slate-600">Total:</span>
|
||||||
|
<span className="text-lg font-bold text-slate-900">{formatCurrency(totalPrice)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{paymentStatus === 'deposit' && (
|
||||||
|
<div className="bg-amber-100/50 rounded-lg p-4 border border-amber-300 space-y-2">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-amber-800 font-semibold">Deposit to pay (20%):</span>
|
||||||
|
<span className="text-lg font-bold text-amber-900">{formatCurrency(totalPrice * 0.2)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-amber-700">Remaining balance:</span>
|
||||||
|
<span className="font-semibold text-amber-900">{formatCurrency(totalPrice * 0.8)}</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-amber-700 mt-2 italic">
|
||||||
|
Pay 20% deposit to secure booking, remaining balance on arrival
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{paymentStatus === 'full' && (
|
||||||
|
<div className="bg-green-100/50 rounded-lg p-4 border border-green-300">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-green-800 font-semibold">Amount to pay:</span>
|
||||||
|
<span className="text-lg font-bold text-green-900">{formatCurrency(totalPrice)}</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-green-700 mt-2 italic">
|
||||||
|
Full payment will be marked as completed
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{paymentStatus === 'unpaid' && (
|
||||||
|
<div className="bg-blue-100/50 rounded-lg p-4 border border-blue-300">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<span className="text-blue-800 font-semibold">Payment due at check-in:</span>
|
||||||
|
<span className="text-lg font-bold text-blue-900">{formatCurrency(totalPrice)}</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-blue-700 mt-2 italic">
|
||||||
|
Guest will pay the full amount upon arrival
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Booking Status */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2">
|
||||||
|
Booking Status *
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={bookingStatus}
|
||||||
|
onChange={(e) => setBookingStatus(e.target.value as 'pending' | 'confirmed')}
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
<option value="confirmed">Confirmed</option>
|
||||||
|
<option value="pending">Pending</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Special Requests */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
|
||||||
|
<FileText className="w-5 h-5 text-amber-600" />
|
||||||
|
Special Requests / Notes
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={specialRequests}
|
||||||
|
onChange={(e) => setSpecialRequests(e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
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 resize-none"
|
||||||
|
placeholder="Any special requests or notes..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<div className="mt-8 pt-6 border-t border-slate-200 flex justify-end gap-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleClose}
|
||||||
|
className="px-6 py-3 bg-slate-200 text-slate-700 rounded-xl font-semibold hover:bg-slate-300 transition-all duration-200"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-lg hover:shadow-xl"
|
||||||
|
>
|
||||||
|
{loading ? 'Creating...' : 'Create Booking'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default CreateBookingModal;
|
||||||
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Search, Eye, XCircle, CheckCircle, Loader2, FileText } from 'lucide-react';
|
import { Search, Eye, XCircle, CheckCircle, Loader2, FileText, Plus } from 'lucide-react';
|
||||||
import { bookingService, Booking, invoiceService } from '../../services/api';
|
import { bookingService, Booking, invoiceService } from '../../services/api';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import Loading from '../../components/common/Loading';
|
import Loading from '../../components/common/Loading';
|
||||||
@@ -7,6 +7,7 @@ import Pagination from '../../components/common/Pagination';
|
|||||||
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
|
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
|
||||||
import { parseDateLocal } from '../../utils/format';
|
import { parseDateLocal } from '../../utils/format';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import CreateBookingModal from '../../components/admin/CreateBookingModal';
|
||||||
|
|
||||||
const BookingManagementPage: React.FC = () => {
|
const BookingManagementPage: React.FC = () => {
|
||||||
const { formatCurrency } = useFormatCurrency();
|
const { formatCurrency } = useFormatCurrency();
|
||||||
@@ -18,6 +19,7 @@ const BookingManagementPage: React.FC = () => {
|
|||||||
const [updatingBookingId, setUpdatingBookingId] = useState<number | null>(null);
|
const [updatingBookingId, setUpdatingBookingId] = useState<number | null>(null);
|
||||||
const [cancellingBookingId, setCancellingBookingId] = useState<number | null>(null);
|
const [cancellingBookingId, setCancellingBookingId] = useState<number | null>(null);
|
||||||
const [creatingInvoice, setCreatingInvoice] = useState(false);
|
const [creatingInvoice, setCreatingInvoice] = useState(false);
|
||||||
|
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||||
const [filters, setFilters] = useState({
|
const [filters, setFilters] = useState({
|
||||||
search: '',
|
search: '',
|
||||||
status: '',
|
status: '',
|
||||||
@@ -156,15 +158,26 @@ const BookingManagementPage: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
|
<div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
|
||||||
{}
|
{/* Header with Create Button */}
|
||||||
<div className="animate-fade-in">
|
<div className="animate-fade-in">
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-6">
|
||||||
|
<div className="flex-1">
|
||||||
<div className="flex items-center gap-3 mb-2">
|
<div className="flex items-center gap-3 mb-2">
|
||||||
<div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
|
<div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
|
||||||
<h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
|
<h1 className="text-3xl sm:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
|
||||||
Booking Management
|
Booking Management
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-slate-600 mt-3 text-lg font-light">Manage and track all hotel bookings with precision</p>
|
<p className="text-slate-600 mt-3 text-base sm:text-lg font-light">Manage and track all hotel bookings with precision</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreateModal(true)}
|
||||||
|
className="flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl whitespace-nowrap w-full sm:w-auto"
|
||||||
|
>
|
||||||
|
<Plus className="w-5 h-5" />
|
||||||
|
Create Booking
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{}
|
{}
|
||||||
@@ -677,6 +690,16 @@ const BookingManagementPage: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Create Booking Modal */}
|
||||||
|
<CreateBookingModal
|
||||||
|
isOpen={showCreateModal}
|
||||||
|
onClose={() => setShowCreateModal(false)}
|
||||||
|
onSuccess={() => {
|
||||||
|
setShowCreateModal(false);
|
||||||
|
fetchBookings();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import Pagination from '../../components/common/Pagination';
|
|||||||
import apiClient from '../../services/api/apiClient';
|
import apiClient from '../../services/api/apiClient';
|
||||||
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
|
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
|
||||||
import { parseDateLocal } from '../../utils/format';
|
import { parseDateLocal } from '../../utils/format';
|
||||||
|
import CreateBookingModal from '../../components/admin/CreateBookingModal';
|
||||||
|
|
||||||
type ReceptionTab = 'overview' | 'check-in' | 'check-out' | 'bookings' | 'rooms' | 'services';
|
type ReceptionTab = 'overview' | 'check-in' | 'check-out' | 'bookings' | 'rooms' | 'services';
|
||||||
|
|
||||||
@@ -88,6 +89,7 @@ const ReceptionDashboardPage: React.FC = () => {
|
|||||||
const [bookingTotalPages, setBookingTotalPages] = useState(1);
|
const [bookingTotalPages, setBookingTotalPages] = useState(1);
|
||||||
const [bookingTotalItems, setBookingTotalItems] = useState(0);
|
const [bookingTotalItems, setBookingTotalItems] = useState(0);
|
||||||
const bookingItemsPerPage = 5;
|
const bookingItemsPerPage = 5;
|
||||||
|
const [showCreateBookingModal, setShowCreateBookingModal] = useState(false);
|
||||||
|
|
||||||
|
|
||||||
const [rooms, setRooms] = useState<Room[]>([]);
|
const [rooms, setRooms] = useState<Room[]>([]);
|
||||||
@@ -1949,7 +1951,8 @@ const ReceptionDashboardPage: React.FC = () => {
|
|||||||
|
|
||||||
{}
|
{}
|
||||||
<div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
|
<div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
|
||||||
<div className="space-y-3">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||||
|
<div className="space-y-3 flex-1">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="p-2.5 rounded-xl bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-200/40">
|
<div className="p-2.5 rounded-xl bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-200/40">
|
||||||
<Calendar className="w-6 h-6 text-blue-600" />
|
<Calendar className="w-6 h-6 text-blue-600" />
|
||||||
@@ -1960,6 +1963,14 @@ const ReceptionDashboardPage: React.FC = () => {
|
|||||||
Manage and track all hotel bookings with precision
|
Manage and track all hotel bookings with precision
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowCreateBookingModal(true)}
|
||||||
|
className="flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl whitespace-nowrap w-full sm:w-auto"
|
||||||
|
>
|
||||||
|
<Plus className="w-5 h-5" />
|
||||||
|
Create Booking
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{}
|
{}
|
||||||
@@ -3233,6 +3244,16 @@ const ReceptionDashboardPage: React.FC = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Create Booking Modal */}
|
||||||
|
<CreateBookingModal
|
||||||
|
isOpen={showCreateBookingModal}
|
||||||
|
onClose={() => setShowCreateBookingModal(false)}
|
||||||
|
onSuccess={() => {
|
||||||
|
setShowCreateBookingModal(false);
|
||||||
|
fetchBookings();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -283,6 +283,16 @@ export const generateQRCode = (
|
|||||||
return qrUrl;
|
return qrUrl;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const adminCreateBooking = async (
|
||||||
|
bookingData: BookingData & { user_id: number; status?: string }
|
||||||
|
): Promise<BookingResponse> => {
|
||||||
|
const response = await apiClient.post<BookingResponse>(
|
||||||
|
'/bookings/admin-create',
|
||||||
|
bookingData
|
||||||
|
);
|
||||||
|
return response.data;
|
||||||
|
};
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
createBooking,
|
createBooking,
|
||||||
getMyBookings,
|
getMyBookings,
|
||||||
@@ -294,4 +304,5 @@ export default {
|
|||||||
generateQRCode,
|
generateQRCode,
|
||||||
getAllBookings,
|
getAllBookings,
|
||||||
updateBooking,
|
updateBooking,
|
||||||
|
adminCreateBooking,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user