Total Amount: {invoice.get('total_amount', 0):.2f}
-
Amount Paid: {invoice.get('amount_paid', 0):.2f}
-
Balance Due: {invoice.get('balance_due', 0):.2f}
-
-
-
-
-
-
- """
+from ..utils.email_templates import booking_confirmation_email_template, booking_status_changed_email_template
+router = APIRouter(prefix='/bookings', tags=['bookings'])
+def _generate_invoice_email_html(invoice: dict, is_proforma: bool=False) -> str:
+ invoice_type = 'Proforma Invoice' if is_proforma else 'Invoice'
+ items_html = ''.join([f for item in invoice.get('items', [])])
+ return f
def generate_booking_number() -> str:
- """Generate unique booking number"""
- prefix = "BK"
+ prefix = 'BK'
ts = int(datetime.utcnow().timestamp() * 1000)
rand = random.randint(1000, 9999)
- return f"{prefix}-{ts}-{rand}"
-
+ return f'{prefix}-{ts}-{rand}'
def calculate_booking_payment_balance(booking: Booking) -> dict:
- """Calculate total paid amount and remaining balance for a booking"""
total_paid = 0.0
if booking.payments:
- # Sum all completed payments
- total_paid = sum(
- float(payment.amount) if payment.amount else 0.0
- for payment in booking.payments
- if payment.payment_status == PaymentStatus.completed
- )
-
+ total_paid = sum((float(payment.amount) if payment.amount else 0.0 for payment in booking.payments if payment.payment_status == PaymentStatus.completed))
total_price = float(booking.total_price) if booking.total_price else 0.0
remaining_balance = total_price - total_paid
-
- return {
- "total_paid": total_paid,
- "total_price": total_price,
- "remaining_balance": remaining_balance,
- "is_fully_paid": remaining_balance <= 0.01, # Allow small floating point differences
- "payment_percentage": (total_paid / total_price * 100) if total_price > 0 else 0
- }
+ return {'total_paid': total_paid, 'total_price': total_price, 'remaining_balance': remaining_balance, 'is_fully_paid': remaining_balance <= 0.01, 'payment_percentage': total_paid / total_price * 100 if total_price > 0 else 0}
-
-@router.get("/")
-async def get_all_bookings(
- search: Optional[str] = Query(None),
- status_filter: Optional[str] = Query(None, alias="status"),
- startDate: Optional[str] = Query(None),
- endDate: Optional[str] = Query(None),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Get all bookings (Admin/Staff only)"""
+@router.get('/')
+async def get_all_bookings(search: Optional[str]=Query(None), status_filter: Optional[str]=Query(None, alias='status'), startDate: Optional[str]=Query(None), endDate: Optional[str]=Query(None), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
- query = db.query(Booking).options(
- selectinload(Booking.payments),
- joinedload(Booking.user),
- joinedload(Booking.room).joinedload(Room.room_type)
- )
-
- # Filter by search (booking_number)
+ query = db.query(Booking).options(selectinload(Booking.payments), joinedload(Booking.user), joinedload(Booking.room).joinedload(Room.room_type))
if search:
- query = query.filter(Booking.booking_number.like(f"%{search}%"))
-
- # Filter by status
+ query = query.filter(Booking.booking_number.like(f'%{search}%'))
if status_filter:
try:
query = query.filter(Booking.status == BookingStatus(status_filter))
except ValueError:
pass
-
- # Filter by date range
if startDate:
start = datetime.fromisoformat(startDate.replace('Z', '+00:00'))
query = query.filter(Booking.check_in_date >= start)
-
if endDate:
end = datetime.fromisoformat(endDate.replace('Z', '+00:00'))
query = query.filter(Booking.check_in_date <= end)
-
- # Get total count
total = query.count()
-
- # Apply pagination
offset = (page - 1) * limit
bookings = query.order_by(Booking.created_at.desc()).offset(offset).limit(limit).all()
-
- # Include related data
result = []
for booking in bookings:
- # Determine payment_method and payment_status from payments
payment_method_from_payments = None
- payment_status_from_payments = "unpaid"
+ payment_status_from_payments = 'unpaid'
if booking.payments:
latest_payment = max(booking.payments, key=lambda p: p.created_at if p.created_at else datetime.min)
if isinstance(latest_payment.payment_method, PaymentMethod):
@@ -253,132 +71,45 @@ async def get_all_bookings(
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"
+ payment_status_from_payments = 'paid'
elif latest_payment.payment_status == PaymentStatus.refunded:
- payment_status_from_payments = "refunded"
-
- 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,
- "num_guests": booking.num_guests,
- "guest_count": booking.num_guests, # Frontend expects guest_count
- "total_price": float(booking.total_price) if booking.total_price else 0.0,
- "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,
- "status": booking.status.value if isinstance(booking.status, BookingStatus) else booking.status,
- "payment_method": payment_method_from_payments if payment_method_from_payments else "cash",
- "payment_status": payment_status_from_payments,
- "deposit_paid": booking.deposit_paid,
- "requires_deposit": booking.requires_deposit,
- "special_requests": booking.special_requests,
- "notes": booking.special_requests, # Frontend expects notes
- "created_at": booking.created_at.isoformat() if booking.created_at else None,
- "createdAt": booking.created_at.isoformat() if booking.created_at else None,
- "updated_at": booking.updated_at.isoformat() if booking.updated_at else None,
- "updatedAt": booking.updated_at.isoformat() if booking.updated_at else None,
- }
-
- # Add user info
+ payment_status_from_payments = 'refunded'
+ 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, 'num_guests': booking.num_guests, 'guest_count': booking.num_guests, 'total_price': float(booking.total_price) if booking.total_price else 0.0, '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, 'status': booking.status.value if isinstance(booking.status, BookingStatus) else booking.status, 'payment_method': payment_method_from_payments if payment_method_from_payments else 'cash', 'payment_status': payment_status_from_payments, 'deposit_paid': booking.deposit_paid, 'requires_deposit': booking.requires_deposit, 'special_requests': booking.special_requests, 'notes': booking.special_requests, 'created_at': booking.created_at.isoformat() if booking.created_at else None, 'createdAt': booking.created_at.isoformat() if booking.created_at else None, 'updated_at': booking.updated_at.isoformat() if booking.updated_at else None, 'updatedAt': booking.updated_at.isoformat() if booking.updated_at else None}
if booking.user:
- booking_dict["user"] = {
- "id": booking.user.id,
- "name": booking.user.full_name,
- "full_name": booking.user.full_name,
- "email": booking.user.email,
- "phone": booking.user.phone,
- "phone_number": booking.user.phone,
- }
-
- # Add room info
+ booking_dict['user'] = {'id': booking.user.id, 'name': booking.user.full_name, 'full_name': booking.user.full_name, 'email': booking.user.email, 'phone': booking.user.phone, 'phone_number': booking.user.phone}
if booking.room:
- booking_dict["room"] = {
- "id": booking.room.id,
- "room_number": booking.room.room_number,
- "floor": booking.room.floor,
- }
- # Safely access room_type - it should be loaded via joinedload
+ booking_dict['room'] = {'id': booking.room.id, 'room_number': booking.room.room_number, 'floor': booking.room.floor}
try:
if hasattr(booking.room, 'room_type') and 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,
- }
+ 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}
except Exception as room_type_error:
import logging
logger = logging.getLogger(__name__)
- logger.warning(f"Could not load room_type for booking {booking.id}: {room_type_error}")
-
- # Add payments
+ logger.warning(f'Could not load room_type for booking {booking.id}: {room_type_error}')
if booking.payments:
- booking_dict["payments"] = [
- {
- "id": p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type)),
- "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,
- "created_at": p.created_at.isoformat() if p.created_at else None,
- }
- for p in booking.payments
- ]
+ booking_dict['payments'] = [{'id': p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type), '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, 'created_at': p.created_at.isoformat() if p.created_at else None} for p in booking.payments]
else:
- booking_dict["payments"] = []
-
+ booking_dict['payments'] = []
result.append(booking_dict)
-
- return {
- "status": "success",
- "data": {
- "bookings": result,
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'bookings': result, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except Exception as e:
import logging
import traceback
logger = logging.getLogger(__name__)
- logger.error(f"Error in get_all_bookings: {str(e)}")
+ logger.error(f'Error in get_all_bookings: {str(e)}')
logger.error(traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/me")
-async def get_my_bookings(
- request: Request,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get current user's bookings"""
+@router.get('/me')
+async def get_my_bookings(request: Request, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- bookings = db.query(Booking).options(
- selectinload(Booking.payments),
- joinedload(Booking.room).joinedload(Room.room_type)
- ).filter(
- Booking.user_id == current_user.id
- ).order_by(Booking.created_at.desc()).all()
-
+ bookings = db.query(Booking).options(selectinload(Booking.payments), joinedload(Booking.room).joinedload(Room.room_type)).filter(Booking.user_id == current_user.id).order_by(Booking.created_at.desc()).all()
base_url = get_base_url(request)
result = []
for booking in bookings:
- # Determine payment_method and payment_status from payments
payment_method_from_payments = None
- payment_status_from_payments = "unpaid"
+ payment_status_from_payments = 'unpaid'
if booking.payments:
latest_payment = max(booking.payments, key=lambda p: p.created_at if p.created_at else datetime.min)
if isinstance(latest_payment.payment_method, PaymentMethod):
@@ -387,948 +118,428 @@ async def get_my_bookings(
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"
+ payment_status_from_payments = 'paid'
elif latest_payment.payment_status == PaymentStatus.refunded:
- payment_status_from_payments = "refunded"
-
- booking_dict = {
- "id": booking.id,
- "booking_number": booking.booking_number,
- "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,
- "num_guests": booking.num_guests,
- "guest_count": booking.num_guests,
- "total_price": float(booking.total_price) if booking.total_price else 0.0,
- "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,
- "status": booking.status.value if isinstance(booking.status, BookingStatus) else booking.status,
- "payment_method": payment_method_from_payments if payment_method_from_payments else "cash",
- "payment_status": payment_status_from_payments,
- "deposit_paid": booking.deposit_paid,
- "requires_deposit": booking.requires_deposit,
- "special_requests": booking.special_requests,
- "notes": booking.special_requests,
- "created_at": booking.created_at.isoformat() if booking.created_at else None,
- "createdAt": booking.created_at.isoformat() if booking.created_at else None,
- "updated_at": booking.updated_at.isoformat() if booking.updated_at else None,
- "updatedAt": booking.updated_at.isoformat() if booking.updated_at else None,
- }
-
- # Add room info
+ payment_status_from_payments = 'refunded'
+ booking_dict = {'id': booking.id, 'booking_number': booking.booking_number, '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, 'num_guests': booking.num_guests, 'guest_count': booking.num_guests, 'total_price': float(booking.total_price) if booking.total_price else 0.0, '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, 'status': booking.status.value if isinstance(booking.status, BookingStatus) else booking.status, 'payment_method': payment_method_from_payments if payment_method_from_payments else 'cash', 'payment_status': payment_status_from_payments, 'deposit_paid': booking.deposit_paid, 'requires_deposit': booking.requires_deposit, 'special_requests': booking.special_requests, 'notes': booking.special_requests, 'created_at': booking.created_at.isoformat() if booking.created_at else None, 'createdAt': booking.created_at.isoformat() if booking.created_at else None, 'updated_at': booking.updated_at.isoformat() if booking.updated_at else None, 'updatedAt': booking.updated_at.isoformat() if booking.updated_at else None}
if booking.room and booking.room.room_type:
- # Normalize room images if they exist
room_images = []
if booking.room.images:
try:
room_images = normalize_images(booking.room.images, base_url)
except:
room_images = []
-
- booking_dict["room"] = {
- "id": booking.room.id,
- "room_number": booking.room.room_number,
- "floor": booking.room.floor,
- "images": room_images, # Include room images
- "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,
- "images": room_images, # Also include in room_type for backwards compatibility
- }
- }
-
- # Add payments
+ booking_dict['room'] = {'id': booking.room.id, 'room_number': booking.room.room_number, 'floor': booking.room.floor, 'images': room_images, '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, 'images': room_images}}
if booking.payments:
- booking_dict["payments"] = [
- {
- "id": p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type)),
- "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,
- "created_at": p.created_at.isoformat() if p.created_at else None,
- }
- for p in booking.payments
- ]
+ booking_dict['payments'] = [{'id': p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type), '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, 'created_at': p.created_at.isoformat() if p.created_at else None} for p in booking.payments]
else:
- booking_dict["payments"] = []
-
+ booking_dict['payments'] = []
result.append(booking_dict)
-
- return {
- "success": True,
- "data": {"bookings": result}
- }
+ return {'success': True, 'data': {'bookings': result}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/")
-async def create_booking(
- booking_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create new booking"""
+@router.post('/')
+async def create_booking(booking_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
+ if current_user.role in ['admin', 'staff']:
+ raise HTTPException(status_code=403, detail='Admin and staff users cannot create bookings')
try:
import logging
logger = logging.getLogger(__name__)
-
- # Validate that booking_data is a dict
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.")
-
- logger.info(f"Received booking request from user {current_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")
- promotion_code = booking_data.get("promotion_code")
-
- # Invoice information (optional)
- invoice_info = booking_data.get("invoice_info", {})
-
- # Detailed validation with specific error messages
+ 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.')
+ logger.info(f'Received booking request from user {current_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')
+ promotion_code = booking_data.get('promotion_code')
+ invoice_info = booking_data.get('invoice_info', {})
missing_fields = []
if not room_id:
- missing_fields.append("room_id")
+ missing_fields.append('room_id')
if not check_in_date:
- missing_fields.append("check_in_date")
+ missing_fields.append('check_in_date')
if not check_out_date:
- missing_fields.append("check_out_date")
+ missing_fields.append('check_out_date')
if total_price is None:
- missing_fields.append("total_price")
-
+ missing_fields.append('total_price')
if missing_fields:
- error_msg = f"Missing required booking fields: {', '.join(missing_fields)}"
+ error_msg = f'Missing required booking fields: {', '.join(missing_fields)}'
logger.error(error_msg)
raise HTTPException(status_code=400, detail=error_msg)
-
- # Check if room exists
room = db.query(Room).filter(Room.id == room_id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Parse dates as date-only strings (YYYY-MM-DD) - treat as naive datetime
+ raise HTTPException(status_code=404, detail='Room not found')
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:
- # Date-only format (YYYY-MM-DD) - parse as naive datetime
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:
- # Date-only format (YYYY-MM-DD) - parse as naive datetime
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()
-
+ 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"
- )
-
+ raise HTTPException(status_code=409, detail='Room already booked for the selected dates')
booking_number = generate_booking_number()
-
- # Determine if deposit is required
- # Cash requires deposit, Stripe and PayPal don't require deposit (full payment or deposit handled via payment flow)
- requires_deposit = payment_method == "cash"
+ 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
-
- # For Stripe and PayPal, booking can be confirmed immediately after payment
+ deposit_amount = float(total_price) * deposit_percentage / 100 if requires_deposit else 0
initial_status = BookingStatus.pending
- if payment_method in ["stripe", "paypal"]:
- # Will be confirmed after successful payment
+ if payment_method in ['stripe', 'paypal']:
initial_status = BookingStatus.pending
-
- # Calculate original price (before discount) and discount amount
- # 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
room_total = room_price * number_of_nights
-
- # Calculate services total (will be recalculated when adding services, but estimate here)
- services = booking_data.get("services", [])
+ 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)
+ 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
discount_amount = max(0.0, original_price - float(total_price)) if promotion_code else 0.0
-
- # Add promotion code to notes if provided
- final_notes = notes or ""
+ 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
-
- # Create booking
- 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,
- )
-
+ 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)
db.add(booking)
db.flush()
-
- # Create payment record if Stripe or PayPal payment method is selected
- if payment_method in ["stripe", "paypal"]:
+ if payment_method in ['stripe', 'paypal']:
from ..models.payment import Payment, PaymentMethod, PaymentStatus, PaymentType
- if payment_method == "stripe":
+ if payment_method == 'stripe':
payment_method_enum = PaymentMethod.stripe
- elif payment_method == "paypal":
+ elif payment_method == 'paypal':
payment_method_enum = PaymentMethod.paypal
else:
- # This shouldn't happen, but just in case
- 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
-
- 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,
- )
+ 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)
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}")
-
- # Create deposit payment if required (for cash method)
- # For cash payments, create a pending deposit payment record that can be paid via PayPal or Stripe
+ logger.info(f'Payment created: ID={payment.id}, method={(payment.payment_method.value if hasattr(payment.payment_method, 'value') else payment.payment_method)}')
if requires_deposit and deposit_amount > 0:
from ..models.payment import Payment, PaymentMethod, PaymentStatus, PaymentType
- deposit_payment = Payment(
- booking_id=booking.id,
- amount=deposit_amount,
- payment_method=PaymentMethod.stripe, # Default, will be updated when user chooses payment method
- payment_type=PaymentType.deposit,
- deposit_percentage=deposit_percentage,
- payment_status=PaymentStatus.pending,
- payment_date=None,
- )
+ deposit_payment = Payment(booking_id=booking.id, amount=deposit_amount, payment_method=PaymentMethod.stripe, payment_type=PaymentType.deposit, deposit_percentage=deposit_percentage, payment_status=PaymentStatus.pending, payment_date=None)
db.add(deposit_payment)
db.flush()
- logger.info(f"Deposit payment created: ID={deposit_payment.id}, amount={deposit_amount}, percentage={deposit_percentage}%")
-
- # Add services to booking if provided
- services = booking_data.get("services", [])
+ logger.info(f'Deposit payment created: ID={deposit_payment.id}, amount={deposit_amount}, percentage={deposit_percentage}%')
+ services = booking_data.get('services', [])
if services:
from ..models.service import Service
- # ServiceUsage is already imported at the top of the file
-
for service_item in services:
- service_id = service_item.get("service_id")
- quantity = service_item.get("quantity", 1)
-
+ service_id = service_item.get('service_id')
+ quantity = service_item.get('quantity', 1)
if not service_id:
continue
-
- # Check if service exists and is active
service = db.query(Service).filter(Service.id == service_id).first()
if not service or not service.is_active:
continue
-
- # Calculate total price for this service
unit_price = float(service.price)
total_price = unit_price * quantity
-
- # Create service usage
- service_usage = ServiceUsage(
- booking_id=booking.id,
- service_id=service_id,
- quantity=quantity,
- unit_price=unit_price,
- total_price=total_price,
- )
+ service_usage = ServiceUsage(booking_id=booking.id, service_id=service_id, quantity=quantity, unit_price=unit_price, total_price=total_price)
db.add(service_usage)
-
db.commit()
db.refresh(booking)
-
- # Automatically create invoice(s) for the booking
try:
from ..services.invoice_service import InvoiceService
from ..utils.mailer import send_email
from sqlalchemy.orm import joinedload, selectinload
-
- # Reload booking with service_usages for invoice creation
- booking = db.query(Booking).options(
- selectinload(Booking.service_usages).selectinload(ServiceUsage.service)
- ).filter(Booking.id == booking.id).first()
-
- # Get company settings for invoice
+ booking = db.query(Booking).options(selectinload(Booking.service_usages).selectinload(ServiceUsage.service)).filter(Booking.id == booking.id).first()
from ..models.system_settings import SystemSettings
company_settings = {}
- for key in ["company_name", "company_address", "company_phone", "company_email", "company_tax_id", "company_logo_url"]:
+ for key in ['company_name', 'company_address', 'company_phone', 'company_email', 'company_tax_id', 'company_logo_url']:
setting = db.query(SystemSettings).filter(SystemSettings.key == key).first()
if setting and setting.value:
company_settings[key] = setting.value
-
- # Get tax rate from settings (default to 0 if not set)
- tax_rate_setting = db.query(SystemSettings).filter(SystemSettings.key == "tax_rate").first()
+ tax_rate_setting = db.query(SystemSettings).filter(SystemSettings.key == 'tax_rate').first()
tax_rate = float(tax_rate_setting.value) if tax_rate_setting and tax_rate_setting.value else 0.0
-
- # Merge invoice info from form with company settings (form takes precedence)
- # Only include non-empty values from invoice_info
invoice_kwargs = {**company_settings}
if invoice_info:
- if invoice_info.get("company_name"):
- invoice_kwargs["company_name"] = invoice_info.get("company_name")
- if invoice_info.get("company_address"):
- invoice_kwargs["company_address"] = invoice_info.get("company_address")
- if invoice_info.get("company_tax_id"):
- invoice_kwargs["company_tax_id"] = invoice_info.get("company_tax_id")
- if invoice_info.get("customer_tax_id"):
- invoice_kwargs["customer_tax_id"] = invoice_info.get("customer_tax_id")
- if invoice_info.get("notes"):
- invoice_kwargs["notes"] = invoice_info.get("notes")
- if invoice_info.get("terms_and_conditions"):
- invoice_kwargs["terms_and_conditions"] = invoice_info.get("terms_and_conditions")
- if invoice_info.get("payment_instructions"):
- invoice_kwargs["payment_instructions"] = invoice_info.get("payment_instructions")
-
- # Get discount from booking
+ if invoice_info.get('company_name'):
+ invoice_kwargs['company_name'] = invoice_info.get('company_name')
+ if invoice_info.get('company_address'):
+ invoice_kwargs['company_address'] = invoice_info.get('company_address')
+ if invoice_info.get('company_tax_id'):
+ invoice_kwargs['company_tax_id'] = invoice_info.get('company_tax_id')
+ if invoice_info.get('customer_tax_id'):
+ invoice_kwargs['customer_tax_id'] = invoice_info.get('customer_tax_id')
+ if invoice_info.get('notes'):
+ invoice_kwargs['notes'] = invoice_info.get('notes')
+ if invoice_info.get('terms_and_conditions'):
+ invoice_kwargs['terms_and_conditions'] = invoice_info.get('terms_and_conditions')
+ if invoice_info.get('payment_instructions'):
+ invoice_kwargs['payment_instructions'] = invoice_info.get('payment_instructions')
booking_discount = float(booking.discount_amount) if booking.discount_amount else 0.0
-
- # Add promotion code to invoice notes if present
- invoice_notes = invoice_kwargs.get("notes", "")
+ invoice_notes = invoice_kwargs.get('notes', '')
if booking.promotion_code:
- promotion_note = f"Promotion Code: {booking.promotion_code}"
- invoice_notes = f"{promotion_note}\n{invoice_notes}".strip() if invoice_notes else promotion_note
- invoice_kwargs["notes"] = invoice_notes
-
- # Create invoices based on payment method
- if payment_method == "cash":
- # For cash bookings: create invoice for 20% deposit + proforma for 80% remaining
+ promotion_note = f'Promotion Code: {booking.promotion_code}'
+ 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
-
- # Calculate proportional discount for partial invoices
- # Deposit invoice gets 20% of the discount, proforma gets 80%
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
-
- # Create invoice for deposit (20%)
- 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
- )
-
- # Create proforma invoice for remaining amount (80%)
- proforma_invoice = InvoiceService.create_invoice_from_booking(
- booking_id=booking.id,
- db=db,
- created_by_id=current_user.id,
- tax_rate=tax_rate,
- discount_amount=proforma_discount,
- due_days=30,
- is_proforma=True,
- invoice_amount=remaining_amount,
- **invoice_kwargs
- )
-
- # Send deposit invoice via email
+ 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)
+ proforma_invoice = InvoiceService.create_invoice_from_booking(booking_id=booking.id, db=db, created_by_id=current_user.id, tax_rate=tax_rate, discount_amount=proforma_discount, due_days=30, is_proforma=True, invoice_amount=remaining_amount, **invoice_kwargs)
try:
invoice_html = _generate_invoice_email_html(deposit_invoice, is_proforma=False)
- await send_email(
- to=current_user.email,
- subject=f"Invoice {deposit_invoice['invoice_number']} - Deposit Payment",
- html=invoice_html
- )
- logger.info(f"Deposit invoice sent to {current_user.email}")
+ await send_email(to=current_user.email, subject=f'Invoice {deposit_invoice['invoice_number']} - Deposit Payment', html=invoice_html)
+ logger.info(f'Deposit invoice sent to {current_user.email}')
except Exception as email_error:
- logger.error(f"Failed to send deposit invoice email: {str(email_error)}")
-
- # Send proforma invoice via email
+ logger.error(f'Failed to send deposit invoice email: {str(email_error)}')
try:
proforma_html = _generate_invoice_email_html(proforma_invoice, is_proforma=True)
- await send_email(
- to=current_user.email,
- subject=f"Proforma Invoice {proforma_invoice['invoice_number']} - Remaining Balance",
- html=proforma_html
- )
- logger.info(f"Proforma invoice sent to {current_user.email}")
+ await send_email(to=current_user.email, subject=f'Proforma Invoice {proforma_invoice['invoice_number']} - Remaining Balance', html=proforma_html)
+ logger.info(f'Proforma invoice sent to {current_user.email}')
except Exception as email_error:
- logger.error(f"Failed to send proforma invoice email: {str(email_error)}")
+ logger.error(f'Failed to send proforma invoice email: {str(email_error)}')
else:
- # For full payment (Stripe/PayPal): create full invoice
- # Invoice will be created and sent after payment is confirmed
- # We create it now as draft, and it will be updated when payment is confirmed
- full_invoice = InvoiceService.create_invoice_from_booking(
- booking_id=booking.id,
- db=db,
- created_by_id=current_user.id,
- tax_rate=tax_rate,
- discount_amount=booking_discount,
- due_days=30,
- is_proforma=False,
- **invoice_kwargs
- )
-
- # Don't send invoice email yet - will be sent after payment is confirmed
- # The invoice will be updated and sent when payment is completed
- logger.info(f"Invoice {full_invoice['invoice_number']} created for booking {booking.id} (will be sent after payment confirmation)")
+ full_invoice = InvoiceService.create_invoice_from_booking(booking_id=booking.id, db=db, created_by_id=current_user.id, tax_rate=tax_rate, discount_amount=booking_discount, due_days=30, is_proforma=False, **invoice_kwargs)
+ logger.info(f'Invoice {full_invoice['invoice_number']} created for booking {booking.id} (will be sent after payment confirmation)')
except Exception as e:
- # Log error but don't fail booking creation if invoice creation fails
import logging
import traceback
logger = logging.getLogger(__name__)
- logger.error(f"Failed to create invoice for booking {booking.id}: {str(e)}")
- logger.error(f"Traceback: {traceback.format_exc()}")
-
- # Fetch with relations for proper serialization (eager load payments and service_usages)
+ logger.error(f'Failed to create invoice for booking {booking.id}: {str(e)}')
+ logger.error(f'Traceback: {traceback.format_exc()}')
from sqlalchemy.orm import joinedload, selectinload
- booking = db.query(Booking).options(
- joinedload(Booking.payments),
- selectinload(Booking.service_usages).selectinload(ServiceUsage.service)
- ).filter(Booking.id == booking.id).first()
-
- # Determine payment_method and payment_status from payments
+ booking = db.query(Booking).options(joinedload(Booking.payments), selectinload(Booking.service_usages).selectinload(ServiceUsage.service)).filter(Booking.id == booking.id).first()
payment_method_from_payments = None
- payment_status_from_payments = "unpaid"
+ payment_status_from_payments = 'unpaid'
if booking.payments:
latest_payment = sorted(booking.payments, key=lambda p: p.created_at, reverse=True)[0]
- # Safely extract payment method value
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)
-
- logger.info(f"Booking {booking.id} - Latest payment method: {payment_method_from_payments}, raw: {latest_payment.payment_method}")
-
+ logger.info(f'Booking {booking.id} - Latest payment method: {payment_method_from_payments}, raw: {latest_payment.payment_method}')
if latest_payment.payment_status == PaymentStatus.completed:
- payment_status_from_payments = "paid"
+ payment_status_from_payments = 'paid'
elif latest_payment.payment_status == PaymentStatus.refunded:
- payment_status_from_payments = "refunded"
-
- # Use payment_method from payments if available, otherwise fall back to request payment_method
+ payment_status_from_payments = 'refunded'
final_payment_method = payment_method_from_payments if payment_method_from_payments else payment_method
- logger.info(f"Booking {booking.id} - Final payment_method: {final_payment_method} (from_payments: {payment_method_from_payments}, request: {payment_method})")
-
- # Serialize booking properly
- 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": current_user.full_name,
- "email": current_user.email,
- "phone": current_user.phone_number if hasattr(current_user, 'phone_number') else (current_user.phone if hasattr(current_user, 'phone') 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,
- }
-
- # Add payments if they exist
+ logger.info(f'Booking {booking.id} - Final payment_method: {final_payment_method} (from_payments: {payment_method_from_payments}, request: {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': current_user.full_name, 'email': current_user.email, 'phone': current_user.phone_number if hasattr(current_user, 'phone_number') else current_user.phone if hasattr(current_user, 'phone') 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
- ]
-
- # Add service usages if they exist
+ 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)
import logging
logger = logging.getLogger(__name__)
- logger.info(f"Booking {booking.id} - service_usages: {service_usages}, type: {type(service_usages)}")
-
+ logger.info(f'Booking {booking.id} - service_usages: {service_usages}, type: {type(service_usages)}')
if service_usages and len(service_usages) > 0:
- logger.info(f"Booking {booking.id} - Found {len(service_usages)} service usages")
- 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
- ]
- logger.info(f"Booking {booking.id} - Serialized service_usages: {booking_dict['service_usages']}")
+ logger.info(f'Booking {booking.id} - Found {len(service_usages)} service usages')
+ 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]
+ logger.info(f'Booking {booking.id} - Serialized service_usages: {booking_dict['service_usages']}')
else:
- # Initialize empty array if no service_usages
- logger.info(f"Booking {booking.id} - No service_usages found, initializing empty array")
- booking_dict["service_usages"] = []
-
- # Add room info if available
+ logger.info(f'Booking {booking.id} - No service_usages found, initializing empty array')
+ booking_dict['service_usages'] = []
if booking.room:
- booking_dict["room"] = {
- "id": booking.room.id,
- "room_number": booking.room.room_number,
- "floor": booking.room.floor,
- }
+ 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,
- }
-
- # Don't send email here - emails will be sent when booking is confirmed or cancelled
-
- return {
- "success": True,
- "data": {"booking": booking_dict},
- "message": f"Booking created. Please pay {deposit_percentage}% deposit to confirm." if requires_deposit else "Booking created successfully"
- }
+ 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. Please pay {deposit_percentage}% deposit to confirm.' if requires_deposit else 'Booking created successfully'}
except HTTPException:
raise
except Exception as e:
import logging
import traceback
logger = logging.getLogger(__name__)
- logger.error(f"Error creating booking (payment_method: {payment_method}): {str(e)}")
- logger.error(f"Traceback: {traceback.format_exc()}")
+ logger.error(f'Error creating booking (payment_method: {payment_method}): {str(e)}')
+ logger.error(f'Traceback: {traceback.format_exc()}')
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{id}")
-async def get_booking_by_id(
- id: int,
- request: Request,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get booking by ID"""
+@router.get('/{id}')
+async def get_booking_by_id(id: int, request: Request, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Eager load all relationships to avoid N+1 queries
- # Using selectinload for better performance with multiple relationships
from sqlalchemy.orm import selectinload
- booking = db.query(Booking)\
- .options(
- selectinload(Booking.payments),
- selectinload(Booking.service_usages).selectinload(ServiceUsage.service),
- joinedload(Booking.user),
- joinedload(Booking.room).joinedload(Room.room_type)
- )\
- .filter(Booking.id == id)\
- .first()
-
+ booking = db.query(Booking).options(selectinload(Booking.payments), selectinload(Booking.service_usages).selectinload(ServiceUsage.service), 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")
-
- # Check access
- if current_user.role_id != 1 and booking.user_id != current_user.id: # Not admin
- raise HTTPException(status_code=403, detail="Forbidden")
-
- # Determine payment_method and payment_status from payments
- # Get latest payment efficiently (already loaded via joinedload)
+ raise HTTPException(status_code=404, detail='Booking not found')
+ if current_user.role_id != 1 and booking.user_id != current_user.id:
+ raise HTTPException(status_code=403, detail='Forbidden')
import logging
logger = logging.getLogger(__name__)
-
payment_method_from_payments = None
- payment_status = "unpaid"
+ payment_status = 'unpaid'
if booking.payments:
- # Find latest payment (payments are already loaded, so this is fast)
latest_payment = max(booking.payments, key=lambda p: p.created_at if p.created_at else datetime.min)
- # Safely extract payment method value
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)
-
- logger.info(f"Get booking {id} - Latest payment method: {payment_method_from_payments}, raw: {latest_payment.payment_method}")
-
+ logger.info(f'Get booking {id} - Latest payment method: {payment_method_from_payments}, raw: {latest_payment.payment_method}')
if latest_payment.payment_status == PaymentStatus.completed:
- payment_status = "paid"
+ payment_status = 'paid'
elif latest_payment.payment_status == PaymentStatus.refunded:
- payment_status = "refunded"
-
- # Use payment_method from payments, fallback to "cash" if no payments
- final_payment_method = payment_method_from_payments if payment_method_from_payments else "cash"
- logger.info(f"Get booking {id} - Final payment_method: {final_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, # Frontend expects guest_count
- "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,
- "deposit_paid": booking.deposit_paid,
- "requires_deposit": booking.requires_deposit,
- "notes": booking.special_requests, # Frontend expects notes
- "guest_info": {
- "full_name": booking.user.full_name if booking.user else "",
- "email": booking.user.email if booking.user else "",
- "phone": booking.user.phone_number if booking.user and hasattr(booking.user, 'phone_number') else (booking.user.phone if booking.user and hasattr(booking.user, 'phone') else ""),
- } if booking.user else None,
- "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,
- }
-
- # Add relations
- # Only get base_url if we need it (room has images)
+ payment_status = 'refunded'
+ final_payment_method = payment_method_from_payments if payment_method_from_payments else 'cash'
+ logger.info(f'Get booking {id} - Final payment_method: {final_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, '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_number if booking.user and hasattr(booking.user, 'phone_number') else booking.user.phone if booking.user and hasattr(booking.user, 'phone') else ''} if booking.user else None, '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.room and booking.room.images:
base_url = get_base_url(request)
- # Normalize room images if they exist
try:
room_images = normalize_images(booking.room.images, base_url)
except:
room_images = []
else:
room_images = []
-
if booking.room:
-
- booking_dict["room"] = {
- "id": booking.room.id,
- "room_number": booking.room.room_number,
- "floor": booking.room.floor,
- "status": booking.room.status.value if isinstance(booking.room.status, RoomStatus) else booking.room.status,
- "images": room_images, # Include room images directly on room object
- }
+ booking_dict['room'] = {'id': booking.room.id, 'room_number': booking.room.room_number, 'floor': booking.room.floor, 'status': booking.room.status.value if isinstance(booking.room.status, RoomStatus) else booking.room.status, 'images': room_images}
if booking.room.room_type:
- # Use room images if room_type doesn't have images (which is typical)
- # RoomType doesn't have images column, images are stored on Room
room_type_images = room_images if room_images else []
-
- 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,
- "images": room_type_images,
- }
-
+ 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, 'images': room_type_images}
if booking.payments:
- booking_dict["payments"] = [
- {
- "id": p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type)),
- "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,
- "created_at": p.created_at.isoformat() if p.created_at else None,
- }
- for p in booking.payments
- ]
-
- # Add service usages if they exist
- # Use getattr to safely access service_usages in case relationship isn't loaded
+ booking_dict['payments'] = [{'id': p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type), '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, 'created_at': p.created_at.isoformat() if p.created_at else None} for p in booking.payments]
service_usages = getattr(booking, 'service_usages', None)
import logging
logger = logging.getLogger(__name__)
- logger.info(f"Get booking {id} - service_usages: {service_usages}, type: {type(service_usages)}")
-
+ logger.info(f'Get booking {id} - service_usages: {service_usages}, type: {type(service_usages)}')
if service_usages and len(service_usages) > 0:
- logger.info(f"Get booking {id} - Found {len(service_usages)} service usages")
- 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
- ]
- logger.info(f"Get booking {id} - Serialized service_usages: {booking_dict['service_usages']}")
+ logger.info(f'Get booking {id} - Found {len(service_usages)} service usages')
+ 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]
+ logger.info(f'Get booking {id} - Serialized service_usages: {booking_dict['service_usages']}')
else:
- # Initialize empty array if no service_usages
- logger.info(f"Get booking {id} - No service_usages found, initializing empty array")
- booking_dict["service_usages"] = []
-
- return {
- "success": True,
- "data": {"booking": booking_dict}
- }
+ logger.info(f'Get booking {id} - No service_usages found, initializing empty array')
+ booking_dict['service_usages'] = []
+ return {'success': True, 'data': {'booking': booking_dict}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.patch("/{id}/cancel")
-async def cancel_booking(
- id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Cancel a booking"""
+@router.patch('/{id}/cancel')
+async def cancel_booking(id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
booking = db.query(Booking).filter(Booking.id == id).first()
-
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
+ raise HTTPException(status_code=404, detail='Booking not found')
if booking.user_id != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
+ raise HTTPException(status_code=403, detail='Forbidden')
if booking.status == BookingStatus.cancelled:
- raise HTTPException(status_code=400, detail="Booking already cancelled")
-
- # Prevent cancellation of confirmed bookings
+ raise HTTPException(status_code=400, detail='Booking already cancelled')
if booking.status == BookingStatus.confirmed:
- raise HTTPException(
- status_code=400,
- detail="Cannot cancel a confirmed booking. Please contact support for assistance."
- )
-
- # Only allow cancellation of pending bookings
+ raise HTTPException(status_code=400, detail='Cannot cancel a confirmed booking. Please contact support for assistance.')
if booking.status != BookingStatus.pending:
- raise HTTPException(
- status_code=400,
- detail=f"Cannot cancel booking with status: {booking.status.value}. Only pending bookings can be cancelled."
- )
-
+ raise HTTPException(status_code=400, detail=f'Cannot cancel booking with status: {booking.status.value}. Only pending bookings can be cancelled.')
+ booking = db.query(Booking).options(selectinload(Booking.payments)).filter(Booking.id == id).first()
+ payments_updated = False
+ if booking.payments:
+ for payment in booking.payments:
+ if payment.payment_status == PaymentStatus.pending:
+ payment.payment_status = PaymentStatus.failed
+ existing_notes = payment.notes or ''
+ cancellation_note = f'\nPayment cancelled due to booking cancellation on {datetime.utcnow().isoformat()}'
+ payment.notes = existing_notes + cancellation_note if existing_notes else cancellation_note.strip()
+ payments_updated = True
+ from sqlalchemy import update, func
+ pending_payments = db.query(Payment).filter(Payment.booking_id == id, Payment.payment_status == PaymentStatus.pending).all()
+ for payment in pending_payments:
+ payment.payment_status = PaymentStatus.failed
+ existing_notes = payment.notes or ''
+ cancellation_note = f'\nPayment cancelled due to booking cancellation on {datetime.utcnow().isoformat()}'
+ payment.notes = existing_notes + cancellation_note if existing_notes else cancellation_note.strip()
+ payments_updated = True
booking.status = BookingStatus.cancelled
+ if payments_updated > 0:
+ db.flush()
db.commit()
-
- # Send cancellation email (non-blocking)
try:
from ..models.system_settings import SystemSettings
-
- # Get client URL from settings
- 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"))
-
- 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
- )
+ 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')
+ 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)
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Failed to send cancellation email: {e}")
-
- return {
- "success": True,
- "data": {"booking": booking}
- }
+ logger.error(f'Failed to send cancellation email: {e}')
+ return {'success': True, 'data': {'booking': booking}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@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)
-):
- """Update booking status (Admin only)"""
+@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:
- # Load booking with payments to check balance
- booking = db.query(Booking).options(
- selectinload(Booking.payments)
- ).filter(Booking.id == id).first()
+ booking = db.query(Booking).options(selectinload(Booking.payments)).filter(Booking.id == id).first()
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
- status_value = booking_data.get("status")
+ status_value = booking_data.get('status')
if status_value:
try:
- booking.status = BookingStatus(status_value)
+ new_status = BookingStatus(status_value)
+ booking.status = new_status
+ if new_status == BookingStatus.cancelled:
+ if booking.payments:
+ for payment in booking.payments:
+ if payment.payment_status == PaymentStatus.pending:
+ payment.payment_status = PaymentStatus.failed
+ existing_notes = payment.notes or ''
+ cancellation_note = f'\nPayment cancelled due to booking cancellation on {datetime.utcnow().isoformat()}'
+ payment.notes = existing_notes + cancellation_note if existing_notes else cancellation_note.strip()
+ db.flush()
except ValueError:
- raise HTTPException(status_code=400, detail="Invalid status")
-
+ raise HTTPException(status_code=400, detail='Invalid status')
db.commit()
db.refresh(booking)
-
- # Check payment balance if status changed to checked_in
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)
- if payment_balance["remaining_balance"] > 0.01: # More than 1 cent remaining
- payment_warning = {
- "message": f"Guest has not fully paid. Remaining balance: {payment_balance['remaining_balance']:.2f}",
- "total_paid": payment_balance["total_paid"],
- "total_price": payment_balance["total_price"],
- "remaining_balance": payment_balance["remaining_balance"],
- "payment_percentage": payment_balance["payment_percentage"]
- }
-
- # Send status change email only if status changed to confirmed or cancelled (non-blocking)
+ if payment_balance['remaining_balance'] > 0.01:
+ payment_warning = {'message': f'Guest has not fully paid. Remaining balance: {payment_balance['remaining_balance']:.2f}', 'total_paid': payment_balance['total_paid'], 'total_price': payment_balance['total_price'], 'remaining_balance': payment_balance['remaining_balance'], 'payment_percentage': payment_balance['payment_percentage']}
if status_value and old_status != booking.status:
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
-
- # Get client URL from settings
- 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_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:
- # Send booking confirmation email with full details
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()
-
+ 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"
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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
- )
+ 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)
elif booking.status == BookingStatus.cancelled:
- # Send cancellation email
- 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
- )
+ 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)
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}
- }
-
- # Add payment warning if there's remaining balance during check-in
+ logger.error(f'Failed to send status change email: {e}')
+ response_data = {'status': 'success', 'message': 'Booking updated successfully', 'data': {'booking': booking}}
if payment_warning:
- response_data["warning"] = payment_warning
- response_data["message"] = "Booking updated successfully. ⚠️ Payment reminder: Guest has remaining balance."
-
+ response_data['warning'] = payment_warning
+ response_data['message'] = 'Booking updated successfully. ⚠️ Payment reminder: Guest has remaining balance.'
return response_data
except HTTPException:
raise
@@ -1336,26 +547,14 @@ async def update_booking(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/check/{booking_number}")
-async def check_booking_by_number(
- booking_number: str,
- db: Session = Depends(get_db)
-):
- """Check booking by booking number"""
+@router.get('/check/{booking_number}')
+async def check_booking_by_number(booking_number: str, db: Session=Depends(get_db)):
try:
- booking = db.query(Booking).options(
- selectinload(Booking.payments),
- joinedload(Booking.user),
- joinedload(Booking.room).joinedload(Room.room_type)
- ).filter(Booking.booking_number == booking_number).first()
-
+ booking = db.query(Booking).options(selectinload(Booking.payments), joinedload(Booking.user), joinedload(Booking.room).joinedload(Room.room_type)).filter(Booking.booking_number == booking_number).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
- # Determine payment_method and payment_status from payments
+ raise HTTPException(status_code=404, detail='Booking not found')
payment_method_from_payments = None
- payment_status_from_payments = "unpaid"
+ payment_status_from_payments = 'unpaid'
if booking.payments:
latest_payment = max(booking.payments, key=lambda p: p.created_at if p.created_at else datetime.min)
if isinstance(latest_payment.payment_method, PaymentMethod):
@@ -1364,107 +563,28 @@ async def check_booking_by_number(
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"
+ payment_status_from_payments = 'paid'
elif latest_payment.payment_status == PaymentStatus.refunded:
- payment_status_from_payments = "refunded"
-
- 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,
- "num_guests": booking.num_guests,
- "guest_count": booking.num_guests,
- "total_price": float(booking.total_price) if booking.total_price else 0.0,
- "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,
- "status": booking.status.value if isinstance(booking.status, BookingStatus) else booking.status,
- "payment_method": payment_method_from_payments if payment_method_from_payments else "cash",
- "payment_status": payment_status_from_payments,
- "deposit_paid": booking.deposit_paid,
- "requires_deposit": booking.requires_deposit,
- "special_requests": booking.special_requests,
- "notes": booking.special_requests,
- "created_at": booking.created_at.isoformat() if booking.created_at else None,
- "createdAt": booking.created_at.isoformat() if booking.created_at else None,
- "updated_at": booking.updated_at.isoformat() if booking.updated_at else None,
- "updatedAt": booking.updated_at.isoformat() if booking.updated_at else None,
- }
-
- # Add user info
+ payment_status_from_payments = 'refunded'
+ 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, 'num_guests': booking.num_guests, 'guest_count': booking.num_guests, 'total_price': float(booking.total_price) if booking.total_price else 0.0, '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, 'status': booking.status.value if isinstance(booking.status, BookingStatus) else booking.status, 'payment_method': payment_method_from_payments if payment_method_from_payments else 'cash', 'payment_status': payment_status_from_payments, 'deposit_paid': booking.deposit_paid, 'requires_deposit': booking.requires_deposit, 'special_requests': booking.special_requests, 'notes': booking.special_requests, 'created_at': booking.created_at.isoformat() if booking.created_at else None, 'createdAt': booking.created_at.isoformat() if booking.created_at else None, 'updated_at': booking.updated_at.isoformat() if booking.updated_at else None, 'updatedAt': booking.updated_at.isoformat() if booking.updated_at else None}
if booking.user:
- booking_dict["user"] = {
- "id": booking.user.id,
- "name": booking.user.full_name,
- "full_name": booking.user.full_name,
- "email": booking.user.email,
- "phone": booking.user.phone,
- "phone_number": booking.user.phone,
- }
-
- # Add room info
+ booking_dict['user'] = {'id': booking.user.id, 'name': booking.user.full_name, 'full_name': booking.user.full_name, 'email': booking.user.email, 'phone': booking.user.phone, 'phone_number': booking.user.phone}
if booking.room:
- booking_dict["room"] = {
- "id": booking.room.id,
- "room_number": booking.room.room_number,
- "floor": booking.room.floor,
- }
+ 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,
- }
-
- # Add payments
+ 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}
if booking.payments:
- booking_dict["payments"] = [
- {
- "id": p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type)),
- "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,
- "created_at": p.created_at.isoformat() if p.created_at else None,
- }
- for p in booking.payments
- ]
+ booking_dict['payments'] = [{'id': p.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.value if hasattr(p.payment_type, 'value') else str(p.payment_type), '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, 'created_at': p.created_at.isoformat() if p.created_at else None} for p in booking.payments]
else:
- booking_dict["payments"] = []
-
- # Calculate and add payment balance information
+ booking_dict['payments'] = []
payment_balance = calculate_booking_payment_balance(booking)
- booking_dict["payment_balance"] = {
- "total_paid": payment_balance["total_paid"],
- "total_price": payment_balance["total_price"],
- "remaining_balance": payment_balance["remaining_balance"],
- "is_fully_paid": payment_balance["is_fully_paid"],
- "payment_percentage": payment_balance["payment_percentage"]
- }
-
- # Add warning if there's remaining balance (useful for check-in)
- response_data = {
- "status": "success",
- "data": {"booking": booking_dict}
- }
-
- if payment_balance["remaining_balance"] > 0.01:
- response_data["warning"] = {
- "message": f"Guest has not fully paid. Remaining balance: {payment_balance['remaining_balance']:.2f}",
- "remaining_balance": payment_balance["remaining_balance"],
- "payment_percentage": payment_balance["payment_percentage"]
- }
-
+ booking_dict['payment_balance'] = {'total_paid': payment_balance['total_paid'], 'total_price': payment_balance['total_price'], 'remaining_balance': payment_balance['remaining_balance'], 'is_fully_paid': payment_balance['is_fully_paid'], 'payment_percentage': payment_balance['payment_percentage']}
+ response_data = {'status': 'success', 'data': {'booking': booking_dict}}
+ if payment_balance['remaining_balance'] > 0.01:
+ response_data['warning'] = {'message': f'Guest has not fully paid. Remaining balance: {payment_balance['remaining_balance']:.2f}', 'remaining_balance': payment_balance['remaining_balance'], 'payment_percentage': payment_balance['payment_percentage']}
return response_data
except HTTPException:
raise
except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/chat_routes.py b/Backend/src/routes/chat_routes.py
new file mode 100644
index 00000000..57dd4433
--- /dev/null
+++ b/Backend/src/routes/chat_routes.py
@@ -0,0 +1,335 @@
+from fastapi import APIRouter, Depends, HTTPException, status, WebSocket, WebSocketDisconnect
+from sqlalchemy.orm import Session
+from sqlalchemy import and_, or_
+from typing import List, Optional
+from datetime import datetime
+import json
+from ..config.database import get_db
+from ..middleware.auth import get_current_user, get_current_user_optional
+from ..models.user import User
+from ..models.chat import Chat, ChatMessage, ChatStatus
+from ..models.role import Role
+router = APIRouter(prefix='/chat', tags=['chat'])
+
+class ConnectionManager:
+
+ def __init__(self):
+ self.active_connections: dict[int, List[WebSocket]] = {}
+ self.staff_connections: dict[int, WebSocket] = {}
+ self.visitor_connections: dict[int, WebSocket] = {}
+
+ async def connect_chat(self, websocket: WebSocket, chat_id: int, user_type: str):
+ await websocket.accept()
+ if chat_id not in self.active_connections:
+ self.active_connections[chat_id] = []
+ self.active_connections[chat_id].append(websocket)
+ if user_type == 'staff':
+ pass
+ elif user_type == 'visitor':
+ self.visitor_connections[chat_id] = websocket
+
+ def disconnect_chat(self, websocket: WebSocket, chat_id: int):
+ if chat_id in self.active_connections:
+ if websocket in self.active_connections[chat_id]:
+ self.active_connections[chat_id].remove(websocket)
+ if not self.active_connections[chat_id]:
+ del self.active_connections[chat_id]
+ if chat_id in self.visitor_connections and self.visitor_connections[chat_id] == websocket:
+ del self.visitor_connections[chat_id]
+
+ async def send_personal_message(self, message: dict, websocket: WebSocket):
+ try:
+ await websocket.send_json(message)
+ except Exception as e:
+ print(f'Error sending message: {e}')
+
+ async def broadcast_to_chat(self, message: dict, chat_id: int):
+ if chat_id in self.active_connections:
+ disconnected = []
+ for connection in self.active_connections[chat_id]:
+ try:
+ await connection.send_json(message)
+ except Exception as e:
+ print(f'Error broadcasting to connection: {e}')
+ disconnected.append(connection)
+ for conn in disconnected:
+ self.active_connections[chat_id].remove(conn)
+
+ async def notify_staff_new_chat(self, chat_data: dict):
+ disconnected = []
+ for user_id, websocket in self.staff_connections.items():
+ try:
+ await websocket.send_json({'type': 'new_chat', 'data': chat_data})
+ except Exception as e:
+ print(f'Error notifying staff {user_id}: {e}')
+ disconnected.append(user_id)
+ for user_id in disconnected:
+ del self.staff_connections[user_id]
+
+ async def notify_staff_new_message(self, chat_id: int, message_data: dict, chat: Chat):
+ if message_data.get('sender_type') == 'visitor':
+ notification_data = {'type': 'new_message_notification', 'data': {'chat_id': chat_id, 'chat': {'id': chat.id, 'visitor_name': chat.visitor_name, 'visitor_email': chat.visitor_email, 'status': chat.status.value, 'created_at': chat.created_at.isoformat()}, 'message': {'id': message_data.get('id'), 'message': message_data.get('message'), 'sender_type': message_data.get('sender_type'), 'created_at': message_data.get('created_at')}}}
+ disconnected = []
+ for user_id, websocket in self.staff_connections.items():
+ try:
+ await websocket.send_json(notification_data)
+ except Exception as e:
+ print(f'Error notifying staff {user_id}: {e}')
+ disconnected.append(user_id)
+ for user_id in disconnected:
+ del self.staff_connections[user_id]
+
+ def connect_staff(self, user_id: int, websocket: WebSocket):
+ self.staff_connections[user_id] = websocket
+
+ def disconnect_staff(self, user_id: int):
+ if user_id in self.staff_connections:
+ del self.staff_connections[user_id]
+manager = ConnectionManager()
+
+@router.post('/create', status_code=status.HTTP_201_CREATED)
+async def create_chat(visitor_name: Optional[str]=None, visitor_email: Optional[str]=None, visitor_phone: Optional[str]=None, current_user: Optional[User]=Depends(get_current_user_optional), db: Session=Depends(get_db)):
+ if current_user:
+ chat = Chat(visitor_id=current_user.id, visitor_name=current_user.full_name, visitor_email=current_user.email, status=ChatStatus.pending)
+ else:
+ if not visitor_name:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Visitor name is required')
+ if not visitor_email:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Visitor email is required')
+ chat = Chat(visitor_name=visitor_name, visitor_email=visitor_email, status=ChatStatus.pending)
+ db.add(chat)
+ db.commit()
+ db.refresh(chat)
+ chat_data = {'id': chat.id, 'visitor_name': chat.visitor_name, 'visitor_email': chat.visitor_email, 'status': chat.status.value, 'created_at': chat.created_at.isoformat()}
+ await manager.notify_staff_new_chat(chat_data)
+ return {'success': True, 'data': {'id': chat.id, 'visitor_name': chat.visitor_name, 'visitor_email': chat.visitor_email, 'status': chat.status.value, 'created_at': chat.created_at.isoformat()}}
+
+@router.post('/{chat_id}/accept')
+async def accept_chat(chat_id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
+ if current_user.role.name not in ['staff', 'admin']:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Only staff members can accept chats')
+ chat = db.query(Chat).filter(Chat.id == chat_id).first()
+ if not chat:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Chat not found')
+ if chat.status != ChatStatus.pending:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Chat is not pending')
+ chat.staff_id = current_user.id
+ chat.status = ChatStatus.active
+ db.commit()
+ db.refresh(chat)
+ await manager.broadcast_to_chat({'type': 'chat_accepted', 'data': {'staff_name': current_user.full_name, 'staff_id': current_user.id}}, chat_id)
+ return {'success': True, 'data': {'id': chat.id, 'staff_id': chat.staff_id, 'staff_name': current_user.full_name, 'status': chat.status.value}}
+
+@router.get('/list')
+async def list_chats(status_filter: Optional[str]=None, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
+ if current_user.role.name in ['staff', 'admin']:
+ query = db.query(Chat)
+ if status_filter:
+ try:
+ status_enum = ChatStatus(status_filter)
+ query = query.filter(Chat.status == status_enum)
+ except ValueError:
+ pass
+ chats = query.order_by(Chat.created_at.desc()).all()
+ else:
+ chats = db.query(Chat).filter(Chat.visitor_id == current_user.id).order_by(Chat.created_at.desc()).all()
+ return {'success': True, 'data': [{'id': chat.id, 'visitor_id': chat.visitor_id, 'visitor_name': chat.visitor_name, 'visitor_email': chat.visitor_email, 'staff_id': chat.staff_id, 'staff_name': chat.staff.full_name if chat.staff else None, 'status': chat.status.value, 'created_at': chat.created_at.isoformat(), 'updated_at': chat.updated_at.isoformat(), 'message_count': len(chat.messages)} for chat in chats]}
+
+@router.get('/{chat_id}')
+async def get_chat(chat_id: int, current_user: Optional[User]=Depends(get_current_user_optional), db: Session=Depends(get_db)):
+ chat = db.query(Chat).filter(Chat.id == chat_id).first()
+ if not chat:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Chat not found')
+ if current_user:
+ if current_user.role.name not in ['staff', 'admin']:
+ if chat.visitor_id != current_user.id:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="You don't have permission to view this chat")
+ return {'success': True, 'data': {'id': chat.id, 'visitor_id': chat.visitor_id, 'visitor_name': chat.visitor_name, 'visitor_email': chat.visitor_email, 'staff_id': chat.staff_id, 'staff_name': chat.staff.full_name if chat.staff else None, 'status': chat.status.value, 'created_at': chat.created_at.isoformat(), 'updated_at': chat.updated_at.isoformat()}}
+
+@router.get('/{chat_id}/messages')
+async def get_messages(chat_id: int, current_user: Optional[User]=Depends(get_current_user_optional), db: Session=Depends(get_db)):
+ chat = db.query(Chat).filter(Chat.id == chat_id).first()
+ if not chat:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Chat not found')
+ if current_user:
+ if current_user.role.name not in ['staff', 'admin']:
+ if chat.visitor_id != current_user.id:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="You don't have permission to view this chat")
+ else:
+ pass
+ messages = db.query(ChatMessage).filter(ChatMessage.chat_id == chat_id).order_by(ChatMessage.created_at.asc()).all()
+ return {'success': True, 'data': [{'id': msg.id, 'chat_id': msg.chat_id, 'sender_id': msg.sender_id, 'sender_type': msg.sender_type, 'sender_name': msg.sender.full_name if msg.sender else None, 'message': msg.message, 'is_read': msg.is_read, 'created_at': msg.created_at.isoformat()} for msg in messages]}
+
+@router.post('/{chat_id}/message')
+async def send_message(chat_id: int, message: str, current_user: Optional[User]=Depends(get_current_user_optional), db: Session=Depends(get_db)):
+ chat = db.query(Chat).filter(Chat.id == chat_id).first()
+ if not chat:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Chat not found')
+ if chat.status == ChatStatus.closed:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Chat is closed')
+ sender_type = 'visitor'
+ sender_id = None
+ if current_user:
+ if current_user.role.name in ['staff', 'admin']:
+ sender_type = 'staff'
+ sender_id = current_user.id
+ else:
+ sender_type = 'visitor'
+ sender_id = current_user.id
+ if chat.visitor_id != current_user.id:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="You don't have permission to send messages in this chat")
+ else:
+ sender_type = 'visitor'
+ sender_id = None
+ chat_message = ChatMessage(chat_id=chat_id, sender_id=sender_id, sender_type=sender_type, message=message)
+ db.add(chat_message)
+ db.commit()
+ db.refresh(chat_message)
+ message_data = {'type': 'new_message', 'data': {'id': chat_message.id, 'chat_id': chat_message.chat_id, 'sender_id': chat_message.sender_id, 'sender_type': chat_message.sender_type, 'sender_name': chat_message.sender.full_name if chat_message.sender else None, 'message': chat_message.message, 'is_read': chat_message.is_read, 'created_at': chat_message.created_at.isoformat()}}
+ await manager.broadcast_to_chat(message_data, chat_id)
+ if chat_message.sender_type == 'visitor':
+ await manager.notify_staff_new_message(chat_id, message_data['data'], chat)
+ return {'success': True, 'data': {'id': chat_message.id, 'chat_id': chat_message.chat_id, 'sender_type': chat_message.sender_type, 'message': chat_message.message, 'created_at': chat_message.created_at.isoformat()}}
+
+@router.post('/{chat_id}/close')
+async def close_chat(chat_id: int, current_user: Optional[User]=Depends(get_current_user_optional), db: Session=Depends(get_db)):
+ chat = db.query(Chat).filter(Chat.id == chat_id).first()
+ if not chat:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Chat not found')
+ if current_user:
+ if current_user.role.name not in ['staff', 'admin']:
+ if chat.visitor_id != current_user.id:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="You don't have permission to close this chat")
+ else:
+ pass
+ chat.status = ChatStatus.closed
+ chat.closed_at = datetime.utcnow()
+ db.commit()
+ await manager.broadcast_to_chat({'type': 'chat_closed', 'data': {'chat_id': chat_id}}, chat_id)
+ return {'success': True, 'data': {'id': chat.id, 'status': chat.status.value}}
+
+@router.websocket('/ws/{chat_id}')
+async def websocket_chat(websocket: WebSocket, chat_id: int, user_type: str=None, token: Optional[str]=None):
+ query_params = dict(websocket.query_params)
+ user_type = query_params.get('user_type', 'visitor')
+ token = query_params.get('token')
+ current_user = None
+ if user_type == 'staff' and token:
+ try:
+ from ..middleware.auth import verify_token
+ from ..config.database import get_db
+ payload = verify_token(token)
+ user_id = payload.get('userId')
+ db_gen = get_db()
+ db = next(db_gen)
+ try:
+ current_user = db.query(User).filter(User.id == user_id).first()
+ if not current_user or current_user.role.name not in ['staff', 'admin']:
+ await websocket.close(code=1008, reason='Unauthorized')
+ return
+ finally:
+ db.close()
+ except Exception as e:
+ await websocket.close(code=1008, reason='Invalid token')
+ return
+ await manager.connect_chat(websocket, chat_id, user_type)
+ if user_type == 'staff' and current_user:
+ manager.connect_staff(current_user.id, websocket)
+ try:
+ while True:
+ data = await websocket.receive_text()
+ message_data = json.loads(data)
+ if message_data.get('type') == 'message':
+ from ..config.database import get_db
+ db_gen = get_db()
+ db = next(db_gen)
+ try:
+ chat = db.query(Chat).filter(Chat.id == chat_id).first()
+ if not chat:
+ continue
+ sender_id = current_user.id if current_user else None
+ sender_type = 'staff' if user_type == 'staff' else 'visitor'
+ chat_message = ChatMessage(chat_id=chat_id, sender_id=sender_id, sender_type=sender_type, message=message_data.get('message', ''))
+ db.add(chat_message)
+ db.commit()
+ db.refresh(chat_message)
+ finally:
+ db.close()
+ message_data = {'type': 'new_message', 'data': {'id': chat_message.id, 'chat_id': chat_message.chat_id, 'sender_id': chat_message.sender_id, 'sender_type': chat_message.sender_type, 'sender_name': chat_message.sender.full_name if chat_message.sender else None, 'message': chat_message.message, 'is_read': chat_message.is_read, 'created_at': chat_message.created_at.isoformat()}}
+ await manager.broadcast_to_chat(message_data, chat_id)
+ if chat_message.sender_type == 'visitor':
+ await manager.notify_staff_new_message(chat_id, message_data['data'], chat)
+ except WebSocketDisconnect:
+ manager.disconnect_chat(websocket, chat_id)
+ if user_type == 'staff' and current_user:
+ manager.disconnect_staff(current_user.id)
+
+@router.websocket('/ws/staff/notifications')
+async def websocket_staff_notifications(websocket: WebSocket):
+ current_user = None
+ try:
+ await websocket.accept()
+ query_params = dict(websocket.query_params)
+ token = query_params.get('token')
+ if not token:
+ await websocket.close(code=1008, reason='Token required')
+ return
+ try:
+ from ..middleware.auth import verify_token
+ from ..config.database import get_db
+ payload = verify_token(token)
+ user_id = payload.get('userId')
+ if not user_id:
+ await websocket.close(code=1008, reason='Invalid token payload')
+ return
+ db_gen = get_db()
+ db = next(db_gen)
+ try:
+ current_user = db.query(User).filter(User.id == user_id).first()
+ if not current_user:
+ await websocket.close(code=1008, reason='User not found')
+ return
+ role = db.query(Role).filter(Role.id == current_user.role_id).first()
+ if not role or role.name not in ['staff', 'admin']:
+ await websocket.close(code=1008, reason='Unauthorized role')
+ return
+ finally:
+ db.close()
+ except Exception as e:
+ print(f'WebSocket token verification error: {e}')
+ import traceback
+ traceback.print_exc()
+ await websocket.close(code=1008, reason=f'Token verification failed: {str(e)}')
+ return
+ manager.connect_staff(current_user.id, websocket)
+ try:
+ await websocket.send_json({'type': 'connected', 'data': {'message': 'WebSocket connected'}})
+ except Exception as e:
+ print(f'Error sending initial message: {e}')
+ while True:
+ try:
+ data = await websocket.receive_text()
+ try:
+ message_data = json.loads(data)
+ if message_data.get('type') == 'ping':
+ await websocket.send_json({'type': 'pong', 'data': 'pong'})
+ except json.JSONDecodeError:
+ await websocket.send_json({'type': 'pong', 'data': 'pong'})
+ except WebSocketDisconnect:
+ print('WebSocket disconnected normally')
+ break
+ except Exception as e:
+ print(f'WebSocket receive error: {e}')
+ break
+ except WebSocketDisconnect:
+ print('WebSocket disconnected')
+ except Exception as e:
+ print(f'WebSocket error: {e}')
+ import traceback
+ traceback.print_exc()
+ finally:
+ if current_user:
+ try:
+ manager.disconnect_staff(current_user.id)
+ except:
+ pass
\ No newline at end of file
diff --git a/Backend/src/routes/contact_content_routes.py b/Backend/src/routes/contact_content_routes.py
index b239df30..65d9324b 100644
--- a/Backend/src/routes/contact_content_routes.py
+++ b/Backend/src/routes/contact_content_routes.py
@@ -1,68 +1,23 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
import json
-
from ..config.database import get_db
from ..config.logging_config import get_logger
from ..models.page_content import PageContent, PageType
-
logger = get_logger(__name__)
-
-router = APIRouter(prefix="/contact-content", tags=["contact-content"])
-
+router = APIRouter(prefix='/contact-content', tags=['contact-content'])
def serialize_page_content(content: PageContent) -> dict:
- """Serialize PageContent model to dictionary"""
- return {
- "id": content.id,
- "page_type": content.page_type.value,
- "title": content.title,
- "subtitle": content.subtitle,
- "description": content.description,
- "content": content.content,
- "meta_title": content.meta_title,
- "meta_description": content.meta_description,
- "meta_keywords": content.meta_keywords,
- "og_title": content.og_title,
- "og_description": content.og_description,
- "og_image": content.og_image,
- "canonical_url": content.canonical_url,
- "contact_info": json.loads(content.contact_info) if content.contact_info else None,
- "map_url": content.map_url,
- "is_active": content.is_active,
- "created_at": content.created_at.isoformat() if content.created_at else None,
- "updated_at": content.updated_at.isoformat() if content.updated_at else None,
- }
+ return {'id': content.id, 'page_type': content.page_type.value, 'title': content.title, 'subtitle': content.subtitle, 'description': content.description, 'content': content.content, 'meta_title': content.meta_title, 'meta_description': content.meta_description, 'meta_keywords': content.meta_keywords, 'og_title': content.og_title, 'og_description': content.og_description, 'og_image': content.og_image, 'canonical_url': content.canonical_url, 'contact_info': json.loads(content.contact_info) if content.contact_info else None, 'map_url': content.map_url, 'is_active': content.is_active, 'created_at': content.created_at.isoformat() if content.created_at else None, 'updated_at': content.updated_at.isoformat() if content.updated_at else None}
-
-@router.get("/")
-async def get_contact_content(
- db: Session = Depends(get_db)
-):
- """Get contact page content"""
+@router.get('/')
+async def get_contact_content(db: Session=Depends(get_db)):
try:
content = db.query(PageContent).filter(PageContent.page_type == PageType.CONTACT).first()
-
if not content:
- return {
- "status": "success",
- "data": {
- "page_content": None
- }
- }
-
+ return {'status': 'success', 'data': {'page_content': None}}
content_dict = serialize_page_content(content)
-
- return {
- "status": "success",
- "data": {
- "page_content": content_dict
- }
- }
+ return {'status': 'success', 'data': {'page_content': content_dict}}
except Exception as e:
- logger.error(f"Error fetching contact content: {str(e)}", exc_info=True)
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error fetching contact content: {str(e)}"
- )
-
+ logger.error(f'Error fetching contact content: {str(e)}', exc_info=True)
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching contact content: {str(e)}')
\ No newline at end of file
diff --git a/Backend/src/routes/contact_routes.py b/Backend/src/routes/contact_routes.py
index a6e87bb6..e03448d4 100644
--- a/Backend/src/routes/contact_routes.py
+++ b/Backend/src/routes/contact_routes.py
@@ -3,17 +3,13 @@ from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr
from typing import Optional
import logging
-
from ..config.database import get_db
from ..models.user import User
from ..models.role import Role
from ..models.system_settings import SystemSettings
from ..utils.mailer import send_email
-
logger = logging.getLogger(__name__)
-
-router = APIRouter(prefix="/contact", tags=["contact"])
-
+router = APIRouter(prefix='/contact', tags=['contact'])
class ContactForm(BaseModel):
name: str
@@ -22,182 +18,35 @@ class ContactForm(BaseModel):
message: str
phone: Optional[str] = None
-
def get_admin_email(db: Session) -> str:
- """Get admin email from system settings or find admin user"""
- # First, try to get from company_email (company settings)
- company_email_setting = db.query(SystemSettings).filter(
- SystemSettings.key == "company_email"
- ).first()
-
+ company_email_setting = db.query(SystemSettings).filter(SystemSettings.key == 'company_email').first()
if company_email_setting and company_email_setting.value:
return company_email_setting.value
-
- # Second, try to get from admin_email (legacy setting)
- admin_email_setting = db.query(SystemSettings).filter(
- SystemSettings.key == "admin_email"
- ).first()
-
+ admin_email_setting = db.query(SystemSettings).filter(SystemSettings.key == 'admin_email').first()
if admin_email_setting and admin_email_setting.value:
return admin_email_setting.value
-
- # If not found in settings, find the first admin user
- admin_role = db.query(Role).filter(Role.name == "admin").first()
+ admin_role = db.query(Role).filter(Role.name == 'admin').first()
if admin_role:
- admin_user = db.query(User).filter(
- User.role_id == admin_role.id,
- User.is_active == True
- ).first()
-
+ admin_user = db.query(User).filter(User.role_id == admin_role.id, User.is_active == True).first()
if admin_user:
return admin_user.email
-
- # Fallback to SMTP_FROM_EMAIL if configured
from ..config.settings import settings
if settings.SMTP_FROM_EMAIL:
return settings.SMTP_FROM_EMAIL
-
- # Last resort: raise error
- raise HTTPException(
- status_code=500,
- detail="Admin email not configured. Please set company_email in system settings or ensure an admin user exists."
- )
+ raise HTTPException(status_code=500, detail='Admin email not configured. Please set company_email in system settings or ensure an admin user exists.')
-
-@router.post("/submit")
-async def submit_contact_form(
- contact_data: ContactForm,
- db: Session = Depends(get_db)
-):
- """Submit contact form and send email to admin"""
+@router.post('/submit')
+async def submit_contact_form(contact_data: ContactForm, db: Session=Depends(get_db)):
try:
- # Get admin email
admin_email = get_admin_email(db)
-
- # Create email subject
- subject = f"Contact Form: {contact_data.subject}"
-
- # Create email body (HTML)
- html_body = f"""
-
-
-
-
-
-
-
-
-
-
New Contact Form Submission
-
-
-
- Name:
-
{contact_data.name}
-
-
- Email:
-
{contact_data.email}
-
- {f'
Phone:
{contact_data.phone}
' if contact_data.phone else ''}
-
- Subject:
-
{contact_data.subject}
-
-
- Message:
-
{contact_data.message}
-
-
-
-
-
-
- """
-
- # Create plain text version
- text_body = f"""
-New Contact Form Submission
-
-Name: {contact_data.name}
-Email: {contact_data.email}
-{f'Phone: {contact_data.phone}' if contact_data.phone else ''}
-Subject: {contact_data.subject}
-
-Message:
-{contact_data.message}
- """
-
- # Send email to admin
- await send_email(
- to=admin_email,
- subject=subject,
- html=html_body,
- text=text_body
- )
-
- logger.info(f"Contact form submitted successfully. Email sent to {admin_email}")
-
- return {
- "status": "success",
- "message": "Thank you for contacting us! We will get back to you soon."
- }
-
+ subject = f'Contact Form: {contact_data.subject}'
+ html_body = f
+ text_body = f
+ await send_email(to=admin_email, subject=subject, html=html_body, text=text_body)
+ logger.info(f'Contact form submitted successfully. Email sent to {admin_email}')
+ return {'status': 'success', 'message': 'Thank you for contacting us! We will get back to you soon.'}
except HTTPException:
raise
except Exception as e:
- logger.error(f"Failed to submit contact form: {type(e).__name__}: {str(e)}", exc_info=True)
- raise HTTPException(
- status_code=500,
- detail="Failed to submit contact form. Please try again later."
- )
-
+ logger.error(f'Failed to submit contact form: {type(e).__name__}: {str(e)}', exc_info=True)
+ raise HTTPException(status_code=500, detail='Failed to submit contact form. Please try again later.')
\ No newline at end of file
diff --git a/Backend/src/routes/favorite_routes.py b/Backend/src/routes/favorite_routes.py
index 55734926..fc9bba62 100644
--- a/Backend/src/routes/favorite_routes.py
+++ b/Backend/src/routes/favorite_routes.py
@@ -1,7 +1,6 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import func
-
from ..config.database import get_db
from ..middleware.auth import get_current_user
from ..models.user import User
@@ -9,179 +8,74 @@ from ..models.favorite import Favorite
from ..models.room import Room
from ..models.room_type import RoomType
from ..models.review import Review, ReviewStatus
+router = APIRouter(prefix='/favorites', tags=['favorites'])
-router = APIRouter(prefix="/favorites", tags=["favorites"])
-
-
-@router.get("/")
-async def get_favorites(
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get user's favorite rooms"""
+@router.get('/')
+async def get_favorites(current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
+ if current_user.role in ['admin', 'staff']:
+ raise HTTPException(status_code=403, detail='Admin and staff users cannot have favorites')
try:
- favorites = db.query(Favorite).filter(
- Favorite.user_id == current_user.id
- ).order_by(Favorite.created_at.desc()).all()
-
+ favorites = db.query(Favorite).filter(Favorite.user_id == current_user.id).order_by(Favorite.created_at.desc()).all()
result = []
for favorite in favorites:
if not favorite.room:
continue
-
room = favorite.room
-
- # Get review stats
- review_stats = db.query(
- func.avg(Review.rating).label('average_rating'),
- func.count(Review.id).label('total_reviews')
- ).filter(
- Review.room_id == room.id,
- Review.status == ReviewStatus.approved
- ).first()
-
- room_dict = {
- "id": room.id,
- "room_type_id": room.room_type_id,
- "room_number": room.room_number,
- "floor": room.floor,
- "status": room.status.value if hasattr(room.status, 'value') else room.status,
- "price": float(room.price) if room.price else 0.0,
- "featured": room.featured,
- "description": room.description,
- "amenities": room.amenities,
- "images": room.images or [],
- "average_rating": round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None,
- "total_reviews": review_stats.total_reviews or 0 if review_stats else 0,
- }
-
+ review_stats = db.query(func.avg(Review.rating).label('average_rating'), func.count(Review.id).label('total_reviews')).filter(Review.room_id == room.id, Review.status == ReviewStatus.approved).first()
+ room_dict = {'id': room.id, 'room_type_id': room.room_type_id, 'room_number': room.room_number, 'floor': room.floor, 'status': room.status.value if hasattr(room.status, 'value') else room.status, 'price': float(room.price) if room.price else 0.0, 'featured': room.featured, 'description': room.description, 'amenities': room.amenities, 'images': room.images or [], 'average_rating': round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None, 'total_reviews': review_stats.total_reviews or 0 if review_stats else 0}
if room.room_type:
- room_dict["room_type"] = {
- "id": room.room_type.id,
- "name": room.room_type.name,
- "description": room.room_type.description,
- "base_price": float(room.room_type.base_price) if room.room_type.base_price else 0.0,
- "capacity": room.room_type.capacity,
- "amenities": room.room_type.amenities,
- }
-
- favorite_dict = {
- "id": favorite.id,
- "user_id": favorite.user_id,
- "room_id": favorite.room_id,
- "room": room_dict,
- "created_at": favorite.created_at.isoformat() if favorite.created_at else None,
- }
-
+ room_dict['room_type'] = {'id': room.room_type.id, 'name': room.room_type.name, 'description': room.room_type.description, 'base_price': float(room.room_type.base_price) if room.room_type.base_price else 0.0, 'capacity': room.room_type.capacity, 'amenities': room.room_type.amenities}
+ favorite_dict = {'id': favorite.id, 'user_id': favorite.user_id, 'room_id': favorite.room_id, 'room': room_dict, 'created_at': favorite.created_at.isoformat() if favorite.created_at else None}
result.append(favorite_dict)
-
- return {
- "status": "success",
- "data": {
- "favorites": result,
- "total": len(result),
- }
- }
+ return {'status': 'success', 'data': {'favorites': result, 'total': len(result)}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/{room_id}")
-async def add_favorite(
- room_id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Add room to favorites"""
+@router.post('/{room_id}')
+async def add_favorite(room_id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
+ if current_user.role in ['admin', 'staff']:
+ raise HTTPException(status_code=403, detail='Admin and staff users cannot add favorites')
try:
- # Check if room exists
room = db.query(Room).filter(Room.id == room_id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Check if already favorited
- existing = db.query(Favorite).filter(
- Favorite.user_id == current_user.id,
- Favorite.room_id == room_id
- ).first()
-
+ raise HTTPException(status_code=404, detail='Room not found')
+ existing = db.query(Favorite).filter(Favorite.user_id == current_user.id, Favorite.room_id == room_id).first()
if existing:
- raise HTTPException(
- status_code=400,
- detail="Room already in favorites list"
- )
-
- # Create favorite
- favorite = Favorite(
- user_id=current_user.id,
- room_id=room_id
- )
-
+ raise HTTPException(status_code=400, detail='Room already in favorites list')
+ favorite = Favorite(user_id=current_user.id, room_id=room_id)
db.add(favorite)
db.commit()
db.refresh(favorite)
-
- return {
- "status": "success",
- "message": "Added to favorites list",
- "data": {"favorite": favorite}
- }
+ return {'status': 'success', 'message': 'Added to favorites list', 'data': {'favorite': favorite}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{room_id}")
-async def remove_favorite(
- room_id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Remove room from favorites"""
+@router.delete('/{room_id}')
+async def remove_favorite(room_id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
+ if current_user.role in ['admin', 'staff']:
+ raise HTTPException(status_code=403, detail='Admin and staff users cannot remove favorites')
try:
- favorite = db.query(Favorite).filter(
- Favorite.user_id == current_user.id,
- Favorite.room_id == room_id
- ).first()
-
+ favorite = db.query(Favorite).filter(Favorite.user_id == current_user.id, Favorite.room_id == room_id).first()
if not favorite:
- raise HTTPException(
- status_code=404,
- detail="Room not found in favorites list"
- )
-
+ raise HTTPException(status_code=404, detail='Room not found in favorites list')
db.delete(favorite)
db.commit()
-
- return {
- "status": "success",
- "message": "Removed from favorites list"
- }
+ return {'status': 'success', 'message': 'Removed from favorites list'}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/check/{room_id}")
-async def check_favorite(
- room_id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Check if room is favorited by user"""
+@router.get('/check/{room_id}')
+async def check_favorite(room_id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
+ if current_user.role in ['admin', 'staff']:
+ return {'status': 'success', 'data': {'isFavorited': False}}
try:
- favorite = db.query(Favorite).filter(
- Favorite.user_id == current_user.id,
- Favorite.room_id == room_id
- ).first()
-
- return {
- "status": "success",
- "data": {"isFavorited": favorite is not None}
- }
+ favorite = db.query(Favorite).filter(Favorite.user_id == current_user.id, Favorite.room_id == room_id).first()
+ return {'status': 'success', 'data': {'isFavorited': favorite is not None}}
except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/footer_routes.py b/Backend/src/routes/footer_routes.py
index ba577829..250d1711 100644
--- a/Backend/src/routes/footer_routes.py
+++ b/Backend/src/routes/footer_routes.py
@@ -1,63 +1,23 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
import json
-
from ..config.database import get_db
from ..config.logging_config import get_logger
from ..models.page_content import PageContent, PageType
-
logger = get_logger(__name__)
-
-router = APIRouter(prefix="/footer", tags=["footer"])
-
+router = APIRouter(prefix='/footer', tags=['footer'])
def serialize_page_content(content: PageContent) -> dict:
- """Serialize PageContent model to dictionary"""
- return {
- "id": content.id,
- "page_type": content.page_type.value,
- "title": content.title,
- "subtitle": content.subtitle,
- "description": content.description,
- "content": content.content,
- "social_links": json.loads(content.social_links) if content.social_links else None,
- "footer_links": json.loads(content.footer_links) if content.footer_links else None,
- "badges": json.loads(content.badges) if content.badges else None,
- "copyright_text": content.copyright_text,
- "is_active": content.is_active,
- "created_at": content.created_at.isoformat() if content.created_at else None,
- "updated_at": content.updated_at.isoformat() if content.updated_at else None,
- }
+ return {'id': content.id, 'page_type': content.page_type.value, 'title': content.title, 'subtitle': content.subtitle, 'description': content.description, 'content': content.content, 'social_links': json.loads(content.social_links) if content.social_links else None, 'footer_links': json.loads(content.footer_links) if content.footer_links else None, 'badges': json.loads(content.badges) if content.badges else None, 'copyright_text': content.copyright_text, 'is_active': content.is_active, 'created_at': content.created_at.isoformat() if content.created_at else None, 'updated_at': content.updated_at.isoformat() if content.updated_at else None}
-
-@router.get("/")
-async def get_footer_content(
- db: Session = Depends(get_db)
-):
- """Get footer content"""
+@router.get('/')
+async def get_footer_content(db: Session=Depends(get_db)):
try:
content = db.query(PageContent).filter(PageContent.page_type == PageType.FOOTER).first()
-
if not content:
- return {
- "status": "success",
- "data": {
- "page_content": None
- }
- }
-
+ return {'status': 'success', 'data': {'page_content': None}}
content_dict = serialize_page_content(content)
-
- return {
- "status": "success",
- "data": {
- "page_content": content_dict
- }
- }
+ return {'status': 'success', 'data': {'page_content': content_dict}}
except Exception as e:
- logger.error(f"Error fetching footer content: {str(e)}", exc_info=True)
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error fetching footer content: {str(e)}"
- )
-
+ logger.error(f'Error fetching footer content: {str(e)}', exc_info=True)
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching footer content: {str(e)}')
\ No newline at end of file
diff --git a/Backend/src/routes/home_routes.py b/Backend/src/routes/home_routes.py
index 5163c81e..630986c8 100644
--- a/Backend/src/routes/home_routes.py
+++ b/Backend/src/routes/home_routes.py
@@ -1,110 +1,23 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
import json
-
from ..config.database import get_db
from ..config.logging_config import get_logger
from ..models.page_content import PageContent, PageType
-
logger = get_logger(__name__)
-
-router = APIRouter(prefix="/home", tags=["home"])
-
+router = APIRouter(prefix='/home', tags=['home'])
def serialize_page_content(content: PageContent) -> dict:
- """Serialize PageContent model to dictionary"""
- return {
- "id": content.id,
- "page_type": content.page_type.value,
- "title": content.title,
- "subtitle": content.subtitle,
- "description": content.description,
- "content": content.content,
- "meta_title": content.meta_title,
- "meta_description": content.meta_description,
- "meta_keywords": content.meta_keywords,
- "og_title": content.og_title,
- "og_description": content.og_description,
- "og_image": content.og_image,
- "canonical_url": content.canonical_url,
- "hero_title": content.hero_title,
- "hero_subtitle": content.hero_subtitle,
- "hero_image": content.hero_image,
- "amenities_section_title": content.amenities_section_title,
- "amenities_section_subtitle": content.amenities_section_subtitle,
- "amenities": json.loads(content.amenities) if content.amenities else None,
- "testimonials_section_title": content.testimonials_section_title,
- "testimonials_section_subtitle": content.testimonials_section_subtitle,
- "testimonials": json.loads(content.testimonials) if content.testimonials else None,
- "gallery_section_title": content.gallery_section_title,
- "gallery_section_subtitle": content.gallery_section_subtitle,
- "gallery_images": json.loads(content.gallery_images) if content.gallery_images else None,
- "luxury_section_title": content.luxury_section_title,
- "luxury_section_subtitle": content.luxury_section_subtitle,
- "luxury_section_image": content.luxury_section_image,
- "luxury_features": json.loads(content.luxury_features) if content.luxury_features else None,
- "luxury_gallery_section_title": content.luxury_gallery_section_title,
- "luxury_gallery_section_subtitle": content.luxury_gallery_section_subtitle,
- "luxury_gallery": json.loads(content.luxury_gallery) if content.luxury_gallery else None,
- "luxury_testimonials_section_title": content.luxury_testimonials_section_title,
- "luxury_testimonials_section_subtitle": content.luxury_testimonials_section_subtitle,
- "luxury_testimonials": json.loads(content.luxury_testimonials) if content.luxury_testimonials else None,
- "about_preview_title": content.about_preview_title,
- "about_preview_subtitle": content.about_preview_subtitle,
- "about_preview_content": content.about_preview_content,
- "about_preview_image": content.about_preview_image,
- "stats": json.loads(content.stats) if content.stats else None,
- "luxury_services_section_title": content.luxury_services_section_title,
- "luxury_services_section_subtitle": content.luxury_services_section_subtitle,
- "luxury_services": json.loads(content.luxury_services) if content.luxury_services else None,
- "luxury_experiences_section_title": content.luxury_experiences_section_title,
- "luxury_experiences_section_subtitle": content.luxury_experiences_section_subtitle,
- "luxury_experiences": json.loads(content.luxury_experiences) if content.luxury_experiences else None,
- "awards_section_title": content.awards_section_title,
- "awards_section_subtitle": content.awards_section_subtitle,
- "awards": json.loads(content.awards) if content.awards else None,
- "cta_title": content.cta_title,
- "cta_subtitle": content.cta_subtitle,
- "cta_button_text": content.cta_button_text,
- "cta_button_link": content.cta_button_link,
- "cta_image": content.cta_image,
- "partners_section_title": content.partners_section_title,
- "partners_section_subtitle": content.partners_section_subtitle,
- "partners": json.loads(content.partners) if content.partners else None,
- "is_active": content.is_active,
- "created_at": content.created_at.isoformat() if content.created_at else None,
- "updated_at": content.updated_at.isoformat() if content.updated_at else None,
- }
+ return {'id': content.id, 'page_type': content.page_type.value, 'title': content.title, 'subtitle': content.subtitle, 'description': content.description, 'content': content.content, 'meta_title': content.meta_title, 'meta_description': content.meta_description, 'meta_keywords': content.meta_keywords, 'og_title': content.og_title, 'og_description': content.og_description, 'og_image': content.og_image, 'canonical_url': content.canonical_url, 'hero_title': content.hero_title, 'hero_subtitle': content.hero_subtitle, 'hero_image': content.hero_image, 'amenities_section_title': content.amenities_section_title, 'amenities_section_subtitle': content.amenities_section_subtitle, 'amenities': json.loads(content.amenities) if content.amenities else None, 'testimonials_section_title': content.testimonials_section_title, 'testimonials_section_subtitle': content.testimonials_section_subtitle, 'testimonials': json.loads(content.testimonials) if content.testimonials else None, 'gallery_section_title': content.gallery_section_title, 'gallery_section_subtitle': content.gallery_section_subtitle, 'gallery_images': json.loads(content.gallery_images) if content.gallery_images else None, 'luxury_section_title': content.luxury_section_title, 'luxury_section_subtitle': content.luxury_section_subtitle, 'luxury_section_image': content.luxury_section_image, 'luxury_features': json.loads(content.luxury_features) if content.luxury_features else None, 'luxury_gallery_section_title': content.luxury_gallery_section_title, 'luxury_gallery_section_subtitle': content.luxury_gallery_section_subtitle, 'luxury_gallery': json.loads(content.luxury_gallery) if content.luxury_gallery else None, 'luxury_testimonials_section_title': content.luxury_testimonials_section_title, 'luxury_testimonials_section_subtitle': content.luxury_testimonials_section_subtitle, 'luxury_testimonials': json.loads(content.luxury_testimonials) if content.luxury_testimonials else None, 'about_preview_title': content.about_preview_title, 'about_preview_subtitle': content.about_preview_subtitle, 'about_preview_content': content.about_preview_content, 'about_preview_image': content.about_preview_image, 'stats': json.loads(content.stats) if content.stats else None, 'luxury_services_section_title': content.luxury_services_section_title, 'luxury_services_section_subtitle': content.luxury_services_section_subtitle, 'luxury_services': json.loads(content.luxury_services) if content.luxury_services else None, 'luxury_experiences_section_title': content.luxury_experiences_section_title, 'luxury_experiences_section_subtitle': content.luxury_experiences_section_subtitle, 'luxury_experiences': json.loads(content.luxury_experiences) if content.luxury_experiences else None, 'awards_section_title': content.awards_section_title, 'awards_section_subtitle': content.awards_section_subtitle, 'awards': json.loads(content.awards) if content.awards else None, 'cta_title': content.cta_title, 'cta_subtitle': content.cta_subtitle, 'cta_button_text': content.cta_button_text, 'cta_button_link': content.cta_button_link, 'cta_image': content.cta_image, 'partners_section_title': content.partners_section_title, 'partners_section_subtitle': content.partners_section_subtitle, 'partners': json.loads(content.partners) if content.partners else None, 'is_active': content.is_active, 'created_at': content.created_at.isoformat() if content.created_at else None, 'updated_at': content.updated_at.isoformat() if content.updated_at else None}
-
-@router.get("/")
-async def get_home_content(
- db: Session = Depends(get_db)
-):
- """Get homepage content"""
+@router.get('/')
+async def get_home_content(db: Session=Depends(get_db)):
try:
content = db.query(PageContent).filter(PageContent.page_type == PageType.HOME).first()
-
if not content:
- return {
- "status": "success",
- "data": {
- "page_content": None
- }
- }
-
+ return {'status': 'success', 'data': {'page_content': None}}
content_dict = serialize_page_content(content)
-
- return {
- "status": "success",
- "data": {
- "page_content": content_dict
- }
- }
+ return {'status': 'success', 'data': {'page_content': content_dict}}
except Exception as e:
- logger.error(f"Error fetching home content: {str(e)}", exc_info=True)
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error fetching home content: {str(e)}"
- )
-
+ logger.error(f'Error fetching home content: {str(e)}', exc_info=True)
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching home content: {str(e)}')
\ No newline at end of file
diff --git a/Backend/src/routes/invoice_routes.py b/Backend/src/routes/invoice_routes.py
index c121b123..8fea1dae 100644
--- a/Backend/src/routes/invoice_routes.py
+++ b/Backend/src/routes/invoice_routes.py
@@ -2,139 +2,60 @@ from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
-
from ..config.database import get_db
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
from ..models.invoice import Invoice, InvoiceStatus
from ..models.booking import Booking
from ..services.invoice_service import InvoiceService
+router = APIRouter(prefix='/invoices', tags=['invoices'])
-router = APIRouter(prefix="/invoices", tags=["invoices"])
-
-
-@router.get("/")
-async def get_invoices(
- booking_id: Optional[int] = Query(None),
- status_filter: Optional[str] = Query(None, alias="status"),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get invoices for current user (or all invoices for admin)"""
+@router.get('/')
+async def get_invoices(booking_id: Optional[int]=Query(None), status_filter: Optional[str]=Query(None, alias='status'), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Admin can see all invoices, users can only see their own
user_id = None if current_user.role_id == 1 else current_user.id
-
- result = InvoiceService.get_invoices(
- db=db,
- user_id=user_id,
- booking_id=booking_id,
- status=status_filter,
- page=page,
- limit=limit
- )
-
- return {
- "status": "success",
- "data": result
- }
+ result = InvoiceService.get_invoices(db=db, user_id=user_id, booking_id=booking_id, status=status_filter, page=page, limit=limit)
+ return {'status': 'success', 'data': result}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{id}")
-async def get_invoice_by_id(
- id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get invoice by ID"""
+@router.get('/{id}')
+async def get_invoice_by_id(id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
invoice = InvoiceService.get_invoice(id, db)
-
if not invoice:
- raise HTTPException(status_code=404, detail="Invoice not found")
-
- # Check access: admin can see all, users can only see their own
- if current_user.role_id != 1 and invoice["user_id"] != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- return {
- "status": "success",
- "data": {"invoice": invoice}
- }
+ raise HTTPException(status_code=404, detail='Invoice not found')
+ if current_user.role_id != 1 and invoice['user_id'] != current_user.id:
+ raise HTTPException(status_code=403, detail='Forbidden')
+ return {'status': 'success', 'data': {'invoice': invoice}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/")
-async def create_invoice(
- invoice_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create a new invoice from a booking (Admin/Staff only)"""
+@router.post('/')
+async def create_invoice(invoice_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Only admin/staff can create invoices
if current_user.role_id not in [1, 2]:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- booking_id = invoice_data.get("booking_id")
+ raise HTTPException(status_code=403, detail='Forbidden')
+ booking_id = invoice_data.get('booking_id')
if not booking_id:
- raise HTTPException(status_code=400, detail="booking_id is required")
-
- # Ensure booking_id is an integer
+ raise HTTPException(status_code=400, detail='booking_id is required')
try:
booking_id = int(booking_id)
except (ValueError, TypeError):
- raise HTTPException(status_code=400, detail="booking_id must be a valid integer")
-
- # Check if booking exists
+ raise HTTPException(status_code=400, detail='booking_id must be a valid integer')
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
- # Prepare invoice kwargs
- invoice_kwargs = {
- "company_name": invoice_data.get("company_name"),
- "company_address": invoice_data.get("company_address"),
- "company_phone": invoice_data.get("company_phone"),
- "company_email": invoice_data.get("company_email"),
- "company_tax_id": invoice_data.get("company_tax_id"),
- "company_logo_url": invoice_data.get("company_logo_url"),
- "customer_tax_id": invoice_data.get("customer_tax_id"),
- "notes": invoice_data.get("notes"),
- "terms_and_conditions": invoice_data.get("terms_and_conditions"),
- "payment_instructions": invoice_data.get("payment_instructions"),
- }
-
- # Add promotion code to invoice notes if present in booking
- invoice_notes = invoice_kwargs.get("notes", "")
+ raise HTTPException(status_code=404, detail='Booking not found')
+ invoice_kwargs = {'company_name': invoice_data.get('company_name'), 'company_address': invoice_data.get('company_address'), 'company_phone': invoice_data.get('company_phone'), 'company_email': invoice_data.get('company_email'), 'company_tax_id': invoice_data.get('company_tax_id'), 'company_logo_url': invoice_data.get('company_logo_url'), 'customer_tax_id': invoice_data.get('customer_tax_id'), 'notes': invoice_data.get('notes'), 'terms_and_conditions': invoice_data.get('terms_and_conditions'), 'payment_instructions': invoice_data.get('payment_instructions')}
+ invoice_notes = invoice_kwargs.get('notes', '')
if booking.promotion_code:
- promotion_note = f"Promotion Code: {booking.promotion_code}"
- invoice_notes = f"{promotion_note}\n{invoice_notes}".strip() if invoice_notes else promotion_note
- invoice_kwargs["notes"] = invoice_notes
-
- # Create invoice
- invoice = InvoiceService.create_invoice_from_booking(
- booking_id=booking_id,
- db=db,
- created_by_id=current_user.id,
- tax_rate=invoice_data.get("tax_rate", 0.0),
- discount_amount=invoice_data.get("discount_amount", 0.0),
- due_days=invoice_data.get("due_days", 30),
- **invoice_kwargs
- )
-
- return {
- "status": "success",
- "message": "Invoice created successfully",
- "data": {"invoice": invoice}
- }
+ promotion_note = f'Promotion Code: {booking.promotion_code}'
+ invoice_notes = f'{promotion_note}\n{invoice_notes}'.strip() if invoice_notes else promotion_note
+ invoice_kwargs['notes'] = invoice_notes
+ invoice = InvoiceService.create_invoice_from_booking(booking_id=booking_id, db=db, created_by_id=current_user.id, tax_rate=invoice_data.get('tax_rate', 0.0), discount_amount=invoice_data.get('discount_amount', 0.0), due_days=invoice_data.get('due_days', 30), **invoice_kwargs)
+ return {'status': 'success', 'message': 'Invoice created successfully', 'data': {'invoice': invoice}}
except HTTPException:
raise
except ValueError as e:
@@ -142,33 +63,14 @@ async def create_invoice(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}")
-async def update_invoice(
- id: int,
- invoice_data: dict,
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Update an invoice (Admin/Staff only)"""
+@router.put('/{id}')
+async def update_invoice(id: int, invoice_data: dict, current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
invoice = db.query(Invoice).filter(Invoice.id == id).first()
if not invoice:
- raise HTTPException(status_code=404, detail="Invoice not found")
-
- # Update invoice
- updated_invoice = InvoiceService.update_invoice(
- invoice_id=id,
- db=db,
- updated_by_id=current_user.id,
- **invoice_data
- )
-
- return {
- "status": "success",
- "message": "Invoice updated successfully",
- "data": {"invoice": updated_invoice}
- }
+ raise HTTPException(status_code=404, detail='Invoice not found')
+ updated_invoice = InvoiceService.update_invoice(invoice_id=id, db=db, updated_by_id=current_user.id, **invoice_data)
+ return {'status': 'success', 'message': 'Invoice updated successfully', 'data': {'invoice': updated_invoice}}
except HTTPException:
raise
except ValueError as e:
@@ -176,30 +78,12 @@ async def update_invoice(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/{id}/mark-paid")
-async def mark_invoice_as_paid(
- id: int,
- payment_data: dict,
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Mark an invoice as paid (Admin/Staff only)"""
+@router.post('/{id}/mark-paid')
+async def mark_invoice_as_paid(id: int, payment_data: dict, current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
- amount = payment_data.get("amount")
-
- updated_invoice = InvoiceService.mark_invoice_as_paid(
- invoice_id=id,
- db=db,
- amount=amount,
- updated_by_id=current_user.id
- )
-
- return {
- "status": "success",
- "message": "Invoice marked as paid successfully",
- "data": {"invoice": updated_invoice}
- }
+ amount = payment_data.get('amount')
+ updated_invoice = InvoiceService.mark_invoice_as_paid(invoice_id=id, db=db, amount=amount, updated_by_id=current_user.id)
+ return {'status': 'success', 'message': 'Invoice marked as paid successfully', 'data': {'invoice': updated_invoice}}
except HTTPException:
raise
except ValueError as e:
@@ -207,61 +91,32 @@ async def mark_invoice_as_paid(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{id}")
-async def delete_invoice(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Delete an invoice (Admin only)"""
+@router.delete('/{id}')
+async def delete_invoice(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
invoice = db.query(Invoice).filter(Invoice.id == id).first()
if not invoice:
- raise HTTPException(status_code=404, detail="Invoice not found")
-
+ raise HTTPException(status_code=404, detail='Invoice not found')
db.delete(invoice)
db.commit()
-
- return {
- "status": "success",
- "message": "Invoice deleted successfully"
- }
+ return {'status': 'success', 'message': 'Invoice deleted successfully'}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/booking/{booking_id}")
-async def get_invoices_by_booking(
- booking_id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get all invoices for a specific booking"""
+@router.get('/booking/{booking_id}')
+async def get_invoices_by_booking(booking_id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Check if booking exists and user has access
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
- # Check access: admin can see all, users can only see their own bookings
+ raise HTTPException(status_code=404, detail='Booking not found')
if current_user.role_id != 1 and booking.user_id != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- result = InvoiceService.get_invoices(
- db=db,
- booking_id=booking_id
- )
-
- return {
- "status": "success",
- "data": result
- }
+ raise HTTPException(status_code=403, detail='Forbidden')
+ result = InvoiceService.get_invoices(db=db, booking_id=booking_id)
+ return {'status': 'success', 'data': result}
except HTTPException:
raise
except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
-
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/page_content_routes.py b/Backend/src/routes/page_content_routes.py
index bebef6eb..90136046 100644
--- a/Backend/src/routes/page_content_routes.py
+++ b/Backend/src/routes/page_content_routes.py
@@ -7,425 +7,123 @@ import json
import os
import aiofiles
import uuid
-
from ..config.database import get_db
from ..config.logging_config import get_logger
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
from ..models.page_content import PageContent, PageType
-
logger = get_logger(__name__)
+router = APIRouter(prefix='/page-content', tags=['page-content'])
-router = APIRouter(prefix="/page-content", tags=["page-content"])
-
-
-@router.get("/")
-async def get_all_page_contents(
- db: Session = Depends(get_db)
-):
- """Get all page contents"""
+@router.get('/')
+async def get_all_page_contents(db: Session=Depends(get_db)):
try:
contents = db.query(PageContent).all()
result = []
for content in contents:
- content_dict = {
- "id": content.id,
- "page_type": content.page_type.value,
- "title": content.title,
- "subtitle": content.subtitle,
- "description": content.description,
- "content": content.content,
- "meta_title": content.meta_title,
- "meta_description": content.meta_description,
- "meta_keywords": content.meta_keywords,
- "og_title": content.og_title,
- "og_description": content.og_description,
- "og_image": content.og_image,
- "canonical_url": content.canonical_url,
- "contact_info": json.loads(content.contact_info) if content.contact_info else None,
- "map_url": content.map_url,
- "social_links": json.loads(content.social_links) if content.social_links else None,
- "footer_links": json.loads(content.footer_links) if content.footer_links else None,
- "badges": json.loads(content.badges) if content.badges else None,
- "copyright_text": content.copyright_text,
- "hero_title": content.hero_title,
- "hero_subtitle": content.hero_subtitle,
- "hero_image": content.hero_image,
- "story_content": content.story_content,
- "values": json.loads(content.values) if content.values else None,
- "features": json.loads(content.features) if content.features else None,
- "about_hero_image": content.about_hero_image,
- "mission": content.mission,
- "vision": content.vision,
- "team": json.loads(content.team) if content.team else None,
- "timeline": json.loads(content.timeline) if content.timeline else None,
- "achievements": json.loads(content.achievements) if content.achievements else None,
- "amenities_section_title": content.amenities_section_title,
- "amenities_section_subtitle": content.amenities_section_subtitle,
- "amenities": json.loads(content.amenities) if content.amenities else None,
- "testimonials_section_title": content.testimonials_section_title,
- "testimonials_section_subtitle": content.testimonials_section_subtitle,
- "testimonials": json.loads(content.testimonials) if content.testimonials else None,
- "gallery_section_title": content.gallery_section_title,
- "gallery_section_subtitle": content.gallery_section_subtitle,
- "gallery_images": json.loads(content.gallery_images) if content.gallery_images else None,
- "luxury_section_title": content.luxury_section_title,
- "luxury_section_subtitle": content.luxury_section_subtitle,
- "luxury_section_image": content.luxury_section_image,
- "luxury_features": json.loads(content.luxury_features) if content.luxury_features else None,
- "luxury_gallery_section_title": content.luxury_gallery_section_title,
- "luxury_gallery_section_subtitle": content.luxury_gallery_section_subtitle,
- "luxury_gallery": json.loads(content.luxury_gallery) if content.luxury_gallery else None,
- "luxury_testimonials_section_title": content.luxury_testimonials_section_title,
- "luxury_testimonials_section_subtitle": content.luxury_testimonials_section_subtitle,
- "luxury_testimonials": json.loads(content.luxury_testimonials) if content.luxury_testimonials else None,
- "about_preview_title": content.about_preview_title,
- "about_preview_subtitle": content.about_preview_subtitle,
- "about_preview_content": content.about_preview_content,
- "about_preview_image": content.about_preview_image,
- "stats": json.loads(content.stats) if content.stats else None,
- "luxury_services_section_title": content.luxury_services_section_title,
- "luxury_services_section_subtitle": content.luxury_services_section_subtitle,
- "luxury_services": json.loads(content.luxury_services) if content.luxury_services else None,
- "luxury_experiences_section_title": content.luxury_experiences_section_title,
- "luxury_experiences_section_subtitle": content.luxury_experiences_section_subtitle,
- "luxury_experiences": json.loads(content.luxury_experiences) if content.luxury_experiences else None,
- "awards_section_title": content.awards_section_title,
- "awards_section_subtitle": content.awards_section_subtitle,
- "awards": json.loads(content.awards) if content.awards else None,
- "cta_title": content.cta_title,
- "cta_subtitle": content.cta_subtitle,
- "cta_button_text": content.cta_button_text,
- "cta_button_link": content.cta_button_link,
- "cta_image": content.cta_image,
- "partners_section_title": content.partners_section_title,
- "partners_section_subtitle": content.partners_section_subtitle,
- "partners": json.loads(content.partners) if content.partners else None,
- "is_active": content.is_active,
- "created_at": content.created_at.isoformat() if content.created_at else None,
- "updated_at": content.updated_at.isoformat() if content.updated_at else None,
- }
+ content_dict = {'id': content.id, 'page_type': content.page_type.value, 'title': content.title, 'subtitle': content.subtitle, 'description': content.description, 'content': content.content, 'meta_title': content.meta_title, 'meta_description': content.meta_description, 'meta_keywords': content.meta_keywords, 'og_title': content.og_title, 'og_description': content.og_description, 'og_image': content.og_image, 'canonical_url': content.canonical_url, 'contact_info': json.loads(content.contact_info) if content.contact_info else None, 'map_url': content.map_url, 'social_links': json.loads(content.social_links) if content.social_links else None, 'footer_links': json.loads(content.footer_links) if content.footer_links else None, 'badges': json.loads(content.badges) if content.badges else None, 'copyright_text': content.copyright_text, 'hero_title': content.hero_title, 'hero_subtitle': content.hero_subtitle, 'hero_image': content.hero_image, 'story_content': content.story_content, 'values': json.loads(content.values) if content.values else None, 'features': json.loads(content.features) if content.features else None, 'about_hero_image': content.about_hero_image, 'mission': content.mission, 'vision': content.vision, 'team': json.loads(content.team) if content.team else None, 'timeline': json.loads(content.timeline) if content.timeline else None, 'achievements': json.loads(content.achievements) if content.achievements else None, 'amenities_section_title': content.amenities_section_title, 'amenities_section_subtitle': content.amenities_section_subtitle, 'amenities': json.loads(content.amenities) if content.amenities else None, 'testimonials_section_title': content.testimonials_section_title, 'testimonials_section_subtitle': content.testimonials_section_subtitle, 'testimonials': json.loads(content.testimonials) if content.testimonials else None, 'gallery_section_title': content.gallery_section_title, 'gallery_section_subtitle': content.gallery_section_subtitle, 'gallery_images': json.loads(content.gallery_images) if content.gallery_images else None, 'luxury_section_title': content.luxury_section_title, 'luxury_section_subtitle': content.luxury_section_subtitle, 'luxury_section_image': content.luxury_section_image, 'luxury_features': json.loads(content.luxury_features) if content.luxury_features else None, 'luxury_gallery_section_title': content.luxury_gallery_section_title, 'luxury_gallery_section_subtitle': content.luxury_gallery_section_subtitle, 'luxury_gallery': json.loads(content.luxury_gallery) if content.luxury_gallery else None, 'luxury_testimonials_section_title': content.luxury_testimonials_section_title, 'luxury_testimonials_section_subtitle': content.luxury_testimonials_section_subtitle, 'luxury_testimonials': json.loads(content.luxury_testimonials) if content.luxury_testimonials else None, 'about_preview_title': content.about_preview_title, 'about_preview_subtitle': content.about_preview_subtitle, 'about_preview_content': content.about_preview_content, 'about_preview_image': content.about_preview_image, 'stats': json.loads(content.stats) if content.stats else None, 'luxury_services_section_title': content.luxury_services_section_title, 'luxury_services_section_subtitle': content.luxury_services_section_subtitle, 'luxury_services': json.loads(content.luxury_services) if content.luxury_services else None, 'luxury_experiences_section_title': content.luxury_experiences_section_title, 'luxury_experiences_section_subtitle': content.luxury_experiences_section_subtitle, 'luxury_experiences': json.loads(content.luxury_experiences) if content.luxury_experiences else None, 'awards_section_title': content.awards_section_title, 'awards_section_subtitle': content.awards_section_subtitle, 'awards': json.loads(content.awards) if content.awards else None, 'cta_title': content.cta_title, 'cta_subtitle': content.cta_subtitle, 'cta_button_text': content.cta_button_text, 'cta_button_link': content.cta_button_link, 'cta_image': content.cta_image, 'partners_section_title': content.partners_section_title, 'partners_section_subtitle': content.partners_section_subtitle, 'partners': json.loads(content.partners) if content.partners else None, 'is_active': content.is_active, 'created_at': content.created_at.isoformat() if content.created_at else None, 'updated_at': content.updated_at.isoformat() if content.updated_at else None}
result.append(content_dict)
-
- return {
- "status": "success",
- "data": {
- "page_contents": result
- }
- }
+ return {'status': 'success', 'data': {'page_contents': result}}
except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error fetching page contents: {str(e)}"
- )
-
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching page contents: {str(e)}')
def get_base_url(request: Request) -> str:
- """Get base URL for image normalization"""
- return os.getenv("SERVER_URL") or f"http://{request.headers.get('host', 'localhost:8000')}"
-
+ return os.getenv('SERVER_URL') or f'http://{request.headers.get('host', 'localhost:8000')}'
def normalize_image_url(image_url: str, base_url: str) -> str:
- """Normalize image URL to absolute URL"""
if not image_url:
return image_url
if image_url.startswith('http://') or image_url.startswith('https://'):
return image_url
if image_url.startswith('/'):
- return f"{base_url}{image_url}"
- return f"{base_url}/{image_url}"
+ return f'{base_url}{image_url}'
+ return f'{base_url}/{image_url}'
-
-@router.post("/upload", dependencies=[Depends(authorize_roles("admin"))])
-async def upload_page_content_image(
- request: Request,
- image: UploadFile = File(...),
- current_user: User = Depends(authorize_roles("admin")),
-):
- """Upload page content image (Admin only)"""
+@router.post('/upload', dependencies=[Depends(authorize_roles('admin'))])
+async def upload_page_content_image(request: Request, image: UploadFile=File(...), current_user: User=Depends(authorize_roles('admin'))):
try:
- logger.info(f"Upload request received: filename={image.filename}, content_type={image.content_type}")
-
- # Validate file exists
+ logger.info(f'Upload request received: filename={image.filename}, content_type={image.content_type}')
if not image:
- logger.error("No file provided in upload request")
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="No file provided"
- )
-
- # Validate file type
+ logger.error('No file provided in upload request')
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='No file provided')
if not image.content_type or not image.content_type.startswith('image/'):
- logger.error(f"Invalid file type: {image.content_type}")
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=f"File must be an image. Received: {image.content_type}"
- )
-
- # Validate filename
+ logger.error(f'Invalid file type: {image.content_type}')
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'File must be an image. Received: {image.content_type}')
if not image.filename:
- logger.error("No filename provided in upload request")
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Filename is required"
- )
-
- # Create uploads directory
- upload_dir = Path(__file__).parent.parent.parent / "uploads" / "page-content"
+ logger.error('No filename provided in upload request')
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Filename is required')
+ upload_dir = Path(__file__).parent.parent.parent / 'uploads' / 'page-content'
upload_dir.mkdir(parents=True, exist_ok=True)
- logger.info(f"Upload directory: {upload_dir}")
-
- # Generate filename
+ logger.info(f'Upload directory: {upload_dir}')
ext = Path(image.filename).suffix or '.jpg'
- filename = f"page-content-{uuid.uuid4()}{ext}"
+ filename = f'page-content-{uuid.uuid4()}{ext}'
file_path = upload_dir / filename
-
- # Save file
async with aiofiles.open(file_path, 'wb') as f:
content = await image.read()
if not content:
- logger.error("Empty file uploaded")
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="File is empty"
- )
+ logger.error('Empty file uploaded')
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='File is empty')
await f.write(content)
- logger.info(f"File saved successfully: {file_path}, size: {len(content)} bytes")
-
- # Return the image URL
- image_url = f"/uploads/page-content/{filename}"
+ logger.info(f'File saved successfully: {file_path}, size: {len(content)} bytes')
+ image_url = f'/uploads/page-content/{filename}'
base_url = get_base_url(request)
full_url = normalize_image_url(image_url, base_url)
-
- logger.info(f"Upload successful: {image_url}")
- return {
- "success": True,
- "status": "success",
- "message": "Image uploaded successfully",
- "data": {
- "image_url": image_url,
- "full_url": full_url
- }
- }
+ logger.info(f'Upload successful: {image_url}')
+ return {'success': True, 'status': 'success', 'message': 'Image uploaded successfully', 'data': {'image_url': image_url, 'full_url': full_url}}
except HTTPException as e:
- logger.error(f"HTTPException in upload: {e.detail}")
+ logger.error(f'HTTPException in upload: {e.detail}')
raise
except Exception as e:
- logger.error(f"Unexpected error uploading image: {str(e)}", exc_info=True)
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error uploading image: {str(e)}"
- )
+ logger.error(f'Unexpected error uploading image: {str(e)}', exc_info=True)
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error uploading image: {str(e)}')
-
-@router.get("/{page_type}")
-async def get_page_content(
- page_type: PageType,
- db: Session = Depends(get_db)
-):
- """Get content for a specific page"""
+@router.get('/{page_type}')
+async def get_page_content(page_type: PageType, db: Session=Depends(get_db)):
try:
content = db.query(PageContent).filter(PageContent.page_type == page_type).first()
-
if not content:
- # Return default structure if not found
- return {
- "status": "success",
- "data": {
- "page_content": None
- }
- }
-
- content_dict = {
- "id": content.id,
- "page_type": content.page_type.value,
- "title": content.title,
- "subtitle": content.subtitle,
- "description": content.description,
- "content": content.content,
- "meta_title": content.meta_title,
- "meta_description": content.meta_description,
- "meta_keywords": content.meta_keywords,
- "og_title": content.og_title,
- "og_description": content.og_description,
- "og_image": content.og_image,
- "canonical_url": content.canonical_url,
- "contact_info": json.loads(content.contact_info) if content.contact_info else None,
- "map_url": content.map_url,
- "social_links": json.loads(content.social_links) if content.social_links else None,
- "footer_links": json.loads(content.footer_links) if content.footer_links else None,
- "badges": json.loads(content.badges) if content.badges else None,
- "copyright_text": content.copyright_text,
- "hero_title": content.hero_title,
- "hero_subtitle": content.hero_subtitle,
- "hero_image": content.hero_image,
- "story_content": content.story_content,
- "values": json.loads(content.values) if content.values else None,
- "features": json.loads(content.features) if content.features else None,
- "about_hero_image": content.about_hero_image,
- "mission": content.mission,
- "vision": content.vision,
- "team": json.loads(content.team) if content.team else None,
- "timeline": json.loads(content.timeline) if content.timeline else None,
- "achievements": json.loads(content.achievements) if content.achievements else None,
- "amenities_section_title": content.amenities_section_title,
- "amenities_section_subtitle": content.amenities_section_subtitle,
- "amenities": json.loads(content.amenities) if content.amenities else None,
- "testimonials_section_title": content.testimonials_section_title,
- "testimonials_section_subtitle": content.testimonials_section_subtitle,
- "testimonials": json.loads(content.testimonials) if content.testimonials else None,
- "gallery_section_title": content.gallery_section_title,
- "gallery_section_subtitle": content.gallery_section_subtitle,
- "gallery_images": json.loads(content.gallery_images) if content.gallery_images else None,
- "luxury_section_title": content.luxury_section_title,
- "luxury_section_subtitle": content.luxury_section_subtitle,
- "luxury_section_image": content.luxury_section_image,
- "luxury_features": json.loads(content.luxury_features) if content.luxury_features else None,
- "luxury_gallery_section_title": content.luxury_gallery_section_title,
- "luxury_gallery_section_subtitle": content.luxury_gallery_section_subtitle,
- "luxury_gallery": json.loads(content.luxury_gallery) if content.luxury_gallery else None,
- "luxury_testimonials_section_title": content.luxury_testimonials_section_title,
- "luxury_testimonials_section_subtitle": content.luxury_testimonials_section_subtitle,
- "luxury_testimonials": json.loads(content.luxury_testimonials) if content.luxury_testimonials else None,
- "about_preview_title": content.about_preview_title,
- "about_preview_subtitle": content.about_preview_subtitle,
- "about_preview_content": content.about_preview_content,
- "about_preview_image": content.about_preview_image,
- "stats": json.loads(content.stats) if content.stats else None,
- "luxury_services_section_title": content.luxury_services_section_title,
- "luxury_services_section_subtitle": content.luxury_services_section_subtitle,
- "luxury_services": json.loads(content.luxury_services) if content.luxury_services else None,
- "luxury_experiences_section_title": content.luxury_experiences_section_title,
- "luxury_experiences_section_subtitle": content.luxury_experiences_section_subtitle,
- "luxury_experiences": json.loads(content.luxury_experiences) if content.luxury_experiences else None,
- "awards_section_title": content.awards_section_title,
- "awards_section_subtitle": content.awards_section_subtitle,
- "awards": json.loads(content.awards) if content.awards else None,
- "cta_title": content.cta_title,
- "cta_subtitle": content.cta_subtitle,
- "cta_button_text": content.cta_button_text,
- "cta_button_link": content.cta_button_link,
- "cta_image": content.cta_image,
- "partners_section_title": content.partners_section_title,
- "partners_section_subtitle": content.partners_section_subtitle,
- "partners": json.loads(content.partners) if content.partners else None,
- "is_active": content.is_active,
- "created_at": content.created_at.isoformat() if content.created_at else None,
- "updated_at": content.updated_at.isoformat() if content.updated_at else None,
- }
-
- return {
- "status": "success",
- "data": {
- "page_content": content_dict
- }
- }
+ return {'status': 'success', 'data': {'page_content': None}}
+ content_dict = {'id': content.id, 'page_type': content.page_type.value, 'title': content.title, 'subtitle': content.subtitle, 'description': content.description, 'content': content.content, 'meta_title': content.meta_title, 'meta_description': content.meta_description, 'meta_keywords': content.meta_keywords, 'og_title': content.og_title, 'og_description': content.og_description, 'og_image': content.og_image, 'canonical_url': content.canonical_url, 'contact_info': json.loads(content.contact_info) if content.contact_info else None, 'map_url': content.map_url, 'social_links': json.loads(content.social_links) if content.social_links else None, 'footer_links': json.loads(content.footer_links) if content.footer_links else None, 'badges': json.loads(content.badges) if content.badges else None, 'copyright_text': content.copyright_text, 'hero_title': content.hero_title, 'hero_subtitle': content.hero_subtitle, 'hero_image': content.hero_image, 'story_content': content.story_content, 'values': json.loads(content.values) if content.values else None, 'features': json.loads(content.features) if content.features else None, 'about_hero_image': content.about_hero_image, 'mission': content.mission, 'vision': content.vision, 'team': json.loads(content.team) if content.team else None, 'timeline': json.loads(content.timeline) if content.timeline else None, 'achievements': json.loads(content.achievements) if content.achievements else None, 'amenities_section_title': content.amenities_section_title, 'amenities_section_subtitle': content.amenities_section_subtitle, 'amenities': json.loads(content.amenities) if content.amenities else None, 'testimonials_section_title': content.testimonials_section_title, 'testimonials_section_subtitle': content.testimonials_section_subtitle, 'testimonials': json.loads(content.testimonials) if content.testimonials else None, 'gallery_section_title': content.gallery_section_title, 'gallery_section_subtitle': content.gallery_section_subtitle, 'gallery_images': json.loads(content.gallery_images) if content.gallery_images else None, 'luxury_section_title': content.luxury_section_title, 'luxury_section_subtitle': content.luxury_section_subtitle, 'luxury_section_image': content.luxury_section_image, 'luxury_features': json.loads(content.luxury_features) if content.luxury_features else None, 'luxury_gallery_section_title': content.luxury_gallery_section_title, 'luxury_gallery_section_subtitle': content.luxury_gallery_section_subtitle, 'luxury_gallery': json.loads(content.luxury_gallery) if content.luxury_gallery else None, 'luxury_testimonials_section_title': content.luxury_testimonials_section_title, 'luxury_testimonials_section_subtitle': content.luxury_testimonials_section_subtitle, 'luxury_testimonials': json.loads(content.luxury_testimonials) if content.luxury_testimonials else None, 'about_preview_title': content.about_preview_title, 'about_preview_subtitle': content.about_preview_subtitle, 'about_preview_content': content.about_preview_content, 'about_preview_image': content.about_preview_image, 'stats': json.loads(content.stats) if content.stats else None, 'luxury_services_section_title': content.luxury_services_section_title, 'luxury_services_section_subtitle': content.luxury_services_section_subtitle, 'luxury_services': json.loads(content.luxury_services) if content.luxury_services else None, 'luxury_experiences_section_title': content.luxury_experiences_section_title, 'luxury_experiences_section_subtitle': content.luxury_experiences_section_subtitle, 'luxury_experiences': json.loads(content.luxury_experiences) if content.luxury_experiences else None, 'awards_section_title': content.awards_section_title, 'awards_section_subtitle': content.awards_section_subtitle, 'awards': json.loads(content.awards) if content.awards else None, 'cta_title': content.cta_title, 'cta_subtitle': content.cta_subtitle, 'cta_button_text': content.cta_button_text, 'cta_button_link': content.cta_button_link, 'cta_image': content.cta_image, 'partners_section_title': content.partners_section_title, 'partners_section_subtitle': content.partners_section_subtitle, 'partners': json.loads(content.partners) if content.partners else None, 'is_active': content.is_active, 'created_at': content.created_at.isoformat() if content.created_at else None, 'updated_at': content.updated_at.isoformat() if content.updated_at else None}
+ return {'status': 'success', 'data': {'page_content': content_dict}}
except Exception as e:
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error fetching page content: {str(e)}"
- )
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error fetching page content: {str(e)}')
-
-@router.post("/{page_type}")
-async def create_or_update_page_content(
- page_type: PageType,
- title: Optional[str] = None,
- subtitle: Optional[str] = None,
- description: Optional[str] = None,
- content: Optional[str] = None,
- meta_title: Optional[str] = None,
- meta_description: Optional[str] = None,
- meta_keywords: Optional[str] = None,
- og_title: Optional[str] = None,
- og_description: Optional[str] = None,
- og_image: Optional[str] = None,
- canonical_url: Optional[str] = None,
- contact_info: Optional[str] = None,
- map_url: Optional[str] = None,
- social_links: Optional[str] = None,
- footer_links: Optional[str] = None,
- badges: Optional[str] = None,
- hero_title: Optional[str] = None,
- hero_subtitle: Optional[str] = None,
- hero_image: Optional[str] = None,
- story_content: Optional[str] = None,
- values: Optional[str] = None,
- features: Optional[str] = None,
- about_hero_image: Optional[str] = None,
- mission: Optional[str] = None,
- vision: Optional[str] = None,
- team: Optional[str] = None,
- timeline: Optional[str] = None,
- achievements: Optional[str] = None,
- is_active: bool = True,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create or update page content (admin only)"""
+@router.post('/{page_type}')
+async def create_or_update_page_content(page_type: PageType, title: Optional[str]=None, subtitle: Optional[str]=None, description: Optional[str]=None, content: Optional[str]=None, meta_title: Optional[str]=None, meta_description: Optional[str]=None, meta_keywords: Optional[str]=None, og_title: Optional[str]=None, og_description: Optional[str]=None, og_image: Optional[str]=None, canonical_url: Optional[str]=None, contact_info: Optional[str]=None, map_url: Optional[str]=None, social_links: Optional[str]=None, footer_links: Optional[str]=None, badges: Optional[str]=None, hero_title: Optional[str]=None, hero_subtitle: Optional[str]=None, hero_image: Optional[str]=None, story_content: Optional[str]=None, values: Optional[str]=None, features: Optional[str]=None, about_hero_image: Optional[str]=None, mission: Optional[str]=None, vision: Optional[str]=None, team: Optional[str]=None, timeline: Optional[str]=None, achievements: Optional[str]=None, is_active: bool=True, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- authorize_roles(current_user, ["admin"])
-
- # Validate JSON fields if provided
+ authorize_roles(current_user, ['admin'])
if contact_info:
try:
json.loads(contact_info)
except json.JSONDecodeError:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Invalid JSON in contact_info"
- )
-
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid JSON in contact_info')
if social_links:
try:
json.loads(social_links)
except json.JSONDecodeError:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Invalid JSON in social_links"
- )
-
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid JSON in social_links')
if footer_links:
try:
json.loads(footer_links)
except json.JSONDecodeError:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Invalid JSON in footer_links"
- )
-
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid JSON in footer_links')
if badges:
try:
json.loads(badges)
except json.JSONDecodeError:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Invalid JSON in badges"
- )
-
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid JSON in badges')
if values:
try:
json.loads(values)
except json.JSONDecodeError:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Invalid JSON in values"
- )
-
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid JSON in values')
if features:
try:
json.loads(features)
except json.JSONDecodeError:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail="Invalid JSON in features"
- )
-
- # Check if content exists
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid JSON in features')
existing_content = db.query(PageContent).filter(PageContent.page_type == page_type).first()
-
if existing_content:
- # Update existing
if title is not None:
existing_content.title = title
if subtitle is not None:
@@ -484,224 +182,49 @@ async def create_or_update_page_content(
existing_content.achievements = achievements
if is_active is not None:
existing_content.is_active = is_active
-
existing_content.updated_at = datetime.utcnow()
db.commit()
db.refresh(existing_content)
-
- return {
- "status": "success",
- "message": "Page content updated successfully",
- "data": {
- "page_content": {
- "id": existing_content.id,
- "page_type": existing_content.page_type.value,
- "title": existing_content.title,
- "updated_at": existing_content.updated_at.isoformat() if existing_content.updated_at else None,
- }
- }
- }
+ return {'status': 'success', 'message': 'Page content updated successfully', 'data': {'page_content': {'id': existing_content.id, 'page_type': existing_content.page_type.value, 'title': existing_content.title, 'updated_at': existing_content.updated_at.isoformat() if existing_content.updated_at else None}}}
else:
- # Create new
- new_content = PageContent(
- page_type=page_type,
- title=title,
- subtitle=subtitle,
- description=description,
- content=content,
- meta_title=meta_title,
- meta_description=meta_description,
- meta_keywords=meta_keywords,
- og_title=og_title,
- og_description=og_description,
- og_image=og_image,
- canonical_url=canonical_url,
- contact_info=contact_info,
- map_url=map_url,
- social_links=social_links,
- footer_links=footer_links,
- badges=badges,
- hero_title=hero_title,
- hero_subtitle=hero_subtitle,
- hero_image=hero_image,
- story_content=story_content,
- values=values,
- features=features,
- about_hero_image=about_hero_image,
- mission=mission,
- vision=vision,
- team=team,
- timeline=timeline,
- achievements=achievements,
- is_active=is_active,
- )
-
+ new_content = PageContent(page_type=page_type, title=title, subtitle=subtitle, description=description, content=content, meta_title=meta_title, meta_description=meta_description, meta_keywords=meta_keywords, og_title=og_title, og_description=og_description, og_image=og_image, canonical_url=canonical_url, contact_info=contact_info, map_url=map_url, social_links=social_links, footer_links=footer_links, badges=badges, hero_title=hero_title, hero_subtitle=hero_subtitle, hero_image=hero_image, story_content=story_content, values=values, features=features, about_hero_image=about_hero_image, mission=mission, vision=vision, team=team, timeline=timeline, achievements=achievements, is_active=is_active)
db.add(new_content)
db.commit()
db.refresh(new_content)
-
- return {
- "status": "success",
- "message": "Page content created successfully",
- "data": {
- "page_content": {
- "id": new_content.id,
- "page_type": new_content.page_type.value,
- "title": new_content.title,
- "created_at": new_content.created_at.isoformat() if new_content.created_at else None,
- }
- }
- }
+ return {'status': 'success', 'message': 'Page content created successfully', 'data': {'page_content': {'id': new_content.id, 'page_type': new_content.page_type.value, 'title': new_content.title, 'created_at': new_content.created_at.isoformat() if new_content.created_at else None}}}
except HTTPException:
raise
except Exception as e:
db.rollback()
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error saving page content: {str(e)}"
- )
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error saving page content: {str(e)}')
-
-@router.put("/{page_type}")
-async def update_page_content(
- page_type: PageType,
- page_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create or update page content using JSON body (admin only)"""
+@router.put('/{page_type}')
+async def update_page_content(page_type: PageType, page_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- authorize_roles(current_user, ["admin"])
-
+ authorize_roles(current_user, ['admin'])
existing_content = db.query(PageContent).filter(PageContent.page_type == page_type).first()
-
if not existing_content:
- # Create new content if it doesn't exist
- existing_content = PageContent(
- page_type=page_type,
- is_active=True,
- )
+ existing_content = PageContent(page_type=page_type, is_active=True)
db.add(existing_content)
-
- # Update fields from request body
for key, value in page_data.items():
if hasattr(existing_content, key):
- # Handle JSON fields - convert dict/list to JSON string
- if key in ["contact_info", "social_links", "footer_links", "badges", "values", "features",
- "amenities", "testimonials", "gallery_images", "stats", "luxury_features",
- "luxury_gallery", "luxury_testimonials", "luxury_services", "luxury_experiences",
- "awards", "partners", "team", "timeline", "achievements"] and value is not None:
+ if key in ['contact_info', 'social_links', 'footer_links', 'badges', 'values', 'features', 'amenities', 'testimonials', 'gallery_images', 'stats', 'luxury_features', 'luxury_gallery', 'luxury_testimonials', 'luxury_services', 'luxury_experiences', 'awards', 'partners', 'team', 'timeline', 'achievements'] and value is not None:
if isinstance(value, str):
- # Already a string, validate it's valid JSON
try:
json.loads(value)
except json.JSONDecodeError:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=f"Invalid JSON in {key}"
- )
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f'Invalid JSON in {key}')
elif isinstance(value, (dict, list)):
- # Convert dict/list to JSON string for storage
value = json.dumps(value)
-
- # Skip None values to allow partial updates
if value is not None:
setattr(existing_content, key, value)
-
existing_content.updated_at = datetime.utcnow()
db.commit()
db.refresh(existing_content)
-
- content_dict = {
- "id": existing_content.id,
- "page_type": existing_content.page_type.value,
- "title": existing_content.title,
- "subtitle": existing_content.subtitle,
- "description": existing_content.description,
- "content": existing_content.content,
- "meta_title": existing_content.meta_title,
- "meta_description": existing_content.meta_description,
- "meta_keywords": existing_content.meta_keywords,
- "og_title": existing_content.og_title,
- "og_description": existing_content.og_description,
- "og_image": existing_content.og_image,
- "canonical_url": existing_content.canonical_url,
- "contact_info": json.loads(existing_content.contact_info) if existing_content.contact_info else None,
- "map_url": existing_content.map_url,
- "social_links": json.loads(existing_content.social_links) if existing_content.social_links else None,
- "footer_links": json.loads(existing_content.footer_links) if existing_content.footer_links else None,
- "badges": json.loads(existing_content.badges) if existing_content.badges else None,
- "copyright_text": existing_content.copyright_text,
- "hero_title": existing_content.hero_title,
- "hero_subtitle": existing_content.hero_subtitle,
- "hero_image": existing_content.hero_image,
- "story_content": existing_content.story_content,
- "values": json.loads(existing_content.values) if existing_content.values else None,
- "features": json.loads(existing_content.features) if existing_content.features else None,
- "about_hero_image": existing_content.about_hero_image,
- "mission": existing_content.mission,
- "vision": existing_content.vision,
- "team": json.loads(existing_content.team) if existing_content.team else None,
- "timeline": json.loads(existing_content.timeline) if existing_content.timeline else None,
- "achievements": json.loads(existing_content.achievements) if existing_content.achievements else None,
- "amenities_section_title": existing_content.amenities_section_title,
- "amenities_section_subtitle": existing_content.amenities_section_subtitle,
- "amenities": json.loads(existing_content.amenities) if existing_content.amenities else None,
- "testimonials_section_title": existing_content.testimonials_section_title,
- "testimonials_section_subtitle": existing_content.testimonials_section_subtitle,
- "testimonials": json.loads(existing_content.testimonials) if existing_content.testimonials else None,
- "gallery_section_title": existing_content.gallery_section_title,
- "gallery_section_subtitle": existing_content.gallery_section_subtitle,
- "gallery_images": json.loads(existing_content.gallery_images) if existing_content.gallery_images else None,
- "luxury_section_title": existing_content.luxury_section_title,
- "luxury_section_subtitle": existing_content.luxury_section_subtitle,
- "luxury_section_image": existing_content.luxury_section_image,
- "luxury_features": json.loads(existing_content.luxury_features) if existing_content.luxury_features else None,
- "luxury_gallery_section_title": existing_content.luxury_gallery_section_title,
- "luxury_gallery_section_subtitle": existing_content.luxury_gallery_section_subtitle,
- "luxury_gallery": json.loads(existing_content.luxury_gallery) if existing_content.luxury_gallery else None,
- "luxury_testimonials_section_title": existing_content.luxury_testimonials_section_title,
- "luxury_testimonials_section_subtitle": existing_content.luxury_testimonials_section_subtitle,
- "luxury_testimonials": json.loads(existing_content.luxury_testimonials) if existing_content.luxury_testimonials else None,
- "about_preview_title": existing_content.about_preview_title,
- "about_preview_subtitle": existing_content.about_preview_subtitle,
- "about_preview_content": existing_content.about_preview_content,
- "about_preview_image": existing_content.about_preview_image,
- "stats": json.loads(existing_content.stats) if existing_content.stats else None,
- "luxury_services_section_title": existing_content.luxury_services_section_title,
- "luxury_services_section_subtitle": existing_content.luxury_services_section_subtitle,
- "luxury_services": json.loads(existing_content.luxury_services) if existing_content.luxury_services else None,
- "luxury_experiences_section_title": existing_content.luxury_experiences_section_title,
- "luxury_experiences_section_subtitle": existing_content.luxury_experiences_section_subtitle,
- "luxury_experiences": json.loads(existing_content.luxury_experiences) if existing_content.luxury_experiences else None,
- "awards_section_title": existing_content.awards_section_title,
- "awards_section_subtitle": existing_content.awards_section_subtitle,
- "awards": json.loads(existing_content.awards) if existing_content.awards else None,
- "cta_title": existing_content.cta_title,
- "cta_subtitle": existing_content.cta_subtitle,
- "cta_button_text": existing_content.cta_button_text,
- "cta_button_link": existing_content.cta_button_link,
- "cta_image": existing_content.cta_image,
- "partners_section_title": existing_content.partners_section_title,
- "partners_section_subtitle": existing_content.partners_section_subtitle,
- "partners": json.loads(existing_content.partners) if existing_content.partners else None,
- "is_active": existing_content.is_active,
- "updated_at": existing_content.updated_at.isoformat() if existing_content.updated_at else None,
- }
-
- return {
- "status": "success",
- "message": "Page content updated successfully",
- "data": {
- "page_content": content_dict
- }
- }
+ content_dict = {'id': existing_content.id, 'page_type': existing_content.page_type.value, 'title': existing_content.title, 'subtitle': existing_content.subtitle, 'description': existing_content.description, 'content': existing_content.content, 'meta_title': existing_content.meta_title, 'meta_description': existing_content.meta_description, 'meta_keywords': existing_content.meta_keywords, 'og_title': existing_content.og_title, 'og_description': existing_content.og_description, 'og_image': existing_content.og_image, 'canonical_url': existing_content.canonical_url, 'contact_info': json.loads(existing_content.contact_info) if existing_content.contact_info else None, 'map_url': existing_content.map_url, 'social_links': json.loads(existing_content.social_links) if existing_content.social_links else None, 'footer_links': json.loads(existing_content.footer_links) if existing_content.footer_links else None, 'badges': json.loads(existing_content.badges) if existing_content.badges else None, 'copyright_text': existing_content.copyright_text, 'hero_title': existing_content.hero_title, 'hero_subtitle': existing_content.hero_subtitle, 'hero_image': existing_content.hero_image, 'story_content': existing_content.story_content, 'values': json.loads(existing_content.values) if existing_content.values else None, 'features': json.loads(existing_content.features) if existing_content.features else None, 'about_hero_image': existing_content.about_hero_image, 'mission': existing_content.mission, 'vision': existing_content.vision, 'team': json.loads(existing_content.team) if existing_content.team else None, 'timeline': json.loads(existing_content.timeline) if existing_content.timeline else None, 'achievements': json.loads(existing_content.achievements) if existing_content.achievements else None, 'amenities_section_title': existing_content.amenities_section_title, 'amenities_section_subtitle': existing_content.amenities_section_subtitle, 'amenities': json.loads(existing_content.amenities) if existing_content.amenities else None, 'testimonials_section_title': existing_content.testimonials_section_title, 'testimonials_section_subtitle': existing_content.testimonials_section_subtitle, 'testimonials': json.loads(existing_content.testimonials) if existing_content.testimonials else None, 'gallery_section_title': existing_content.gallery_section_title, 'gallery_section_subtitle': existing_content.gallery_section_subtitle, 'gallery_images': json.loads(existing_content.gallery_images) if existing_content.gallery_images else None, 'luxury_section_title': existing_content.luxury_section_title, 'luxury_section_subtitle': existing_content.luxury_section_subtitle, 'luxury_section_image': existing_content.luxury_section_image, 'luxury_features': json.loads(existing_content.luxury_features) if existing_content.luxury_features else None, 'luxury_gallery_section_title': existing_content.luxury_gallery_section_title, 'luxury_gallery_section_subtitle': existing_content.luxury_gallery_section_subtitle, 'luxury_gallery': json.loads(existing_content.luxury_gallery) if existing_content.luxury_gallery else None, 'luxury_testimonials_section_title': existing_content.luxury_testimonials_section_title, 'luxury_testimonials_section_subtitle': existing_content.luxury_testimonials_section_subtitle, 'luxury_testimonials': json.loads(existing_content.luxury_testimonials) if existing_content.luxury_testimonials else None, 'about_preview_title': existing_content.about_preview_title, 'about_preview_subtitle': existing_content.about_preview_subtitle, 'about_preview_content': existing_content.about_preview_content, 'about_preview_image': existing_content.about_preview_image, 'stats': json.loads(existing_content.stats) if existing_content.stats else None, 'luxury_services_section_title': existing_content.luxury_services_section_title, 'luxury_services_section_subtitle': existing_content.luxury_services_section_subtitle, 'luxury_services': json.loads(existing_content.luxury_services) if existing_content.luxury_services else None, 'luxury_experiences_section_title': existing_content.luxury_experiences_section_title, 'luxury_experiences_section_subtitle': existing_content.luxury_experiences_section_subtitle, 'luxury_experiences': json.loads(existing_content.luxury_experiences) if existing_content.luxury_experiences else None, 'awards_section_title': existing_content.awards_section_title, 'awards_section_subtitle': existing_content.awards_section_subtitle, 'awards': json.loads(existing_content.awards) if existing_content.awards else None, 'cta_title': existing_content.cta_title, 'cta_subtitle': existing_content.cta_subtitle, 'cta_button_text': existing_content.cta_button_text, 'cta_button_link': existing_content.cta_button_link, 'cta_image': existing_content.cta_image, 'partners_section_title': existing_content.partners_section_title, 'partners_section_subtitle': existing_content.partners_section_subtitle, 'partners': json.loads(existing_content.partners) if existing_content.partners else None, 'is_active': existing_content.is_active, 'updated_at': existing_content.updated_at.isoformat() if existing_content.updated_at else None}
+ return {'status': 'success', 'message': 'Page content updated successfully', 'data': {'page_content': content_dict}}
except HTTPException:
raise
except Exception as e:
db.rollback()
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=f"Error updating page content: {str(e)}"
- )
-
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f'Error updating page content: {str(e)}')
\ No newline at end of file
diff --git a/Backend/src/routes/payment_routes.py b/Backend/src/routes/payment_routes.py
index 699b91d4..1fd7cd2f 100644
--- a/Backend/src/routes/payment_routes.py
+++ b/Backend/src/routes/payment_routes.py
@@ -3,7 +3,6 @@ from sqlalchemy.orm import Session, joinedload, selectinload
from typing import Optional
from datetime import datetime
import os
-
from ..config.database import get_db
from ..config.settings import settings
from ..middleware.auth import get_current_user, authorize_roles
@@ -14,945 +13,415 @@ from ..utils.mailer import send_email
from ..utils.email_templates import payment_confirmation_email_template, booking_status_changed_email_template
from ..services.stripe_service import StripeService
from ..services.paypal_service import PayPalService
+router = APIRouter(prefix='/payments', tags=['payments'])
-router = APIRouter(prefix="/payments", tags=["payments"])
-
-
-async def cancel_booking_on_payment_failure(booking: Booking, db: Session, reason: str = "Payment failed or canceled"):
- """
- Helper function to cancel a booking when payment fails or is canceled.
- This bypasses the normal cancellation restrictions and sends cancellation email.
- """
+async def cancel_booking_on_payment_failure(booking: Booking, db: Session, reason: str='Payment failed or canceled'):
if booking.status == BookingStatus.cancelled:
- return # Already cancelled
-
+ return
+ from sqlalchemy.orm import selectinload
+ booking = db.query(Booking).options(selectinload(Booking.payments)).filter(Booking.id == booking.id).first()
+ if booking.payments:
+ for payment in booking.payments:
+ if payment.payment_status == PaymentStatus.pending:
+ payment.payment_status = PaymentStatus.failed
+ existing_notes = payment.notes or ''
+ cancellation_note = f'\nPayment cancelled due to booking cancellation: {reason} on {datetime.utcnow().isoformat()}'
+ payment.notes = existing_notes + cancellation_note if existing_notes else cancellation_note.strip()
booking.status = BookingStatus.cancelled
db.commit()
db.refresh(booking)
-
- # Send cancellation email (non-blocking)
try:
from ..models.system_settings import SystemSettings
-
- # Get client URL from settings
- 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_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.user:
- 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,
- subject=f"Booking Cancelled - {booking.booking_number}",
- html=email_html
- )
+ 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, 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 cancellation email: {e}")
+ logger.error(f'Failed to send cancellation email: {e}')
-
-@router.get("/")
-async def get_payments(
- booking_id: Optional[int] = Query(None),
- status_filter: Optional[str] = Query(None, alias="status"),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get all payments"""
+@router.get('/')
+async def get_payments(booking_id: Optional[int]=Query(None), status_filter: Optional[str]=Query(None, alias='status'), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Build base query
if booking_id:
query = db.query(Payment).filter(Payment.booking_id == booking_id)
else:
query = db.query(Payment)
-
- # Filter by status
if status_filter:
try:
query = query.filter(Payment.payment_status == PaymentStatus(status_filter))
except ValueError:
pass
-
- # Users can only see their own payments unless admin
- if current_user.role_id != 1: # Not admin
+ if current_user.role_id != 1:
query = query.join(Booking).filter(Booking.user_id == current_user.id)
-
- # Get total count before applying eager loading
total = query.count()
-
- # Load payments with booking and user relationships using selectinload to avoid join conflicts
- query = query.options(
- selectinload(Payment.booking).selectinload(Booking.user)
- )
-
+ query = query.options(selectinload(Payment.booking).selectinload(Booking.user))
offset = (page - 1) * limit
payments = query.order_by(Payment.created_at.desc()).offset(offset).limit(limit).all()
-
result = []
for payment in payments:
- payment_dict = {
- "id": payment.id,
- "booking_id": payment.booking_id,
- "amount": float(payment.amount) if payment.amount else 0.0,
- "payment_method": payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else payment.payment_method,
- "payment_type": payment.payment_type.value if isinstance(payment.payment_type, PaymentType) else payment.payment_type,
- "deposit_percentage": payment.deposit_percentage,
- "related_payment_id": payment.related_payment_id,
- "payment_status": payment.payment_status.value if isinstance(payment.payment_status, PaymentStatus) else payment.payment_status,
- "transaction_id": payment.transaction_id,
- "payment_date": payment.payment_date.isoformat() if payment.payment_date else None,
- "notes": payment.notes,
- "created_at": payment.created_at.isoformat() if payment.created_at else None,
- }
-
+ payment_dict = {'id': payment.id, 'booking_id': payment.booking_id, 'amount': float(payment.amount) if payment.amount else 0.0, 'payment_method': payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else payment.payment_method, 'payment_type': payment.payment_type.value if isinstance(payment.payment_type, PaymentType) else payment.payment_type, 'deposit_percentage': payment.deposit_percentage, 'related_payment_id': payment.related_payment_id, 'payment_status': payment.payment_status.value if isinstance(payment.payment_status, PaymentStatus) else payment.payment_status, 'transaction_id': payment.transaction_id, 'payment_date': payment.payment_date.isoformat() if payment.payment_date else None, 'notes': payment.notes, 'created_at': payment.created_at.isoformat() if payment.created_at else None}
if payment.booking:
- payment_dict["booking"] = {
- "id": payment.booking.id,
- "booking_number": payment.booking.booking_number,
- }
- # Include user information if available
+ payment_dict['booking'] = {'id': payment.booking.id, 'booking_number': payment.booking.booking_number}
if payment.booking.user:
- payment_dict["booking"]["user"] = {
- "id": payment.booking.user.id,
- "name": payment.booking.user.full_name,
- "full_name": payment.booking.user.full_name,
- "email": payment.booking.user.email,
- }
-
+ payment_dict['booking']['user'] = {'id': payment.booking.user.id, 'name': payment.booking.user.full_name, 'full_name': payment.booking.user.full_name, 'email': payment.booking.user.email}
result.append(payment_dict)
-
- return {
- "status": "success",
- "data": {
- "payments": result,
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'payments': result, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except HTTPException:
raise
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Error fetching payments: {str(e)}", exc_info=True)
- raise HTTPException(status_code=500, detail=f"Error fetching payments: {str(e)}")
+ logger.error(f'Error fetching payments: {str(e)}', exc_info=True)
+ raise HTTPException(status_code=500, detail=f'Error fetching payments: {str(e)}')
-
-@router.get("/booking/{booking_id}")
-async def get_payments_by_booking_id(
- booking_id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get all payments for a specific booking"""
+@router.get('/booking/{booking_id}')
+async def get_payments_by_booking_id(booking_id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Check if booking exists and user has access
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
- # Check access - users can only see their own bookings unless admin
+ raise HTTPException(status_code=404, detail='Booking not found')
if current_user.role_id != 1 and booking.user_id != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- # Get all payments for this booking with user relationship
- payments = db.query(Payment).options(
- joinedload(Payment.booking).joinedload(Booking.user)
- ).filter(Payment.booking_id == booking_id).order_by(Payment.created_at.desc()).all()
-
+ raise HTTPException(status_code=403, detail='Forbidden')
+ payments = db.query(Payment).options(joinedload(Payment.booking).joinedload(Booking.user)).filter(Payment.booking_id == booking_id).order_by(Payment.created_at.desc()).all()
result = []
for payment in payments:
- payment_dict = {
- "id": payment.id,
- "booking_id": payment.booking_id,
- "amount": float(payment.amount) if payment.amount else 0.0,
- "payment_method": payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else payment.payment_method,
- "payment_type": payment.payment_type.value if isinstance(payment.payment_type, PaymentType) else payment.payment_type,
- "deposit_percentage": payment.deposit_percentage,
- "related_payment_id": payment.related_payment_id,
- "payment_status": payment.payment_status.value if isinstance(payment.payment_status, PaymentStatus) else payment.payment_status,
- "transaction_id": payment.transaction_id,
- "payment_date": payment.payment_date.isoformat() if payment.payment_date else None,
- "notes": payment.notes,
- "created_at": payment.created_at.isoformat() if payment.created_at else None,
- }
-
+ payment_dict = {'id': payment.id, 'booking_id': payment.booking_id, 'amount': float(payment.amount) if payment.amount else 0.0, 'payment_method': payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else payment.payment_method, 'payment_type': payment.payment_type.value if isinstance(payment.payment_type, PaymentType) else payment.payment_type, 'deposit_percentage': payment.deposit_percentage, 'related_payment_id': payment.related_payment_id, 'payment_status': payment.payment_status.value if isinstance(payment.payment_status, PaymentStatus) else payment.payment_status, 'transaction_id': payment.transaction_id, 'payment_date': payment.payment_date.isoformat() if payment.payment_date else None, 'notes': payment.notes, 'created_at': payment.created_at.isoformat() if payment.created_at else None}
if payment.booking:
- payment_dict["booking"] = {
- "id": payment.booking.id,
- "booking_number": payment.booking.booking_number,
- }
- # Include user information if available
+ payment_dict['booking'] = {'id': payment.booking.id, 'booking_number': payment.booking.booking_number}
if payment.booking.user:
- payment_dict["booking"]["user"] = {
- "id": payment.booking.user.id,
- "name": payment.booking.user.full_name,
- "full_name": payment.booking.user.full_name,
- "email": payment.booking.user.email,
- }
-
+ payment_dict['booking']['user'] = {'id': payment.booking.user.id, 'name': payment.booking.user.full_name, 'full_name': payment.booking.user.full_name, 'email': payment.booking.user.email}
result.append(payment_dict)
-
- return {
- "status": "success",
- "data": {
- "payments": result
- }
- }
+ return {'status': 'success', 'data': {'payments': result}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{id}")
-async def get_payment_by_id(
- id: int,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get payment by ID"""
+@router.get('/{id}')
+async def get_payment_by_id(id: int, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
payment = db.query(Payment).filter(Payment.id == id).first()
if not payment:
- raise HTTPException(status_code=404, detail="Payment not found")
-
- # Check access
- if current_user.role_id != 1: # Not admin
+ raise HTTPException(status_code=404, detail='Payment not found')
+ if current_user.role_id != 1:
if payment.booking and payment.booking.user_id != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- payment_dict = {
- "id": payment.id,
- "booking_id": payment.booking_id,
- "amount": float(payment.amount) if payment.amount else 0.0,
- "payment_method": payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else payment.payment_method,
- "payment_type": payment.payment_type.value if isinstance(payment.payment_type, PaymentType) else payment.payment_type,
- "deposit_percentage": payment.deposit_percentage,
- "related_payment_id": payment.related_payment_id,
- "payment_status": payment.payment_status.value if isinstance(payment.payment_status, PaymentStatus) else payment.payment_status,
- "transaction_id": payment.transaction_id,
- "payment_date": payment.payment_date.isoformat() if payment.payment_date else None,
- "notes": payment.notes,
- "created_at": payment.created_at.isoformat() if payment.created_at else None,
- }
-
+ raise HTTPException(status_code=403, detail='Forbidden')
+ payment_dict = {'id': payment.id, 'booking_id': payment.booking_id, 'amount': float(payment.amount) if payment.amount else 0.0, 'payment_method': payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else payment.payment_method, 'payment_type': payment.payment_type.value if isinstance(payment.payment_type, PaymentType) else payment.payment_type, 'deposit_percentage': payment.deposit_percentage, 'related_payment_id': payment.related_payment_id, 'payment_status': payment.payment_status.value if isinstance(payment.payment_status, PaymentStatus) else payment.payment_status, 'transaction_id': payment.transaction_id, 'payment_date': payment.payment_date.isoformat() if payment.payment_date else None, 'notes': payment.notes, 'created_at': payment.created_at.isoformat() if payment.created_at else None}
if payment.booking:
- payment_dict["booking"] = {
- "id": payment.booking.id,
- "booking_number": payment.booking.booking_number,
- }
-
- return {
- "status": "success",
- "data": {"payment": payment_dict}
- }
+ payment_dict['booking'] = {'id': payment.booking.id, 'booking_number': payment.booking.booking_number}
+ return {'status': 'success', 'data': {'payment': payment_dict}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/")
-async def create_payment(
- payment_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create new payment"""
+@router.post('/')
+async def create_payment(payment_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- booking_id = payment_data.get("booking_id")
- amount = float(payment_data.get("amount", 0))
- payment_method = payment_data.get("payment_method", "cash")
- payment_type = payment_data.get("payment_type", "full")
-
- # Check if booking exists
+ booking_id = payment_data.get('booking_id')
+ amount = float(payment_data.get('amount', 0))
+ payment_method = payment_data.get('payment_method', 'cash')
+ payment_type = payment_data.get('payment_type', 'full')
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
- # Check access
+ raise HTTPException(status_code=404, detail='Booking not found')
if current_user.role_id != 1 and booking.user_id != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- # Create payment
- payment = Payment(
- booking_id=booking_id,
- amount=amount,
- payment_method=PaymentMethod(payment_method),
- payment_type=PaymentType(payment_type),
- payment_status=PaymentStatus.pending,
- payment_date=datetime.utcnow() if payment_data.get("mark_as_paid") else None,
- notes=payment_data.get("notes"),
- )
-
- # If marked as paid, update status
- if payment_data.get("mark_as_paid"):
+ raise HTTPException(status_code=403, detail='Forbidden')
+ payment = Payment(booking_id=booking_id, amount=amount, payment_method=PaymentMethod(payment_method), payment_type=PaymentType(payment_type), payment_status=PaymentStatus.pending, payment_date=datetime.utcnow() if payment_data.get('mark_as_paid') else None, notes=payment_data.get('notes'))
+ if payment_data.get('mark_as_paid'):
payment.payment_status = PaymentStatus.completed
payment.payment_date = datetime.utcnow()
-
db.add(payment)
db.commit()
db.refresh(payment)
-
- # Send payment confirmation email if payment was marked as paid (non-blocking)
if payment.payment_status == PaymentStatus.completed and booking.user:
try:
from ..models.system_settings import SystemSettings
-
- # Get client URL from settings
- 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"))
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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')
+ 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 = payment_confirmation_email_template(
- booking_number=booking.booking_number,
- guest_name=booking.user.full_name,
- amount=float(payment.amount),
- payment_method=payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else str(payment.payment_method),
- transaction_id=payment.transaction_id,
- payment_type=payment.payment_type.value if payment.payment_type else None,
- total_price=float(booking.total_price),
- client_url=client_url,
- currency_symbol=currency_symbol
- )
- await send_email(
- to=booking.user.email,
- subject=f"Payment Confirmed - {booking.booking_number}",
- html=email_html
- )
+ email_html = payment_confirmation_email_template(booking_number=booking.booking_number, guest_name=booking.user.full_name, amount=float(payment.amount), payment_method=payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else str(payment.payment_method), transaction_id=payment.transaction_id, payment_type=payment.payment_type.value if payment.payment_type else None, total_price=float(booking.total_price), client_url=client_url, currency_symbol=currency_symbol)
+ await send_email(to=booking.user.email, subject=f'Payment Confirmed - {booking.booking_number}', html=email_html)
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Failed to send payment confirmation email: {e}")
-
- return {
- "status": "success",
- "message": "Payment created successfully",
- "data": {"payment": payment}
- }
+ logger.error(f'Failed to send payment confirmation email: {e}')
+ return {'status': 'success', 'message': 'Payment created successfully', 'data': {'payment': payment}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}/status", dependencies=[Depends(authorize_roles("admin", "staff"))])
-async def update_payment_status(
- id: int,
- status_data: dict,
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Update payment status (Admin/Staff only)"""
+@router.put('/{id}/status', dependencies=[Depends(authorize_roles('admin', 'staff'))])
+async def update_payment_status(id: int, status_data: dict, current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
payment = db.query(Payment).filter(Payment.id == id).first()
if not payment:
- raise HTTPException(status_code=404, detail="Payment not found")
-
- status_value = status_data.get("status")
+ raise HTTPException(status_code=404, detail='Payment not found')
+ status_value = status_data.get('status')
old_status = payment.payment_status
-
if status_value:
try:
new_status = PaymentStatus(status_value)
payment.payment_status = new_status
-
- # Auto-cancel booking if payment is marked as failed or refunded
if new_status in [PaymentStatus.failed, PaymentStatus.refunded]:
booking = db.query(Booking).filter(Booking.id == payment.booking_id).first()
if booking and booking.status != BookingStatus.cancelled:
- await cancel_booking_on_payment_failure(
- booking,
- db,
- reason=f"Payment {new_status.value}"
- )
+ await cancel_booking_on_payment_failure(booking, db, reason=f'Payment {new_status.value}')
except ValueError:
- raise HTTPException(status_code=400, detail="Invalid payment status")
-
- if status_data.get("transaction_id"):
- payment.transaction_id = status_data["transaction_id"]
-
- if status_data.get("mark_as_paid"):
+ raise HTTPException(status_code=400, detail='Invalid payment status')
+ if status_data.get('transaction_id'):
+ payment.transaction_id = status_data['transaction_id']
+ if status_data.get('mark_as_paid'):
payment.payment_status = PaymentStatus.completed
payment.payment_date = datetime.utcnow()
-
db.commit()
db.refresh(payment)
-
- # Send payment confirmation email if payment was just completed (non-blocking)
if payment.payment_status == PaymentStatus.completed and old_status != PaymentStatus.completed:
try:
from ..models.system_settings import SystemSettings
-
- # Get client URL from settings
- 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"))
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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')
+ 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)
- # Refresh booking relationship
payment = db.query(Payment).filter(Payment.id == id).first()
if payment.booking and payment.booking.user:
- # Get client URL from settings
- 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"))
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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')
+ 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 = payment_confirmation_email_template(
- booking_number=payment.booking.booking_number,
- guest_name=payment.booking.user.full_name,
- amount=float(payment.amount),
- payment_method=payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else str(payment.payment_method),
- transaction_id=payment.transaction_id,
- client_url=client_url,
- currency_symbol=currency_symbol
- )
- await send_email(
- to=payment.booking.user.email,
- subject=f"Payment Confirmed - {payment.booking.booking_number}",
- html=email_html
- )
-
- # If this is a deposit payment, update booking deposit_paid status
+ email_html = payment_confirmation_email_template(booking_number=payment.booking.booking_number, guest_name=payment.booking.user.full_name, amount=float(payment.amount), payment_method=payment.payment_method.value if isinstance(payment.payment_method, PaymentMethod) else str(payment.payment_method), transaction_id=payment.transaction_id, client_url=client_url, currency_symbol=currency_symbol)
+ await send_email(to=payment.booking.user.email, subject=f'Payment Confirmed - {payment.booking.booking_number}', html=email_html)
if payment.payment_type == PaymentType.deposit and payment.booking:
payment.booking.deposit_paid = True
- # Restore cancelled bookings or confirm pending bookings when deposit is paid
if payment.booking.status in [BookingStatus.pending, BookingStatus.cancelled]:
payment.booking.status = BookingStatus.confirmed
db.commit()
- # If this is a full payment, also restore cancelled bookings
elif payment.payment_type == PaymentType.full and payment.booking:
- # Calculate total paid from all completed payments
- total_paid = sum(
- float(p.amount) for p in payment.booking.payments
- if p.payment_status == PaymentStatus.completed
- )
- # Confirm booking if fully paid, and restore cancelled bookings
+ total_paid = sum((float(p.amount) for p in payment.booking.payments if p.payment_status == PaymentStatus.completed))
if total_paid >= float(payment.booking.total_price):
if payment.booking.status in [BookingStatus.pending, BookingStatus.cancelled]:
payment.booking.status = BookingStatus.confirmed
db.commit()
except Exception as e:
- print(f"Failed to send payment confirmation email: {e}")
-
- return {
- "status": "success",
- "message": "Payment status updated successfully",
- "data": {"payment": payment}
- }
+ print(f'Failed to send payment confirmation email: {e}')
+ return {'status': 'success', 'message': 'Payment status updated successfully', 'data': {'payment': payment}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/stripe/create-intent")
-async def create_stripe_payment_intent(
- intent_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create a Stripe payment intent"""
+@router.post('/stripe/create-intent')
+async def create_stripe_payment_intent(intent_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Check if Stripe is configured (from database or environment)
from ..services.stripe_service import get_stripe_secret_key
secret_key = get_stripe_secret_key(db)
if not secret_key:
secret_key = settings.STRIPE_SECRET_KEY
-
if not secret_key:
- raise HTTPException(
- status_code=500,
- detail="Stripe is not configured. Please configure Stripe settings in Admin Panel or set STRIPE_SECRET_KEY environment variable."
- )
-
- booking_id = intent_data.get("booking_id")
- amount = float(intent_data.get("amount", 0))
- currency = intent_data.get("currency", "usd")
-
- # Log the incoming amount for debugging
+ raise HTTPException(status_code=500, detail='Stripe is not configured. Please configure Stripe settings in Admin Panel or set STRIPE_SECRET_KEY environment variable.')
+ booking_id = intent_data.get('booking_id')
+ amount = float(intent_data.get('amount', 0))
+ currency = intent_data.get('currency', 'usd')
import logging
logger = logging.getLogger(__name__)
- logger.info(f"Creating Stripe payment intent - Booking ID: {booking_id}, Amount: ${amount:,.2f}, Currency: {currency}")
-
+ logger.info(f'Creating Stripe payment intent - Booking ID: {booking_id}, Amount: ${amount:,.2f}, Currency: {currency}')
if not booking_id or amount <= 0:
- raise HTTPException(
- status_code=400,
- detail="booking_id and amount are required"
- )
-
- # Validate amount is reasonable (Stripe max is $999,999.99)
+ raise HTTPException(status_code=400, detail='booking_id and amount are required')
if amount > 999999.99:
logger.error(f"Amount ${amount:,.2f} exceeds Stripe's maximum of $999,999.99")
- raise HTTPException(
- status_code=400,
- detail=f"Amount ${amount:,.2f} exceeds Stripe's maximum of $999,999.99. Please contact support for large payments."
- )
-
- # Verify booking exists and user has access
+ raise HTTPException(status_code=400, detail=f"Amount ${amount:,.2f} exceeds Stripe's maximum of $999,999.99. Please contact support for large payments.")
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
+ raise HTTPException(status_code=404, detail='Booking not found')
if current_user.role_id != 1 and booking.user_id != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- # For deposit payments, verify the amount matches the deposit payment record
- # This ensures users are only charged the deposit (20%) and not the full amount
- if booking.requires_deposit and not booking.deposit_paid:
- deposit_payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.payment_type == PaymentType.deposit,
- Payment.payment_status == PaymentStatus.pending
- ).order_by(Payment.created_at.desc()).first()
-
+ raise HTTPException(status_code=403, detail='Forbidden')
+ if booking.requires_deposit and (not booking.deposit_paid):
+ deposit_payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.payment_type == PaymentType.deposit, Payment.payment_status == PaymentStatus.pending).order_by(Payment.created_at.desc()).first()
if deposit_payment:
expected_deposit_amount = float(deposit_payment.amount)
- # Allow small floating point differences (0.01)
if abs(amount - expected_deposit_amount) > 0.01:
- logger.warning(
- f"Amount mismatch for deposit payment: "
- f"Requested ${amount:,.2f}, Expected deposit ${expected_deposit_amount:,.2f}, "
- f"Booking total ${float(booking.total_price):,.2f}"
- )
- raise HTTPException(
- status_code=400,
- detail=f"For pay-on-arrival bookings, only the deposit amount (${expected_deposit_amount:,.2f}) should be charged, not the full booking amount (${float(booking.total_price):,.2f})."
- )
-
- # Create payment intent
- intent = StripeService.create_payment_intent(
- amount=amount,
- currency=currency,
- metadata={
- "booking_id": str(booking_id),
- "booking_number": booking.booking_number,
- "user_id": str(current_user.id),
- },
- db=db
- )
-
- # Get publishable key from database or environment
+ logger.warning(f'Amount mismatch for deposit payment: Requested ${amount:,.2f}, Expected deposit ${expected_deposit_amount:,.2f}, Booking total ${float(booking.total_price):,.2f}')
+ raise HTTPException(status_code=400, detail=f'For pay-on-arrival bookings, only the deposit amount (${expected_deposit_amount:,.2f}) should be charged, not the full booking amount (${float(booking.total_price):,.2f}).')
+ intent = StripeService.create_payment_intent(amount=amount, currency=currency, metadata={'booking_id': str(booking_id), 'booking_number': booking.booking_number, 'user_id': str(current_user.id)}, db=db)
from ..services.stripe_service import get_stripe_publishable_key
publishable_key = get_stripe_publishable_key(db)
if not publishable_key:
publishable_key = settings.STRIPE_PUBLISHABLE_KEY
-
if not publishable_key:
import logging
logger = logging.getLogger(__name__)
- logger.warning("Stripe publishable key is not configured")
- raise HTTPException(
- status_code=500,
- detail="Stripe publishable key is not configured. Please configure it in Admin Panel (Settings > Stripe Settings) or set STRIPE_PUBLISHABLE_KEY environment variable."
- )
-
- if not intent.get("client_secret"):
+ logger.warning('Stripe publishable key is not configured')
+ raise HTTPException(status_code=500, detail='Stripe publishable key is not configured. Please configure it in Admin Panel (Settings > Stripe Settings) or set STRIPE_PUBLISHABLE_KEY environment variable.')
+ if not intent.get('client_secret'):
import logging
logger = logging.getLogger(__name__)
- logger.error("Payment intent created but client_secret is missing")
- raise HTTPException(
- status_code=500,
- detail="Failed to create payment intent. Client secret is missing."
- )
-
- return {
- "status": "success",
- "message": "Payment intent created successfully",
- "data": {
- "client_secret": intent["client_secret"],
- "payment_intent_id": intent["id"],
- "publishable_key": publishable_key,
- }
- }
+ logger.error('Payment intent created but client_secret is missing')
+ raise HTTPException(status_code=500, detail='Failed to create payment intent. Client secret is missing.')
+ return {'status': 'success', 'message': 'Payment intent created successfully', 'data': {'client_secret': intent['client_secret'], 'payment_intent_id': intent['id'], 'publishable_key': publishable_key}}
except HTTPException:
raise
except ValueError as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Payment intent creation error: {str(e)}")
+ logger.error(f'Payment intent creation error: {str(e)}')
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Unexpected error creating payment intent: {str(e)}", exc_info=True)
+ logger.error(f'Unexpected error creating payment intent: {str(e)}', exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/stripe/confirm")
-async def confirm_stripe_payment(
- payment_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Confirm a Stripe payment"""
+@router.post('/stripe/confirm')
+async def confirm_stripe_payment(payment_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- payment_intent_id = payment_data.get("payment_intent_id")
- booking_id = payment_data.get("booking_id")
-
+ payment_intent_id = payment_data.get('payment_intent_id')
+ booking_id = payment_data.get('booking_id')
if not payment_intent_id:
- raise HTTPException(
- status_code=400,
- detail="payment_intent_id is required"
- )
-
- # Confirm payment (this commits the transaction internally)
- payment = await StripeService.confirm_payment(
- payment_intent_id=payment_intent_id,
- db=db,
- booking_id=booking_id
- )
-
- # Ensure the transaction is committed before proceeding
- # The service method already commits, but we ensure it here too
+ raise HTTPException(status_code=400, detail='payment_intent_id is required')
+ payment = await StripeService.confirm_payment(payment_intent_id=payment_intent_id, db=db, booking_id=booking_id)
try:
db.commit()
except Exception:
- # If already committed, this will raise an error, which we can ignore
pass
-
- # Get fresh booking from database to get updated status (after commit)
- booking = db.query(Booking).filter(Booking.id == payment["booking_id"]).first()
+ booking = db.query(Booking).filter(Booking.id == payment['booking_id']).first()
if booking:
db.refresh(booking)
-
- # Send payment confirmation email (non-blocking, after commit)
- # This won't affect the transaction since it's already committed
if booking and booking.user:
try:
from ..models.system_settings import SystemSettings
-
- # Get client URL from settings
- 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"))
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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')
+ 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 = payment_confirmation_email_template(
- booking_number=booking.booking_number,
- guest_name=booking.user.full_name,
- amount=payment["amount"],
- payment_method="stripe",
- transaction_id=payment["transaction_id"],
- payment_type=payment.get("payment_type"),
- total_price=float(booking.total_price),
- client_url=client_url,
- currency_symbol=currency_symbol
- )
- await send_email(
- to=booking.user.email,
- subject=f"Payment Confirmed - {booking.booking_number}",
- html=email_html
- )
+ email_html = payment_confirmation_email_template(booking_number=booking.booking_number, guest_name=booking.user.full_name, amount=payment['amount'], payment_method='stripe', transaction_id=payment['transaction_id'], payment_type=payment.get('payment_type'), total_price=float(booking.total_price), client_url=client_url, currency_symbol=currency_symbol)
+ await send_email(to=booking.user.email, subject=f'Payment Confirmed - {booking.booking_number}', html=email_html)
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.warning(f"Failed to send payment confirmation email: {e}")
-
- return {
- "status": "success",
- "message": "Payment confirmed successfully",
- "data": {
- "payment": payment,
- "booking": {
- "id": booking.id if booking else None,
- "booking_number": booking.booking_number if booking else None,
- "status": booking.status.value if booking else None,
- }
- }
- }
+ logger.warning(f'Failed to send payment confirmation email: {e}')
+ return {'status': 'success', 'message': 'Payment confirmed successfully', 'data': {'payment': payment, 'booking': {'id': booking.id if booking else None, 'booking_number': booking.booking_number if booking else None, 'status': booking.status.value if booking else None}}}
except HTTPException:
db.rollback()
raise
except ValueError as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Payment confirmation error: {str(e)}")
+ logger.error(f'Payment confirmation error: {str(e)}')
db.rollback()
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Unexpected error confirming payment: {str(e)}", exc_info=True)
+ logger.error(f'Unexpected error confirming payment: {str(e)}', exc_info=True)
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/stripe/webhook")
-async def stripe_webhook(
- request: Request,
- db: Session = Depends(get_db)
-):
- """Handle Stripe webhook events"""
+@router.post('/stripe/webhook')
+async def stripe_webhook(request: Request, db: Session=Depends(get_db)):
try:
- # Check if webhook secret is configured (from database or environment)
from ..services.stripe_service import get_stripe_webhook_secret
webhook_secret = get_stripe_webhook_secret(db)
if not webhook_secret:
webhook_secret = settings.STRIPE_WEBHOOK_SECRET
-
if not webhook_secret:
- raise HTTPException(
- status_code=503,
- detail={
- "status": "error",
- "message": "Stripe webhook secret is not configured. Please configure it in Admin Panel (Settings > Stripe Settings) or set STRIPE_WEBHOOK_SECRET environment variable."
- }
- )
-
+ raise HTTPException(status_code=503, detail={'status': 'error', 'message': 'Stripe webhook secret is not configured. Please configure it in Admin Panel (Settings > Stripe Settings) or set STRIPE_WEBHOOK_SECRET environment variable.'})
payload = await request.body()
- signature = request.headers.get("stripe-signature")
-
+ signature = request.headers.get('stripe-signature')
if not signature:
- raise HTTPException(
- status_code=400,
- detail="Missing stripe-signature header"
- )
-
- result = await StripeService.handle_webhook(
- payload=payload,
- signature=signature,
- db=db
- )
-
- return {
- "status": "success",
- "data": result
- }
+ raise HTTPException(status_code=400, detail='Missing stripe-signature header')
+ result = await StripeService.handle_webhook(payload=payload, signature=signature, db=db)
+ return {'status': 'success', 'data': result}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/paypal/create-order")
-async def create_paypal_order(
- order_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create a PayPal order"""
+@router.post('/paypal/create-order')
+async def create_paypal_order(order_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Check if PayPal is configured
from ..services.paypal_service import get_paypal_client_id, get_paypal_client_secret
client_id = get_paypal_client_id(db)
if not client_id:
client_id = settings.PAYPAL_CLIENT_ID
-
client_secret = get_paypal_client_secret(db)
if not client_secret:
client_secret = settings.PAYPAL_CLIENT_SECRET
-
if not client_id or not client_secret:
- raise HTTPException(
- status_code=500,
- detail="PayPal is not configured. Please configure PayPal settings in Admin Panel or set PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET environment variables."
- )
-
- booking_id = order_data.get("booking_id")
- amount = float(order_data.get("amount", 0))
- currency = order_data.get("currency", "USD")
-
+ raise HTTPException(status_code=500, detail='PayPal is not configured. Please configure PayPal settings in Admin Panel or set PAYPAL_CLIENT_ID and PAYPAL_CLIENT_SECRET environment variables.')
+ booking_id = order_data.get('booking_id')
+ amount = float(order_data.get('amount', 0))
+ currency = order_data.get('currency', 'USD')
if not booking_id or amount <= 0:
- raise HTTPException(
- status_code=400,
- detail="booking_id and amount are required"
- )
-
- # Validate amount
+ raise HTTPException(status_code=400, detail='booking_id and amount are required')
if amount > 100000:
- raise HTTPException(
- status_code=400,
- detail=f"Amount ${amount:,.2f} exceeds PayPal's maximum of $100,000. Please contact support for large payments."
- )
-
- # Verify booking exists and user has access
+ raise HTTPException(status_code=400, detail=f"Amount ${amount:,.2f} exceeds PayPal's maximum of $100,000. Please contact support for large payments.")
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
+ raise HTTPException(status_code=404, detail='Booking not found')
if current_user.role_id != 1 and booking.user_id != current_user.id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
- # For deposit payments, verify the amount matches the deposit payment record
- # This ensures users are only charged the deposit (20%) and not the full amount
- if booking.requires_deposit and not booking.deposit_paid:
- deposit_payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.payment_type == PaymentType.deposit,
- Payment.payment_status == PaymentStatus.pending
- ).order_by(Payment.created_at.desc()).first()
-
+ raise HTTPException(status_code=403, detail='Forbidden')
+ if booking.requires_deposit and (not booking.deposit_paid):
+ deposit_payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.payment_type == PaymentType.deposit, Payment.payment_status == PaymentStatus.pending).order_by(Payment.created_at.desc()).first()
if deposit_payment:
expected_deposit_amount = float(deposit_payment.amount)
- # Allow small floating point differences (0.01)
if abs(amount - expected_deposit_amount) > 0.01:
import logging
logger = logging.getLogger(__name__)
- logger.warning(
- f"Amount mismatch for deposit payment: "
- f"Requested ${amount:,.2f}, Expected deposit ${expected_deposit_amount:,.2f}, "
- f"Booking total ${float(booking.total_price):,.2f}"
- )
- raise HTTPException(
- status_code=400,
- detail=f"For pay-on-arrival bookings, only the deposit amount (${expected_deposit_amount:,.2f}) should be charged, not the full booking amount (${float(booking.total_price):,.2f})."
- )
-
- # Get return URLs from request or use defaults
- client_url = settings.CLIENT_URL or os.getenv("CLIENT_URL", "http://localhost:5173")
- return_url = order_data.get("return_url", f"{client_url}/payment/paypal/return")
- cancel_url = order_data.get("cancel_url", f"{client_url}/payment/paypal/cancel")
-
- # Create PayPal order
- order = PayPalService.create_order(
- amount=amount,
- currency=currency,
- metadata={
- "booking_id": str(booking_id),
- "booking_number": booking.booking_number,
- "user_id": str(current_user.id),
- "description": f"Hotel Booking Payment - {booking.booking_number}",
- "return_url": return_url,
- "cancel_url": cancel_url,
- },
- db=db
- )
-
- if not order.get("approval_url"):
- raise HTTPException(
- status_code=500,
- detail="Failed to create PayPal order. Approval URL is missing."
- )
-
- return {
- "status": "success",
- "message": "PayPal order created successfully",
- "data": {
- "order_id": order["id"],
- "approval_url": order["approval_url"],
- "status": order["status"],
- }
- }
+ logger.warning(f'Amount mismatch for deposit payment: Requested ${amount:,.2f}, Expected deposit ${expected_deposit_amount:,.2f}, Booking total ${float(booking.total_price):,.2f}')
+ raise HTTPException(status_code=400, detail=f'For pay-on-arrival bookings, only the deposit amount (${expected_deposit_amount:,.2f}) should be charged, not the full booking amount (${float(booking.total_price):,.2f}).')
+ client_url = settings.CLIENT_URL or os.getenv('CLIENT_URL', 'http://localhost:5173')
+ return_url = order_data.get('return_url', f'{client_url}/payment/paypal/return')
+ cancel_url = order_data.get('cancel_url', f'{client_url}/payment/paypal/cancel')
+ order = PayPalService.create_order(amount=amount, currency=currency, metadata={'booking_id': str(booking_id), 'booking_number': booking.booking_number, 'user_id': str(current_user.id), 'description': f'Hotel Booking Payment - {booking.booking_number}', 'return_url': return_url, 'cancel_url': cancel_url}, db=db)
+ if not order.get('approval_url'):
+ raise HTTPException(status_code=500, detail='Failed to create PayPal order. Approval URL is missing.')
+ return {'status': 'success', 'message': 'PayPal order created successfully', 'data': {'order_id': order['id'], 'approval_url': order['approval_url'], 'status': order['status']}}
except HTTPException:
raise
except ValueError as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"PayPal order creation error: {str(e)}")
+ logger.error(f'PayPal order creation error: {str(e)}')
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Unexpected error creating PayPal order: {str(e)}", exc_info=True)
+ logger.error(f'Unexpected error creating PayPal order: {str(e)}', exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/paypal/cancel")
-async def cancel_paypal_payment(
- payment_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Mark PayPal payment as failed and cancel booking when user cancels on PayPal"""
+@router.post('/paypal/cancel')
+async def cancel_paypal_payment(payment_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- booking_id = payment_data.get("booking_id")
-
+ booking_id = payment_data.get('booking_id')
if not booking_id:
- raise HTTPException(
- status_code=400,
- detail="booking_id is required"
- )
-
- # Find pending PayPal payment for this booking
- payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.payment_method == PaymentMethod.paypal,
- Payment.payment_status == PaymentStatus.pending
- ).order_by(Payment.created_at.desc()).first()
-
- # Also check for deposit payments
+ raise HTTPException(status_code=400, detail='booking_id is required')
+ payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.payment_method == PaymentMethod.paypal, Payment.payment_status == PaymentStatus.pending).order_by(Payment.created_at.desc()).first()
if not payment:
- payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.payment_type == PaymentType.deposit,
- Payment.payment_status == PaymentStatus.pending
- ).order_by(Payment.created_at.desc()).first()
-
+ payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.payment_type == PaymentType.deposit, Payment.payment_status == PaymentStatus.pending).order_by(Payment.created_at.desc()).first()
if payment:
payment.payment_status = PaymentStatus.failed
db.commit()
db.refresh(payment)
-
- # Auto-cancel booking
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if booking and booking.status != BookingStatus.cancelled:
- await cancel_booking_on_payment_failure(
- booking,
- db,
- reason="PayPal payment canceled by user"
- )
-
- return {
- "status": "success",
- "message": "Payment canceled and booking cancelled"
- }
+ await cancel_booking_on_payment_failure(booking, db, reason='PayPal payment canceled by user')
+ return {'status': 'success', 'message': 'Payment canceled and booking cancelled'}
except HTTPException:
db.rollback()
raise
@@ -960,108 +429,49 @@ async def cancel_paypal_payment(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/paypal/capture")
-async def capture_paypal_payment(
- payment_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Capture a PayPal payment"""
+@router.post('/paypal/capture')
+async def capture_paypal_payment(payment_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- order_id = payment_data.get("order_id")
- booking_id = payment_data.get("booking_id")
-
+ order_id = payment_data.get('order_id')
+ booking_id = payment_data.get('booking_id')
if not order_id:
- raise HTTPException(
- status_code=400,
- detail="order_id is required"
- )
-
- # Confirm payment (this commits the transaction internally)
- payment = await PayPalService.confirm_payment(
- order_id=order_id,
- db=db,
- booking_id=booking_id
- )
-
- # Ensure the transaction is committed
+ raise HTTPException(status_code=400, detail='order_id is required')
+ payment = await PayPalService.confirm_payment(order_id=order_id, db=db, booking_id=booking_id)
try:
db.commit()
except Exception:
pass
-
- # Get fresh booking from database
- booking = db.query(Booking).filter(Booking.id == payment["booking_id"]).first()
+ booking = db.query(Booking).filter(Booking.id == payment['booking_id']).first()
if booking:
db.refresh(booking)
-
- # Send payment confirmation email (non-blocking)
if booking and booking.user:
try:
from ..models.system_settings import SystemSettings
-
- # Get client URL from settings
- 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"))
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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')
+ 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 = payment_confirmation_email_template(
- booking_number=booking.booking_number,
- guest_name=booking.user.full_name,
- amount=payment["amount"],
- payment_method="paypal",
- transaction_id=payment["transaction_id"],
- payment_type=payment.get("payment_type"),
- total_price=float(booking.total_price),
- client_url=client_url,
- currency_symbol=currency_symbol
- )
- await send_email(
- to=booking.user.email,
- subject=f"Payment Confirmed - {booking.booking_number}",
- html=email_html
- )
+ email_html = payment_confirmation_email_template(booking_number=booking.booking_number, guest_name=booking.user.full_name, amount=payment['amount'], payment_method='paypal', transaction_id=payment['transaction_id'], payment_type=payment.get('payment_type'), total_price=float(booking.total_price), client_url=client_url, currency_symbol=currency_symbol)
+ await send_email(to=booking.user.email, subject=f'Payment Confirmed - {booking.booking_number}', html=email_html)
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.warning(f"Failed to send payment confirmation email: {e}")
-
- return {
- "status": "success",
- "message": "Payment confirmed successfully",
- "data": {
- "payment": payment,
- "booking": {
- "id": booking.id if booking else None,
- "booking_number": booking.booking_number if booking else None,
- "status": booking.status.value if booking else None,
- }
- }
- }
+ logger.warning(f'Failed to send payment confirmation email: {e}')
+ return {'status': 'success', 'message': 'Payment confirmed successfully', 'data': {'payment': payment, 'booking': {'id': booking.id if booking else None, 'booking_number': booking.booking_number if booking else None, 'status': booking.status.value if booking else None}}}
except HTTPException:
db.rollback()
raise
except ValueError as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"PayPal payment confirmation error: {str(e)}")
+ logger.error(f'PayPal payment confirmation error: {str(e)}')
db.rollback()
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
import logging
logger = logging.getLogger(__name__)
- logger.error(f"Unexpected error confirming PayPal payment: {str(e)}", exc_info=True)
+ logger.error(f'Unexpected error confirming PayPal payment: {str(e)}', exc_info=True)
db.rollback()
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/privacy_routes.py b/Backend/src/routes/privacy_routes.py
index 57f5233c..96f2db44 100644
--- a/Backend/src/routes/privacy_routes.py
+++ b/Backend/src/routes/privacy_routes.py
@@ -1,111 +1,39 @@
from fastapi import APIRouter, Depends, Request, Response, status
from sqlalchemy.orm import Session
-
from ..config.database import get_db
from ..config.logging_config import get_logger
from ..config.settings import settings
from ..middleware.cookie_consent import COOKIE_CONSENT_COOKIE_NAME, _parse_consent_cookie
from ..schemas.admin_privacy import PublicPrivacyConfigResponse
-from ..schemas.privacy import (
- CookieCategoryPreferences,
- CookieConsent,
- CookieConsentResponse,
- UpdateCookieConsentRequest,
-)
+from ..schemas.privacy import CookieCategoryPreferences, CookieConsent, CookieConsentResponse, UpdateCookieConsentRequest
from ..services.privacy_admin_service import privacy_admin_service
-
-
logger = get_logger(__name__)
+router = APIRouter(prefix='/privacy', tags=['privacy'])
-router = APIRouter(prefix="/privacy", tags=["privacy"])
-
-
-@router.get(
- "/cookie-consent",
- response_model=CookieConsentResponse,
- status_code=status.HTTP_200_OK,
-)
+@router.get('/cookie-consent', response_model=CookieConsentResponse, status_code=status.HTTP_200_OK)
async def get_cookie_consent(request: Request) -> CookieConsentResponse:
- """
- Return the current cookie consent preferences.
- Reads from the cookie (if present) or returns default (necessary only).
- """
raw_cookie = request.cookies.get(COOKIE_CONSENT_COOKIE_NAME)
consent = _parse_consent_cookie(raw_cookie)
-
- # Ensure necessary is always true
consent.categories.necessary = True
-
return CookieConsentResponse(data=consent)
-
-@router.post(
- "/cookie-consent",
- response_model=CookieConsentResponse,
- status_code=status.HTTP_200_OK,
-)
-async def update_cookie_consent(
- request: UpdateCookieConsentRequest, response: Response
-) -> CookieConsentResponse:
- """
- Update cookie consent preferences.
-
- The 'necessary' category is controlled by the server and always true.
- """
- # Build categories from existing cookie (if any) so partial updates work
- existing_raw = response.headers.get("cookie") # usually empty here
- # We can't reliably read cookies from the response; rely on defaults.
- # For the purposes of this API, we always start from defaults and then
- # override with the request payload.
+@router.post('/cookie-consent', response_model=CookieConsentResponse, status_code=status.HTTP_200_OK)
+async def update_cookie_consent(request: UpdateCookieConsentRequest, response: Response) -> CookieConsentResponse:
+ existing_raw = response.headers.get('cookie')
categories = CookieCategoryPreferences()
-
if request.analytics is not None:
categories.analytics = request.analytics
if request.marketing is not None:
categories.marketing = request.marketing
if request.preferences is not None:
categories.preferences = request.preferences
-
- # 'necessary' enforced server-side
categories.necessary = True
-
consent = CookieConsent(categories=categories, has_decided=True)
-
- # Persist consent as a secure, HttpOnly cookie
- response.set_cookie(
- key=COOKIE_CONSENT_COOKIE_NAME,
- value=consent.model_dump_json(),
- httponly=True,
- secure=settings.is_production,
- samesite="lax",
- max_age=365 * 24 * 60 * 60, # 1 year
- path="/",
- )
-
- logger.info(
- "Cookie consent updated: analytics=%s, marketing=%s, preferences=%s",
- consent.categories.analytics,
- consent.categories.marketing,
- consent.categories.preferences,
- )
-
+ response.set_cookie(key=COOKIE_CONSENT_COOKIE_NAME, value=consent.model_dump_json(), httponly=True, secure=settings.is_production, samesite='lax', max_age=365 * 24 * 60 * 60, path='/')
+ logger.info('Cookie consent updated: analytics=%s, marketing=%s, preferences=%s', consent.categories.analytics, consent.categories.marketing, consent.categories.preferences)
return CookieConsentResponse(data=consent)
-
-@router.get(
- "/config",
- response_model=PublicPrivacyConfigResponse,
- status_code=status.HTTP_200_OK,
-)
-async def get_public_privacy_config(
- db: Session = Depends(get_db),
-) -> PublicPrivacyConfigResponse:
- """
- Public privacy configuration for the frontend:
- - Global policy flags
- - Public integration IDs (e.g. GA measurement ID)
- """
+@router.get('/config', response_model=PublicPrivacyConfigResponse, status_code=status.HTTP_200_OK)
+async def get_public_privacy_config(db: Session=Depends(get_db)) -> PublicPrivacyConfigResponse:
config = privacy_admin_service.get_public_privacy_config(db)
- return PublicPrivacyConfigResponse(data=config)
-
-
+ return PublicPrivacyConfigResponse(data=config)
\ No newline at end of file
diff --git a/Backend/src/routes/promotion_routes.py b/Backend/src/routes/promotion_routes.py
index 6a525dbf..a921e165 100644
--- a/Backend/src/routes/promotion_routes.py
+++ b/Backend/src/routes/promotion_routes.py
@@ -3,346 +3,158 @@ from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional
from datetime import datetime
-
from ..config.database import get_db
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
from ..models.promotion import Promotion, DiscountType
+router = APIRouter(prefix='/promotions', tags=['promotions'])
-router = APIRouter(prefix="/promotions", tags=["promotions"])
-
-
-@router.get("/")
-async def get_promotions(
- search: Optional[str] = Query(None),
- status_filter: Optional[str] = Query(None, alias="status"),
- type: Optional[str] = Query(None),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- db: Session = Depends(get_db)
-):
- """Get all promotions with filters"""
+@router.get('/')
+async def get_promotions(search: Optional[str]=Query(None), status_filter: Optional[str]=Query(None, alias='status'), type: Optional[str]=Query(None), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), db: Session=Depends(get_db)):
try:
query = db.query(Promotion)
-
- # Filter by search (code or name)
if search:
- query = query.filter(
- or_(
- Promotion.code.like(f"%{search}%"),
- Promotion.name.like(f"%{search}%")
- )
- )
-
- # Filter by status (is_active)
+ query = query.filter(or_(Promotion.code.like(f'%{search}%'), Promotion.name.like(f'%{search}%')))
if status_filter:
- is_active = status_filter == "active"
+ is_active = status_filter == 'active'
query = query.filter(Promotion.is_active == is_active)
-
- # Filter by discount type
if type:
try:
query = query.filter(Promotion.discount_type == DiscountType(type))
except ValueError:
pass
-
total = query.count()
offset = (page - 1) * limit
promotions = query.order_by(Promotion.created_at.desc()).offset(offset).limit(limit).all()
-
result = []
for promo in promotions:
- promo_dict = {
- "id": promo.id,
- "code": promo.code,
- "name": promo.name,
- "description": promo.description,
- "discount_type": promo.discount_type.value if isinstance(promo.discount_type, DiscountType) else promo.discount_type,
- "discount_value": float(promo.discount_value) if promo.discount_value else 0.0,
- "min_booking_amount": float(promo.min_booking_amount) if promo.min_booking_amount else None,
- "max_discount_amount": float(promo.max_discount_amount) if promo.max_discount_amount else None,
- "start_date": promo.start_date.isoformat() if promo.start_date else None,
- "end_date": promo.end_date.isoformat() if promo.end_date else None,
- "usage_limit": promo.usage_limit,
- "used_count": promo.used_count,
- "is_active": promo.is_active,
- "created_at": promo.created_at.isoformat() if promo.created_at else None,
- }
+ promo_dict = {'id': promo.id, 'code': promo.code, 'name': promo.name, 'description': promo.description, 'discount_type': promo.discount_type.value if isinstance(promo.discount_type, DiscountType) else promo.discount_type, 'discount_value': float(promo.discount_value) if promo.discount_value else 0.0, 'min_booking_amount': float(promo.min_booking_amount) if promo.min_booking_amount else None, 'max_discount_amount': float(promo.max_discount_amount) if promo.max_discount_amount else None, 'start_date': promo.start_date.isoformat() if promo.start_date else None, 'end_date': promo.end_date.isoformat() if promo.end_date else None, 'usage_limit': promo.usage_limit, 'used_count': promo.used_count, 'is_active': promo.is_active, 'created_at': promo.created_at.isoformat() if promo.created_at else None}
result.append(promo_dict)
-
- return {
- "status": "success",
- "data": {
- "promotions": result,
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'promotions': result, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{code}")
-async def get_promotion_by_code(code: str, db: Session = Depends(get_db)):
- """Get promotion by code"""
+@router.get('/{code}')
+async def get_promotion_by_code(code: str, db: Session=Depends(get_db)):
try:
promotion = db.query(Promotion).filter(Promotion.code == code).first()
if not promotion:
- raise HTTPException(status_code=404, detail="Promotion not found")
-
- promo_dict = {
- "id": promotion.id,
- "code": promotion.code,
- "name": promotion.name,
- "description": promotion.description,
- "discount_type": promotion.discount_type.value if isinstance(promotion.discount_type, DiscountType) else promotion.discount_type,
- "discount_value": float(promotion.discount_value) if promotion.discount_value else 0.0,
- "min_booking_amount": float(promotion.min_booking_amount) if promotion.min_booking_amount else None,
- "max_discount_amount": float(promotion.max_discount_amount) if promotion.max_discount_amount else None,
- "start_date": promotion.start_date.isoformat() if promotion.start_date else None,
- "end_date": promotion.end_date.isoformat() if promotion.end_date else None,
- "usage_limit": promotion.usage_limit,
- "used_count": promotion.used_count,
- "is_active": promotion.is_active,
- }
-
- return {
- "status": "success",
- "data": {"promotion": promo_dict}
- }
+ raise HTTPException(status_code=404, detail='Promotion not found')
+ promo_dict = {'id': promotion.id, 'code': promotion.code, 'name': promotion.name, 'description': promotion.description, 'discount_type': promotion.discount_type.value if isinstance(promotion.discount_type, DiscountType) else promotion.discount_type, 'discount_value': float(promotion.discount_value) if promotion.discount_value else 0.0, 'min_booking_amount': float(promotion.min_booking_amount) if promotion.min_booking_amount else None, 'max_discount_amount': float(promotion.max_discount_amount) if promotion.max_discount_amount else None, 'start_date': promotion.start_date.isoformat() if promotion.start_date else None, 'end_date': promotion.end_date.isoformat() if promotion.end_date else None, 'usage_limit': promotion.usage_limit, 'used_count': promotion.used_count, 'is_active': promotion.is_active}
+ return {'status': 'success', 'data': {'promotion': promo_dict}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/validate")
-async def validate_promotion(
- validation_data: dict,
- db: Session = Depends(get_db)
-):
- """Validate and apply promotion"""
+@router.post('/validate')
+async def validate_promotion(validation_data: dict, db: Session=Depends(get_db)):
try:
- code = validation_data.get("code")
- # Accept both booking_value (from frontend) and booking_amount (for backward compatibility)
- booking_amount = float(validation_data.get("booking_value") or validation_data.get("booking_amount", 0))
-
+ code = validation_data.get('code')
+ booking_amount = float(validation_data.get('booking_value') or validation_data.get('booking_amount', 0))
promotion = db.query(Promotion).filter(Promotion.code == code).first()
if not promotion:
- raise HTTPException(status_code=404, detail="Promotion code not found")
-
- # Check if promotion is active
+ raise HTTPException(status_code=404, detail='Promotion code not found')
if not promotion.is_active:
- raise HTTPException(status_code=400, detail="Promotion is not active")
-
- # Check date validity
+ raise HTTPException(status_code=400, detail='Promotion is not active')
now = datetime.utcnow()
if promotion.start_date and now < promotion.start_date:
- raise HTTPException(status_code=400, detail="Promotion is not valid at this time")
+ raise HTTPException(status_code=400, detail='Promotion is not valid at this time')
if promotion.end_date and now > promotion.end_date:
- raise HTTPException(status_code=400, detail="Promotion is not valid at this time")
-
- # Check usage limit
+ raise HTTPException(status_code=400, detail='Promotion is not valid at this time')
if promotion.usage_limit and promotion.used_count >= promotion.usage_limit:
- raise HTTPException(status_code=400, detail="Promotion usage limit reached")
-
- # Check minimum booking amount
+ raise HTTPException(status_code=400, detail='Promotion usage limit reached')
if promotion.min_booking_amount and booking_amount < float(promotion.min_booking_amount):
- raise HTTPException(
- status_code=400,
- detail=f"Minimum booking amount is {promotion.min_booking_amount}"
- )
-
- # Calculate discount
+ raise HTTPException(status_code=400, detail=f'Minimum booking amount is {promotion.min_booking_amount}')
discount_amount = promotion.calculate_discount(booking_amount)
final_amount = booking_amount - discount_amount
-
- return {
- "success": True,
- "status": "success",
- "data": {
- "promotion": {
- "id": promotion.id,
- "code": promotion.code,
- "name": promotion.name,
- "description": promotion.description,
- "discount_type": promotion.discount_type.value if hasattr(promotion.discount_type, 'value') else str(promotion.discount_type),
- "discount_value": float(promotion.discount_value) if promotion.discount_value else 0,
- "min_booking_amount": float(promotion.min_booking_amount) if promotion.min_booking_amount else None,
- "max_discount_amount": float(promotion.max_discount_amount) if promotion.max_discount_amount else None,
- "start_date": promotion.start_date.isoformat() if promotion.start_date else None,
- "end_date": promotion.end_date.isoformat() if promotion.end_date else None,
- "usage_limit": promotion.usage_limit,
- "used_count": promotion.used_count,
- "status": "active" if promotion.is_active else "inactive",
- },
- "discount": discount_amount,
- "original_amount": booking_amount,
- "discount_amount": discount_amount,
- "final_amount": final_amount,
- },
- "message": "Promotion validated successfully"
- }
+ return {'success': True, 'status': 'success', 'data': {'promotion': {'id': promotion.id, 'code': promotion.code, 'name': promotion.name, 'description': promotion.description, 'discount_type': promotion.discount_type.value if hasattr(promotion.discount_type, 'value') else str(promotion.discount_type), 'discount_value': float(promotion.discount_value) if promotion.discount_value else 0, 'min_booking_amount': float(promotion.min_booking_amount) if promotion.min_booking_amount else None, 'max_discount_amount': float(promotion.max_discount_amount) if promotion.max_discount_amount else None, 'start_date': promotion.start_date.isoformat() if promotion.start_date else None, 'end_date': promotion.end_date.isoformat() if promotion.end_date else None, 'usage_limit': promotion.usage_limit, 'used_count': promotion.used_count, 'status': 'active' if promotion.is_active else 'inactive'}, 'discount': discount_amount, 'original_amount': booking_amount, 'discount_amount': discount_amount, 'final_amount': final_amount}, 'message': 'Promotion validated successfully'}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/", dependencies=[Depends(authorize_roles("admin"))])
-async def create_promotion(
- promotion_data: dict,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Create new promotion (Admin only)"""
+@router.post('/', dependencies=[Depends(authorize_roles('admin'))])
+async def create_promotion(promotion_data: dict, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
- code = promotion_data.get("code")
-
- # Check if code exists
+ code = promotion_data.get('code')
existing = db.query(Promotion).filter(Promotion.code == code).first()
if existing:
- raise HTTPException(status_code=400, detail="Promotion code already exists")
-
- discount_type = promotion_data.get("discount_type")
- discount_value = float(promotion_data.get("discount_value", 0))
-
- # Validate discount value
- if discount_type == "percentage" and discount_value > 100:
- raise HTTPException(
- status_code=400,
- detail="Percentage discount cannot exceed 100%"
- )
-
- promotion = Promotion(
- code=code,
- name=promotion_data.get("name"),
- description=promotion_data.get("description"),
- discount_type=DiscountType(discount_type),
- discount_value=discount_value,
- min_booking_amount=float(promotion_data["min_booking_amount"]) if promotion_data.get("min_booking_amount") else None,
- max_discount_amount=float(promotion_data["max_discount_amount"]) if promotion_data.get("max_discount_amount") else None,
- start_date=datetime.fromisoformat(promotion_data["start_date"].replace('Z', '+00:00')) if promotion_data.get("start_date") else None,
- end_date=datetime.fromisoformat(promotion_data["end_date"].replace('Z', '+00:00')) if promotion_data.get("end_date") else None,
- usage_limit=promotion_data.get("usage_limit"),
- used_count=0,
- is_active=promotion_data.get("status") == "active" if promotion_data.get("status") else True,
- )
-
+ raise HTTPException(status_code=400, detail='Promotion code already exists')
+ discount_type = promotion_data.get('discount_type')
+ discount_value = float(promotion_data.get('discount_value', 0))
+ if discount_type == 'percentage' and discount_value > 100:
+ raise HTTPException(status_code=400, detail='Percentage discount cannot exceed 100%')
+ promotion = Promotion(code=code, name=promotion_data.get('name'), description=promotion_data.get('description'), discount_type=DiscountType(discount_type), discount_value=discount_value, min_booking_amount=float(promotion_data['min_booking_amount']) if promotion_data.get('min_booking_amount') else None, max_discount_amount=float(promotion_data['max_discount_amount']) if promotion_data.get('max_discount_amount') else None, start_date=datetime.fromisoformat(promotion_data['start_date'].replace('Z', '+00:00')) if promotion_data.get('start_date') else None, end_date=datetime.fromisoformat(promotion_data['end_date'].replace('Z', '+00:00')) if promotion_data.get('end_date') else None, usage_limit=promotion_data.get('usage_limit'), used_count=0, is_active=promotion_data.get('status') == 'active' if promotion_data.get('status') else True)
db.add(promotion)
db.commit()
db.refresh(promotion)
-
- return {
- "status": "success",
- "message": "Promotion created successfully",
- "data": {"promotion": promotion}
- }
+ return {'status': 'success', 'message': 'Promotion created successfully', 'data': {'promotion': promotion}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def update_promotion(
- id: int,
- promotion_data: dict,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Update promotion (Admin only)"""
+@router.put('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def update_promotion(id: int, promotion_data: dict, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
promotion = db.query(Promotion).filter(Promotion.id == id).first()
if not promotion:
- raise HTTPException(status_code=404, detail="Promotion not found")
-
- # Check if new code exists (excluding current)
- code = promotion_data.get("code")
+ raise HTTPException(status_code=404, detail='Promotion not found')
+ code = promotion_data.get('code')
if code and code != promotion.code:
- existing = db.query(Promotion).filter(
- Promotion.code == code,
- Promotion.id != id
- ).first()
+ existing = db.query(Promotion).filter(Promotion.code == code, Promotion.id != id).first()
if existing:
- raise HTTPException(status_code=400, detail="Promotion code already exists")
-
- # Validate discount value
- discount_type = promotion_data.get("discount_type", promotion.discount_type.value if isinstance(promotion.discount_type, DiscountType) else promotion.discount_type)
- discount_value = promotion_data.get("discount_value")
+ raise HTTPException(status_code=400, detail='Promotion code already exists')
+ discount_type = promotion_data.get('discount_type', promotion.discount_type.value if isinstance(promotion.discount_type, DiscountType) else promotion.discount_type)
+ discount_value = promotion_data.get('discount_value')
if discount_value is not None:
discount_value = float(discount_value)
- if discount_type == "percentage" and discount_value > 100:
- raise HTTPException(
- status_code=400,
- detail="Percentage discount cannot exceed 100%"
- )
-
- # Update fields
- if "code" in promotion_data:
- promotion.code = promotion_data["code"]
- if "name" in promotion_data:
- promotion.name = promotion_data["name"]
- if "description" in promotion_data:
- promotion.description = promotion_data["description"]
- if "discount_type" in promotion_data:
- promotion.discount_type = DiscountType(promotion_data["discount_type"])
- if "discount_value" in promotion_data:
+ if discount_type == 'percentage' and discount_value > 100:
+ raise HTTPException(status_code=400, detail='Percentage discount cannot exceed 100%')
+ if 'code' in promotion_data:
+ promotion.code = promotion_data['code']
+ if 'name' in promotion_data:
+ promotion.name = promotion_data['name']
+ if 'description' in promotion_data:
+ promotion.description = promotion_data['description']
+ if 'discount_type' in promotion_data:
+ promotion.discount_type = DiscountType(promotion_data['discount_type'])
+ if 'discount_value' in promotion_data:
promotion.discount_value = discount_value
- if "min_booking_amount" in promotion_data:
- promotion.min_booking_amount = float(promotion_data["min_booking_amount"]) if promotion_data["min_booking_amount"] else None
- if "max_discount_amount" in promotion_data:
- promotion.max_discount_amount = float(promotion_data["max_discount_amount"]) if promotion_data["max_discount_amount"] else None
- if "start_date" in promotion_data:
- promotion.start_date = datetime.fromisoformat(promotion_data["start_date"].replace('Z', '+00:00')) if promotion_data["start_date"] else None
- if "end_date" in promotion_data:
- promotion.end_date = datetime.fromisoformat(promotion_data["end_date"].replace('Z', '+00:00')) if promotion_data["end_date"] else None
- if "usage_limit" in promotion_data:
- promotion.usage_limit = promotion_data["usage_limit"]
- if "status" in promotion_data:
- promotion.is_active = promotion_data["status"] == "active"
-
+ if 'min_booking_amount' in promotion_data:
+ promotion.min_booking_amount = float(promotion_data['min_booking_amount']) if promotion_data['min_booking_amount'] else None
+ if 'max_discount_amount' in promotion_data:
+ promotion.max_discount_amount = float(promotion_data['max_discount_amount']) if promotion_data['max_discount_amount'] else None
+ if 'start_date' in promotion_data:
+ promotion.start_date = datetime.fromisoformat(promotion_data['start_date'].replace('Z', '+00:00')) if promotion_data['start_date'] else None
+ if 'end_date' in promotion_data:
+ promotion.end_date = datetime.fromisoformat(promotion_data['end_date'].replace('Z', '+00:00')) if promotion_data['end_date'] else None
+ if 'usage_limit' in promotion_data:
+ promotion.usage_limit = promotion_data['usage_limit']
+ if 'status' in promotion_data:
+ promotion.is_active = promotion_data['status'] == 'active'
db.commit()
db.refresh(promotion)
-
- return {
- "status": "success",
- "message": "Promotion updated successfully",
- "data": {"promotion": promotion}
- }
+ return {'status': 'success', 'message': 'Promotion updated successfully', 'data': {'promotion': promotion}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def delete_promotion(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Delete promotion (Admin only)"""
+@router.delete('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def delete_promotion(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
promotion = db.query(Promotion).filter(Promotion.id == id).first()
if not promotion:
- raise HTTPException(status_code=404, detail="Promotion not found")
-
+ raise HTTPException(status_code=404, detail='Promotion not found')
db.delete(promotion)
db.commit()
-
- return {
- "status": "success",
- "message": "Promotion deleted successfully"
- }
+ return {'status': 'success', 'message': 'Promotion deleted successfully'}
except HTTPException:
raise
except Exception as e:
db.rollback()
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/report_routes.py b/Backend/src/routes/report_routes.py
index bfebd8b3..4f9feb49 100644
--- a/Backend/src/routes/report_routes.py
+++ b/Backend/src/routes/report_routes.py
@@ -3,7 +3,6 @@ from sqlalchemy.orm import Session
from sqlalchemy import func, and_
from typing import Optional
from datetime import datetime, timedelta
-
from ..config.database import get_db
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
@@ -12,55 +11,34 @@ from ..models.payment import Payment, PaymentStatus
from ..models.room import Room
from ..models.service_usage import ServiceUsage
from ..models.service import Service
+router = APIRouter(prefix='/reports', tags=['reports'])
-router = APIRouter(prefix="/reports", tags=["reports"])
-
-
-@router.get("")
-async def get_reports(
- from_date: Optional[str] = Query(None, alias="from"),
- to_date: Optional[str] = Query(None, alias="to"),
- type: Optional[str] = Query(None),
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Get comprehensive reports (Admin/Staff only)"""
+@router.get('')
+async def get_reports(from_date: Optional[str]=Query(None, alias='from'), to_date: Optional[str]=Query(None, alias='to'), type: Optional[str]=Query(None), current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
- # Parse dates if provided
start_date = None
end_date = None
if from_date:
try:
- start_date = datetime.strptime(from_date, "%Y-%m-%d")
+ start_date = datetime.strptime(from_date, '%Y-%m-%d')
except ValueError:
start_date = datetime.fromisoformat(from_date.replace('Z', '+00:00'))
if to_date:
try:
- end_date = datetime.strptime(to_date, "%Y-%m-%d")
- # Set to end of day
+ end_date = datetime.strptime(to_date, '%Y-%m-%d')
end_date = end_date.replace(hour=23, minute=59, second=59)
except ValueError:
end_date = datetime.fromisoformat(to_date.replace('Z', '+00:00'))
-
- # Base queries
booking_query = db.query(Booking)
payment_query = db.query(Payment).filter(Payment.payment_status == PaymentStatus.completed)
-
- # Apply date filters
if start_date:
booking_query = booking_query.filter(Booking.created_at >= start_date)
payment_query = payment_query.filter(Payment.payment_date >= start_date)
if end_date:
booking_query = booking_query.filter(Booking.created_at <= end_date)
payment_query = payment_query.filter(Payment.payment_date <= end_date)
-
- # Total bookings
total_bookings = booking_query.count()
-
- # Total revenue
total_revenue = payment_query.with_entities(func.sum(Payment.amount)).scalar() or 0.0
-
- # Total customers (unique users with bookings)
total_customers = db.query(func.count(func.distinct(Booking.user_id))).scalar() or 0
if start_date or end_date:
customer_query = db.query(func.count(func.distinct(Booking.user_id)))
@@ -69,415 +47,126 @@ async def get_reports(
if end_date:
customer_query = customer_query.filter(Booking.created_at <= end_date)
total_customers = customer_query.scalar() or 0
-
- # Available rooms
- available_rooms = db.query(Room).filter(Room.status == "available").count()
-
- # Occupied rooms (rooms with active bookings)
- occupied_rooms = db.query(func.count(func.distinct(Booking.room_id))).filter(
- Booking.status.in_([BookingStatus.confirmed, BookingStatus.checked_in])
- ).scalar() or 0
-
- # Revenue by date (daily breakdown)
+ available_rooms = db.query(Room).filter(Room.status == 'available').count()
+ occupied_rooms = db.query(func.count(func.distinct(Booking.room_id))).filter(Booking.status.in_([BookingStatus.confirmed, BookingStatus.checked_in])).scalar() or 0
revenue_by_date = []
if start_date and end_date:
- daily_revenue_query = db.query(
- func.date(Payment.payment_date).label('date'),
- func.sum(Payment.amount).label('revenue'),
- func.count(func.distinct(Payment.booking_id)).label('bookings')
- ).filter(Payment.payment_status == PaymentStatus.completed)
-
+ daily_revenue_query = db.query(func.date(Payment.payment_date).label('date'), func.sum(Payment.amount).label('revenue'), func.count(func.distinct(Payment.booking_id)).label('bookings')).filter(Payment.payment_status == PaymentStatus.completed)
if start_date:
daily_revenue_query = daily_revenue_query.filter(Payment.payment_date >= start_date)
if end_date:
daily_revenue_query = daily_revenue_query.filter(Payment.payment_date <= end_date)
-
- daily_revenue_query = daily_revenue_query.group_by(
- func.date(Payment.payment_date)
- ).order_by(func.date(Payment.payment_date))
-
+ daily_revenue_query = daily_revenue_query.group_by(func.date(Payment.payment_date)).order_by(func.date(Payment.payment_date))
daily_data = daily_revenue_query.all()
- revenue_by_date = [
- {
- "date": str(date),
- "revenue": float(revenue or 0),
- "bookings": int(bookings or 0)
- }
- for date, revenue, bookings in daily_data
- ]
-
- # Bookings by status
+ revenue_by_date = [{'date': str(date), 'revenue': float(revenue or 0), 'bookings': int(bookings or 0)} for date, revenue, bookings in daily_data]
bookings_by_status = {}
for status in BookingStatus:
count = booking_query.filter(Booking.status == status).count()
status_name = status.value if hasattr(status, 'value') else str(status)
bookings_by_status[status_name] = count
-
- # Top rooms (by revenue)
- top_rooms_query = db.query(
- Room.id,
- Room.room_number,
- func.count(Booking.id).label('bookings'),
- func.sum(Payment.amount).label('revenue')
- ).join(Booking, Room.id == Booking.room_id).join(
- Payment, Booking.id == Payment.booking_id
- ).filter(Payment.payment_status == PaymentStatus.completed)
-
+ top_rooms_query = db.query(Room.id, Room.room_number, func.count(Booking.id).label('bookings'), func.sum(Payment.amount).label('revenue')).join(Booking, Room.id == Booking.room_id).join(Payment, Booking.id == Payment.booking_id).filter(Payment.payment_status == PaymentStatus.completed)
if start_date:
top_rooms_query = top_rooms_query.filter(Booking.created_at >= start_date)
if end_date:
top_rooms_query = top_rooms_query.filter(Booking.created_at <= end_date)
-
- top_rooms_data = top_rooms_query.group_by(Room.id, Room.room_number).order_by(
- func.sum(Payment.amount).desc()
- ).limit(10).all()
-
- top_rooms = [
- {
- "room_id": room_id,
- "room_number": room_number,
- "bookings": int(bookings or 0),
- "revenue": float(revenue or 0)
- }
- for room_id, room_number, bookings, revenue in top_rooms_data
- ]
-
- # Service usage statistics
- service_usage_query = db.query(
- Service.id,
- Service.name,
- func.count(ServiceUsage.id).label('usage_count'),
- func.sum(ServiceUsage.total_price).label('total_revenue')
- ).join(ServiceUsage, Service.id == ServiceUsage.service_id)
-
+ top_rooms_data = top_rooms_query.group_by(Room.id, Room.room_number).order_by(func.sum(Payment.amount).desc()).limit(10).all()
+ top_rooms = [{'room_id': room_id, 'room_number': room_number, 'bookings': int(bookings or 0), 'revenue': float(revenue or 0)} for room_id, room_number, bookings, revenue in top_rooms_data]
+ service_usage_query = db.query(Service.id, Service.name, func.count(ServiceUsage.id).label('usage_count'), func.sum(ServiceUsage.total_price).label('total_revenue')).join(ServiceUsage, Service.id == ServiceUsage.service_id)
if start_date:
service_usage_query = service_usage_query.filter(ServiceUsage.usage_date >= start_date)
if end_date:
service_usage_query = service_usage_query.filter(ServiceUsage.usage_date <= end_date)
-
- service_usage_data = service_usage_query.group_by(Service.id, Service.name).order_by(
- func.sum(ServiceUsage.total_price).desc()
- ).limit(10).all()
-
- service_usage = [
- {
- "service_id": service_id,
- "service_name": service_name,
- "usage_count": int(usage_count or 0),
- "total_revenue": float(total_revenue or 0)
- }
- for service_id, service_name, usage_count, total_revenue in service_usage_data
- ]
-
- return {
- "status": "success",
- "success": True,
- "data": {
- "total_bookings": total_bookings,
- "total_revenue": float(total_revenue),
- "total_customers": int(total_customers),
- "available_rooms": available_rooms,
- "occupied_rooms": occupied_rooms,
- "revenue_by_date": revenue_by_date if revenue_by_date else None,
- "bookings_by_status": bookings_by_status,
- "top_rooms": top_rooms if top_rooms else None,
- "service_usage": service_usage if service_usage else None,
- }
- }
+ service_usage_data = service_usage_query.group_by(Service.id, Service.name).order_by(func.sum(ServiceUsage.total_price).desc()).limit(10).all()
+ service_usage = [{'service_id': service_id, 'service_name': service_name, 'usage_count': int(usage_count or 0), 'total_revenue': float(total_revenue or 0)} for service_id, service_name, usage_count, total_revenue in service_usage_data]
+ return {'status': 'success', 'success': True, 'data': {'total_bookings': total_bookings, 'total_revenue': float(total_revenue), 'total_customers': int(total_customers), 'available_rooms': available_rooms, 'occupied_rooms': occupied_rooms, 'revenue_by_date': revenue_by_date if revenue_by_date else None, 'bookings_by_status': bookings_by_status, 'top_rooms': top_rooms if top_rooms else None, 'service_usage': service_usage if service_usage else None}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/dashboard")
-async def get_dashboard_stats(
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Get dashboard statistics (Admin/Staff only)"""
+@router.get('/dashboard')
+async def get_dashboard_stats(current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
- # Total bookings
total_bookings = db.query(Booking).count()
-
- # Active bookings
- active_bookings = db.query(Booking).filter(
- Booking.status.in_([BookingStatus.pending, BookingStatus.confirmed, BookingStatus.checked_in])
- ).count()
-
- # Total revenue (from completed payments)
- total_revenue = db.query(func.sum(Payment.amount)).filter(
- Payment.payment_status == PaymentStatus.completed
- ).scalar() or 0.0
-
- # Today's revenue
+ active_bookings = db.query(Booking).filter(Booking.status.in_([BookingStatus.pending, BookingStatus.confirmed, BookingStatus.checked_in])).count()
+ total_revenue = db.query(func.sum(Payment.amount)).filter(Payment.payment_status == PaymentStatus.completed).scalar() or 0.0
today_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
- today_revenue = db.query(func.sum(Payment.amount)).filter(
- and_(
- Payment.payment_status == PaymentStatus.completed,
- Payment.payment_date >= today_start
- )
- ).scalar() or 0.0
-
- # Total rooms
+ today_revenue = db.query(func.sum(Payment.amount)).filter(and_(Payment.payment_status == PaymentStatus.completed, Payment.payment_date >= today_start)).scalar() or 0.0
total_rooms = db.query(Room).count()
-
- # Available rooms
- available_rooms = db.query(Room).filter(Room.status == "available").count()
-
- # Recent bookings (last 7 days)
+ available_rooms = db.query(Room).filter(Room.status == 'available').count()
week_ago = datetime.utcnow() - timedelta(days=7)
- recent_bookings = db.query(Booking).filter(
- Booking.created_at >= week_ago
- ).count()
-
- # Pending payments
- pending_payments = db.query(Payment).filter(
- Payment.payment_status == PaymentStatus.pending
- ).count()
-
- return {
- "status": "success",
- "data": {
- "total_bookings": total_bookings,
- "active_bookings": active_bookings,
- "total_revenue": float(total_revenue),
- "today_revenue": float(today_revenue),
- "total_rooms": total_rooms,
- "available_rooms": available_rooms,
- "recent_bookings": recent_bookings,
- "pending_payments": pending_payments,
- }
- }
+ recent_bookings = db.query(Booking).filter(Booking.created_at >= week_ago).count()
+ pending_payments = db.query(Payment).filter(Payment.payment_status == PaymentStatus.pending).count()
+ return {'status': 'success', 'data': {'total_bookings': total_bookings, 'active_bookings': active_bookings, 'total_revenue': float(total_revenue), 'today_revenue': float(today_revenue), 'total_rooms': total_rooms, 'available_rooms': available_rooms, 'recent_bookings': recent_bookings, 'pending_payments': pending_payments}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/customer/dashboard")
-async def get_customer_dashboard_stats(
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Get customer dashboard statistics"""
+@router.get('/customer/dashboard')
+async def get_customer_dashboard_stats(current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
from datetime import datetime, timedelta
-
- # Total bookings count for user
- total_bookings = db.query(Booking).filter(
- Booking.user_id == current_user.id
- ).count()
-
- # Total spending (sum of completed payments from user's bookings)
- user_bookings = db.query(Booking.id).filter(
- Booking.user_id == current_user.id
- ).subquery()
-
- total_spending = db.query(func.sum(Payment.amount)).filter(
- and_(
- Payment.booking_id.in_(db.query(user_bookings.c.id)),
- Payment.payment_status == PaymentStatus.completed
- )
- ).scalar() or 0.0
-
- # Currently staying (checked_in bookings)
+ total_bookings = db.query(Booking).filter(Booking.user_id == current_user.id).count()
+ user_bookings = db.query(Booking.id).filter(Booking.user_id == current_user.id).subquery()
+ total_spending = db.query(func.sum(Payment.amount)).filter(and_(Payment.booking_id.in_(db.query(user_bookings.c.id)), Payment.payment_status == PaymentStatus.completed)).scalar() or 0.0
now = datetime.utcnow()
- currently_staying = db.query(Booking).filter(
- and_(
- Booking.user_id == current_user.id,
- Booking.status == BookingStatus.checked_in,
- Booking.check_in_date <= now,
- Booking.check_out_date >= now
- )
- ).count()
-
- # Upcoming bookings (confirmed/pending with check_in_date in future)
- upcoming_bookings_query = db.query(Booking).filter(
- and_(
- Booking.user_id == current_user.id,
- Booking.status.in_([BookingStatus.confirmed, BookingStatus.pending]),
- Booking.check_in_date > now
- )
- ).order_by(Booking.check_in_date.asc()).limit(5).all()
-
+ currently_staying = db.query(Booking).filter(and_(Booking.user_id == current_user.id, Booking.status == BookingStatus.checked_in, Booking.check_in_date <= now, Booking.check_out_date >= now)).count()
+ upcoming_bookings_query = db.query(Booking).filter(and_(Booking.user_id == current_user.id, Booking.status.in_([BookingStatus.confirmed, BookingStatus.pending]), Booking.check_in_date > now)).order_by(Booking.check_in_date.asc()).limit(5).all()
upcoming_bookings = []
for booking in upcoming_bookings_query:
- booking_dict = {
- "id": booking.id,
- "booking_number": booking.booking_number,
- "check_in_date": booking.check_in_date.isoformat() if booking.check_in_date else None,
- "check_out_date": booking.check_out_date.isoformat() if booking.check_out_date else None,
- "status": booking.status.value if isinstance(booking.status, BookingStatus) else booking.status,
- "total_price": float(booking.total_price) if booking.total_price else 0.0,
- }
-
+ booking_dict = {'id': booking.id, 'booking_number': booking.booking_number, 'check_in_date': booking.check_in_date.isoformat() if booking.check_in_date else None, 'check_out_date': booking.check_out_date.isoformat() if booking.check_out_date else None, 'status': booking.status.value if isinstance(booking.status, BookingStatus) else booking.status, 'total_price': float(booking.total_price) if booking.total_price else 0.0}
if booking.room:
- booking_dict["room"] = {
- "id": booking.room.id,
- "room_number": booking.room.room_number,
- "room_type": {
- "name": booking.room.room_type.name if booking.room.room_type else None
- }
- }
-
+ booking_dict['room'] = {'id': booking.room.id, 'room_number': booking.room.room_number, 'room_type': {'name': booking.room.room_type.name if booking.room.room_type else None}}
upcoming_bookings.append(booking_dict)
-
- # Recent activity (last 5 bookings ordered by created_at)
- recent_bookings_query = db.query(Booking).filter(
- Booking.user_id == current_user.id
- ).order_by(Booking.created_at.desc()).limit(5).all()
-
+ recent_bookings_query = db.query(Booking).filter(Booking.user_id == current_user.id).order_by(Booking.created_at.desc()).limit(5).all()
recent_activity = []
for booking in recent_bookings_query:
activity_type = None
if booking.status == BookingStatus.checked_out:
- activity_type = "Check-out"
+ activity_type = 'Check-out'
elif booking.status == BookingStatus.checked_in:
- activity_type = "Check-in"
+ activity_type = 'Check-in'
elif booking.status == BookingStatus.confirmed:
- activity_type = "Booking Confirmed"
+ activity_type = 'Booking Confirmed'
elif booking.status == BookingStatus.pending:
- activity_type = "Booking"
+ activity_type = 'Booking'
else:
- activity_type = "Booking"
-
- activity_dict = {
- "action": activity_type,
- "booking_id": booking.id,
- "booking_number": booking.booking_number,
- "created_at": booking.created_at.isoformat() if booking.created_at else None,
- }
-
+ activity_type = 'Booking'
+ activity_dict = {'action': activity_type, 'booking_id': booking.id, 'booking_number': booking.booking_number, 'created_at': booking.created_at.isoformat() if booking.created_at else None}
if booking.room:
- activity_dict["room"] = {
- "room_number": booking.room.room_number,
- }
-
+ activity_dict['room'] = {'room_number': booking.room.room_number}
recent_activity.append(activity_dict)
-
- # Calculate percentage change (placeholder - can be enhanced)
- # For now, compare last month vs this month
last_month_start = (now - timedelta(days=30)).replace(day=1, hour=0, minute=0, second=0)
last_month_end = now.replace(day=1, hour=0, minute=0, second=0) - timedelta(seconds=1)
-
- last_month_bookings = db.query(Booking).filter(
- and_(
- Booking.user_id == current_user.id,
- Booking.created_at >= last_month_start,
- Booking.created_at <= last_month_end
- )
- ).count()
-
- this_month_bookings = db.query(Booking).filter(
- and_(
- Booking.user_id == current_user.id,
- Booking.created_at >= now.replace(day=1, hour=0, minute=0, second=0),
- Booking.created_at <= now
- )
- ).count()
-
+ last_month_bookings = db.query(Booking).filter(and_(Booking.user_id == current_user.id, Booking.created_at >= last_month_start, Booking.created_at <= last_month_end)).count()
+ this_month_bookings = db.query(Booking).filter(and_(Booking.user_id == current_user.id, Booking.created_at >= now.replace(day=1, hour=0, minute=0, second=0), Booking.created_at <= now)).count()
booking_change_percentage = 0
if last_month_bookings > 0:
- booking_change_percentage = ((this_month_bookings - last_month_bookings) / last_month_bookings) * 100
-
- last_month_spending = db.query(func.sum(Payment.amount)).filter(
- and_(
- Payment.booking_id.in_(db.query(user_bookings.c.id)),
- Payment.payment_status == PaymentStatus.completed,
- Payment.payment_date >= last_month_start,
- Payment.payment_date <= last_month_end
- )
- ).scalar() or 0.0
-
- this_month_spending = db.query(func.sum(Payment.amount)).filter(
- and_(
- Payment.booking_id.in_(db.query(user_bookings.c.id)),
- Payment.payment_status == PaymentStatus.completed,
- Payment.payment_date >= now.replace(day=1, hour=0, minute=0, second=0),
- Payment.payment_date <= now
- )
- ).scalar() or 0.0
-
+ booking_change_percentage = (this_month_bookings - last_month_bookings) / last_month_bookings * 100
+ last_month_spending = db.query(func.sum(Payment.amount)).filter(and_(Payment.booking_id.in_(db.query(user_bookings.c.id)), Payment.payment_status == PaymentStatus.completed, Payment.payment_date >= last_month_start, Payment.payment_date <= last_month_end)).scalar() or 0.0
+ this_month_spending = db.query(func.sum(Payment.amount)).filter(and_(Payment.booking_id.in_(db.query(user_bookings.c.id)), Payment.payment_status == PaymentStatus.completed, Payment.payment_date >= now.replace(day=1, hour=0, minute=0, second=0), Payment.payment_date <= now)).scalar() or 0.0
spending_change_percentage = 0
if last_month_spending > 0:
- spending_change_percentage = ((this_month_spending - last_month_spending) / last_month_spending) * 100
-
- return {
- "status": "success",
- "success": True,
- "data": {
- "total_bookings": total_bookings,
- "total_spending": float(total_spending),
- "currently_staying": currently_staying,
- "upcoming_bookings": upcoming_bookings,
- "recent_activity": recent_activity,
- "booking_change_percentage": round(booking_change_percentage, 1),
- "spending_change_percentage": round(spending_change_percentage, 1),
- }
- }
+ spending_change_percentage = (this_month_spending - last_month_spending) / last_month_spending * 100
+ return {'status': 'success', 'success': True, 'data': {'total_bookings': total_bookings, 'total_spending': float(total_spending), 'currently_staying': currently_staying, 'upcoming_bookings': upcoming_bookings, 'recent_activity': recent_activity, 'booking_change_percentage': round(booking_change_percentage, 1), 'spending_change_percentage': round(spending_change_percentage, 1)}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/revenue")
-async def get_revenue_report(
- start_date: Optional[str] = Query(None),
- end_date: Optional[str] = Query(None),
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Get revenue report (Admin/Staff only)"""
+@router.get('/revenue')
+async def get_revenue_report(start_date: Optional[str]=Query(None), end_date: Optional[str]=Query(None), current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
- query = db.query(Payment).filter(
- Payment.payment_status == PaymentStatus.completed
- )
-
+ query = db.query(Payment).filter(Payment.payment_status == PaymentStatus.completed)
if start_date:
start = datetime.fromisoformat(start_date.replace('Z', '+00:00'))
query = query.filter(Payment.payment_date >= start)
-
if end_date:
end = datetime.fromisoformat(end_date.replace('Z', '+00:00'))
query = query.filter(Payment.payment_date <= end)
-
- # Total revenue
- total_revenue = db.query(func.sum(Payment.amount)).filter(
- Payment.payment_status == PaymentStatus.completed
- ).scalar() or 0.0
-
- # Revenue by payment method
- revenue_by_method = db.query(
- Payment.payment_method,
- func.sum(Payment.amount).label('total')
- ).filter(
- Payment.payment_status == PaymentStatus.completed
- ).group_by(Payment.payment_method).all()
-
+ total_revenue = db.query(func.sum(Payment.amount)).filter(Payment.payment_status == PaymentStatus.completed).scalar() or 0.0
+ revenue_by_method = db.query(Payment.payment_method, func.sum(Payment.amount).label('total')).filter(Payment.payment_status == PaymentStatus.completed).group_by(Payment.payment_method).all()
method_breakdown = {}
for method, total in revenue_by_method:
method_name = method.value if hasattr(method, 'value') else str(method)
method_breakdown[method_name] = float(total or 0)
-
- # Revenue by date (daily breakdown)
- daily_revenue = db.query(
- func.date(Payment.payment_date).label('date'),
- func.sum(Payment.amount).label('total')
- ).filter(
- Payment.payment_status == PaymentStatus.completed
- ).group_by(func.date(Payment.payment_date)).order_by(func.date(Payment.payment_date).desc()).limit(30).all()
-
- daily_breakdown = [
- {
- "date": date.isoformat() if isinstance(date, datetime) else str(date),
- "revenue": float(total or 0)
- }
- for date, total in daily_revenue
- ]
-
- return {
- "status": "success",
- "data": {
- "total_revenue": float(total_revenue),
- "revenue_by_method": method_breakdown,
- "daily_breakdown": daily_breakdown,
- }
- }
+ daily_revenue = db.query(func.date(Payment.payment_date).label('date'), func.sum(Payment.amount).label('total')).filter(Payment.payment_status == PaymentStatus.completed).group_by(func.date(Payment.payment_date)).order_by(func.date(Payment.payment_date).desc()).limit(30).all()
+ daily_breakdown = [{'date': date.isoformat() if isinstance(date, datetime) else str(date), 'revenue': float(total or 0)} for date, total in daily_revenue]
+ return {'status': 'success', 'data': {'total_revenue': float(total_revenue), 'revenue_by_method': method_breakdown, 'daily_breakdown': daily_breakdown}}
except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/review_routes.py b/Backend/src/routes/review_routes.py
index 7f7361cd..95c1ee51 100644
--- a/Backend/src/routes/review_routes.py
+++ b/Backend/src/routes/review_routes.py
@@ -1,251 +1,117 @@
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import Optional
-
from ..config.database import get_db
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
from ..models.review import Review, ReviewStatus
from ..models.room import Room
+router = APIRouter(prefix='/reviews', tags=['reviews'])
-router = APIRouter(prefix="/reviews", tags=["reviews"])
-
-
-@router.get("/room/{room_id}")
-async def get_room_reviews(room_id: int, db: Session = Depends(get_db)):
- """Get reviews for a room"""
+@router.get('/room/{room_id}')
+async def get_room_reviews(room_id: int, db: Session=Depends(get_db)):
try:
- reviews = db.query(Review).filter(
- Review.room_id == room_id,
- Review.status == ReviewStatus.approved
- ).order_by(Review.created_at.desc()).all()
-
+ reviews = db.query(Review).filter(Review.room_id == room_id, Review.status == ReviewStatus.approved).order_by(Review.created_at.desc()).all()
result = []
for review in reviews:
- review_dict = {
- "id": review.id,
- "user_id": review.user_id,
- "room_id": review.room_id,
- "rating": review.rating,
- "comment": review.comment,
- "status": review.status.value if isinstance(review.status, ReviewStatus) else review.status,
- "created_at": review.created_at.isoformat() if review.created_at else None,
- }
-
+ review_dict = {'id': review.id, 'user_id': review.user_id, 'room_id': review.room_id, 'rating': review.rating, 'comment': review.comment, 'status': review.status.value if isinstance(review.status, ReviewStatus) else review.status, 'created_at': review.created_at.isoformat() if review.created_at else None}
if review.user:
- review_dict["user"] = {
- "id": review.user.id,
- "full_name": review.user.full_name,
- "email": review.user.email,
- }
-
+ review_dict['user'] = {'id': review.user.id, 'full_name': review.user.full_name, 'email': review.user.email}
result.append(review_dict)
-
- return {
- "status": "success",
- "data": {"reviews": result}
- }
+ return {'status': 'success', 'data': {'reviews': result}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/", dependencies=[Depends(authorize_roles("admin"))])
-async def get_all_reviews(
- status_filter: Optional[str] = Query(None, alias="status"),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Get all reviews (Admin only)"""
+@router.get('/', dependencies=[Depends(authorize_roles('admin'))])
+async def get_all_reviews(status_filter: Optional[str]=Query(None, alias='status'), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
query = db.query(Review)
-
if status_filter:
try:
query = query.filter(Review.status == ReviewStatus(status_filter))
except ValueError:
pass
-
total = query.count()
offset = (page - 1) * limit
reviews = query.order_by(Review.created_at.desc()).offset(offset).limit(limit).all()
-
result = []
for review in reviews:
- review_dict = {
- "id": review.id,
- "user_id": review.user_id,
- "room_id": review.room_id,
- "rating": review.rating,
- "comment": review.comment,
- "status": review.status.value if isinstance(review.status, ReviewStatus) else review.status,
- "created_at": review.created_at.isoformat() if review.created_at else None,
- }
-
+ review_dict = {'id': review.id, 'user_id': review.user_id, 'room_id': review.room_id, 'rating': review.rating, 'comment': review.comment, 'status': review.status.value if isinstance(review.status, ReviewStatus) else review.status, 'created_at': review.created_at.isoformat() if review.created_at else None}
if review.user:
- review_dict["user"] = {
- "id": review.user.id,
- "full_name": review.user.full_name,
- "email": review.user.email,
- "phone": review.user.phone,
- }
-
+ review_dict['user'] = {'id': review.user.id, 'full_name': review.user.full_name, 'email': review.user.email, 'phone': review.user.phone}
if review.room:
- review_dict["room"] = {
- "id": review.room.id,
- "room_number": review.room.room_number,
- }
-
+ review_dict['room'] = {'id': review.room.id, 'room_number': review.room.room_number}
result.append(review_dict)
-
- return {
- "status": "success",
- "data": {
- "reviews": result,
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'reviews': result, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/")
-async def create_review(
- review_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create new review"""
+@router.post('/')
+async def create_review(review_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- room_id = review_data.get("room_id")
- rating = review_data.get("rating")
- comment = review_data.get("comment")
-
- # Check if room exists
+ room_id = review_data.get('room_id')
+ rating = review_data.get('rating')
+ comment = review_data.get('comment')
room = db.query(Room).filter(Room.id == room_id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Check if user already reviewed this room
- existing = db.query(Review).filter(
- Review.user_id == current_user.id,
- Review.room_id == room_id
- ).first()
-
+ raise HTTPException(status_code=404, detail='Room not found')
+ existing = db.query(Review).filter(Review.user_id == current_user.id, Review.room_id == room_id).first()
if existing:
- raise HTTPException(
- status_code=400,
- detail="You have already reviewed this room"
- )
-
- # Create review
- review = Review(
- user_id=current_user.id,
- room_id=room_id,
- rating=rating,
- comment=comment,
- status=ReviewStatus.pending,
- )
-
+ raise HTTPException(status_code=400, detail='You have already reviewed this room')
+ review = Review(user_id=current_user.id, room_id=room_id, rating=rating, comment=comment, status=ReviewStatus.pending)
db.add(review)
db.commit()
db.refresh(review)
-
- return {
- "status": "success",
- "message": "Review submitted successfully and is pending approval",
- "data": {"review": review}
- }
+ return {'status': 'success', 'message': 'Review submitted successfully and is pending approval', 'data': {'review': review}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}/approve", dependencies=[Depends(authorize_roles("admin"))])
-async def approve_review(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Approve review (Admin only)"""
+@router.put('/{id}/approve', dependencies=[Depends(authorize_roles('admin'))])
+async def approve_review(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
review = db.query(Review).filter(Review.id == id).first()
if not review:
- raise HTTPException(status_code=404, detail="Review not found")
-
+ raise HTTPException(status_code=404, detail='Review not found')
review.status = ReviewStatus.approved
db.commit()
db.refresh(review)
-
- return {
- "status": "success",
- "message": "Review approved successfully",
- "data": {"review": review}
- }
+ return {'status': 'success', 'message': 'Review approved successfully', 'data': {'review': review}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}/reject", dependencies=[Depends(authorize_roles("admin"))])
-async def reject_review(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Reject review (Admin only)"""
+@router.put('/{id}/reject', dependencies=[Depends(authorize_roles('admin'))])
+async def reject_review(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
review = db.query(Review).filter(Review.id == id).first()
if not review:
- raise HTTPException(status_code=404, detail="Review not found")
-
+ raise HTTPException(status_code=404, detail='Review not found')
review.status = ReviewStatus.rejected
db.commit()
db.refresh(review)
-
- return {
- "status": "success",
- "message": "Review rejected successfully",
- "data": {"review": review}
- }
+ return {'status': 'success', 'message': 'Review rejected successfully', 'data': {'review': review}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def delete_review(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Delete review (Admin only)"""
+@router.delete('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def delete_review(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
review = db.query(Review).filter(Review.id == id).first()
if not review:
- raise HTTPException(status_code=404, detail="Review not found")
-
+ raise HTTPException(status_code=404, detail='Review not found')
db.delete(review)
db.commit()
-
- return {
- "status": "success",
- "message": "Review deleted successfully"
- }
+ return {'status': 'success', 'message': 'Review deleted successfully'}
except HTTPException:
raise
except Exception as e:
db.rollback()
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/room_routes.py b/Backend/src/routes/room_routes.py
index d8a93732..8128ac6d 100644
--- a/Backend/src/routes/room_routes.py
+++ b/Backend/src/routes/room_routes.py
@@ -3,7 +3,6 @@ from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, func
from typing import List, Optional
from datetime import datetime
-
from ..config.database import get_db
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
@@ -15,885 +14,382 @@ from ..services.room_service import get_rooms_with_ratings, get_amenities_list,
import os
import aiofiles
from pathlib import Path
+router = APIRouter(prefix='/rooms', tags=['rooms'])
-router = APIRouter(prefix="/rooms", tags=["rooms"])
-
-
-@router.get("/")
-async def get_rooms(
- request: Request,
- type: Optional[str] = Query(None),
- minPrice: Optional[float] = Query(None),
- maxPrice: Optional[float] = Query(None),
- capacity: Optional[int] = Query(None),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- sort: Optional[str] = Query(None),
- featured: Optional[bool] = Query(None),
- db: Session = Depends(get_db)
-):
- """Get all rooms with filters"""
+@router.get('/')
+async def get_rooms(request: Request, type: Optional[str]=Query(None), minPrice: Optional[float]=Query(None), maxPrice: Optional[float]=Query(None), capacity: Optional[int]=Query(None), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), sort: Optional[str]=Query(None), featured: Optional[bool]=Query(None), db: Session=Depends(get_db)):
try:
- # Build where clause for rooms
where_clause = {}
room_type_where = {}
-
if featured is not None:
- where_clause["featured"] = featured
-
+ where_clause['featured'] = featured
if type:
- room_type_where["name"] = f"%{type}%"
-
+ room_type_where['name'] = f'%{type}%'
if capacity:
- room_type_where["capacity"] = capacity
-
+ room_type_where['capacity'] = capacity
if minPrice or maxPrice:
if minPrice:
- room_type_where["base_price_min"] = minPrice
+ room_type_where['base_price_min'] = minPrice
if maxPrice:
- room_type_where["base_price_max"] = maxPrice
-
- # Build query
+ room_type_where['base_price_max'] = maxPrice
query = db.query(Room).join(RoomType)
-
- # Apply filters
- if where_clause.get("featured") is not None:
- query = query.filter(Room.featured == where_clause["featured"])
-
- if room_type_where.get("name"):
- query = query.filter(RoomType.name.like(room_type_where["name"]))
-
- if room_type_where.get("capacity"):
- query = query.filter(RoomType.capacity >= room_type_where["capacity"])
-
- if room_type_where.get("base_price_min"):
- query = query.filter(RoomType.base_price >= room_type_where["base_price_min"])
-
- if room_type_where.get("base_price_max"):
- query = query.filter(RoomType.base_price <= room_type_where["base_price_max"])
-
- # Get total count
+ if where_clause.get('featured') is not None:
+ query = query.filter(Room.featured == where_clause['featured'])
+ if room_type_where.get('name'):
+ query = query.filter(RoomType.name.like(room_type_where['name']))
+ if room_type_where.get('capacity'):
+ query = query.filter(RoomType.capacity >= room_type_where['capacity'])
+ if room_type_where.get('base_price_min'):
+ query = query.filter(RoomType.base_price >= room_type_where['base_price_min'])
+ if room_type_where.get('base_price_max'):
+ query = query.filter(RoomType.base_price <= room_type_where['base_price_max'])
total = query.count()
-
- # Apply sorting
- if sort == "newest" or sort == "created_at":
+ if sort == 'newest' or sort == 'created_at':
query = query.order_by(Room.created_at.desc())
else:
query = query.order_by(Room.featured.desc(), Room.created_at.desc())
-
- # Apply pagination
offset = (page - 1) * limit
rooms = query.offset(offset).limit(limit).all()
-
- # Get base URL
base_url = get_base_url(request)
-
- # Get rooms with ratings
rooms_with_ratings = await get_rooms_with_ratings(db, rooms, base_url)
-
- return {
- "status": "success",
- "data": {
- "rooms": rooms_with_ratings,
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'rooms': rooms_with_ratings, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/amenities")
-async def get_amenities(db: Session = Depends(get_db)):
- """Get all available amenities"""
+@router.get('/amenities')
+async def get_amenities(db: Session=Depends(get_db)):
try:
amenities = await get_amenities_list(db)
- return {"status": "success", "data": {"amenities": amenities}}
+ return {'status': 'success', 'data': {'amenities': amenities}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/available")
-async def search_available_rooms(
- request: Request,
- from_date: str = Query(..., alias="from"),
- to_date: str = Query(..., alias="to"),
- roomId: Optional[int] = Query(None, alias="roomId"),
- type: Optional[str] = Query(None),
- capacity: Optional[int] = Query(None),
- page: int = Query(1, ge=1),
- limit: int = Query(12, ge=1, le=100),
- db: Session = Depends(get_db)
-):
- """Search for available rooms or check specific room availability"""
+@router.get('/available')
+async def search_available_rooms(request: Request, from_date: str=Query(..., alias='from'), to_date: str=Query(..., alias='to'), roomId: Optional[int]=Query(None, alias='roomId'), type: Optional[str]=Query(None), capacity: Optional[int]=Query(None), page: int=Query(1, ge=1), limit: int=Query(12, ge=1, le=100), db: Session=Depends(get_db)):
try:
- # Parse dates - handle both date-only and datetime formats
try:
if 'T' in from_date or 'Z' in from_date or '+' in from_date:
check_in = datetime.fromisoformat(from_date.replace('Z', '+00:00'))
else:
check_in = datetime.strptime(from_date, '%Y-%m-%d')
except ValueError:
- raise HTTPException(status_code=400, detail=f"Invalid from date format: {from_date}")
-
+ raise HTTPException(status_code=400, detail=f'Invalid from date format: {from_date}')
try:
if 'T' in to_date or 'Z' in to_date or '+' in to_date:
check_out = datetime.fromisoformat(to_date.replace('Z', '+00:00'))
else:
check_out = datetime.strptime(to_date, '%Y-%m-%d')
except ValueError:
- raise HTTPException(status_code=400, detail=f"Invalid to date format: {to_date}")
-
- # If checking a specific room, handle it differently
+ raise HTTPException(status_code=400, detail=f'Invalid to date format: {to_date}')
if roomId:
- # Check if room exists
room = db.query(Room).filter(Room.id == roomId).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Check if room is available
+ raise HTTPException(status_code=404, detail='Room not found')
if room.status != RoomStatus.available:
- return {
- "status": "success",
- "data": {
- "available": False,
- "message": "Room is not available",
- "room_id": roomId
- }
- }
-
- # Check for overlapping bookings
- overlapping = db.query(Booking).filter(
- and_(
- Booking.room_id == roomId,
- Booking.status != BookingStatus.cancelled,
- Booking.check_in_date < check_out,
- Booking.check_out_date > check_in
- )
- ).first()
-
+ return {'status': 'success', 'data': {'available': False, 'message': 'Room is not available', 'room_id': roomId}}
+ overlapping = db.query(Booking).filter(and_(Booking.room_id == roomId, Booking.status != BookingStatus.cancelled, Booking.check_in_date < check_out, Booking.check_out_date > check_in)).first()
if overlapping:
- return {
- "status": "success",
- "data": {
- "available": False,
- "message": "Room is already booked for the selected dates",
- "room_id": roomId
- }
- }
-
- return {
- "status": "success",
- "data": {
- "available": True,
- "message": "Room is available",
- "room_id": roomId
- }
- }
-
- # Original search functionality
+ return {'status': 'success', 'data': {'available': False, 'message': 'Room is already booked for the selected dates', 'room_id': roomId}}
+ return {'status': 'success', 'data': {'available': True, 'message': 'Room is available', 'room_id': roomId}}
if check_in >= check_out:
- raise HTTPException(
- status_code=400,
- detail="Check-out date must be after check-in date"
- )
-
- # Build room type filter
+ raise HTTPException(status_code=400, detail='Check-out date must be after check-in date')
query = db.query(Room).join(RoomType).filter(Room.status == RoomStatus.available)
-
if type:
- query = query.filter(RoomType.name.like(f"%{type}%"))
-
+ query = query.filter(RoomType.name.like(f'%{type}%'))
if capacity:
query = query.filter(RoomType.capacity >= capacity)
-
- # Exclude rooms with overlapping bookings
- overlapping_rooms = db.query(Booking.room_id).filter(
- and_(
- Booking.status != BookingStatus.cancelled,
- Booking.check_in_date < check_out,
- Booking.check_out_date > check_in
- )
- ).subquery()
-
+ overlapping_rooms = db.query(Booking.room_id).filter(and_(Booking.status != BookingStatus.cancelled, Booking.check_in_date < check_out, Booking.check_out_date > check_in)).subquery()
query = query.filter(~Room.id.in_(db.query(overlapping_rooms.c.room_id)))
-
- # Get total
total = query.count()
-
- # Apply sorting and pagination
query = query.order_by(Room.featured.desc(), Room.created_at.desc())
offset = (page - 1) * limit
rooms = query.offset(offset).limit(limit).all()
-
- # Get base URL
base_url = get_base_url(request)
-
- # Get rooms with ratings
rooms_with_ratings = await get_rooms_with_ratings(db, rooms, base_url)
-
- return {
- "status": "success",
- "data": {
- "rooms": rooms_with_ratings,
- "search": {
- "from": from_date,
- "to": to_date,
- "type": type,
- "capacity": capacity,
- },
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'rooms': rooms_with_ratings, 'search': {'from': from_date, 'to': to_date, 'type': type, 'capacity': capacity}, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/id/{id}")
-async def get_room_by_id(id: int, request: Request, db: Session = Depends(get_db)):
- """Get room by ID"""
+@router.get('/id/{id}')
+async def get_room_by_id(id: int, request: Request, db: Session=Depends(get_db)):
try:
room = db.query(Room).filter(Room.id == id).first()
-
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Get review stats
- review_stats = db.query(
- func.avg(Review.rating).label('average_rating'),
- func.count(Review.id).label('total_reviews')
- ).filter(
- and_(
- Review.room_id == room.id,
- Review.status == ReviewStatus.approved
- )
- ).first()
-
+ raise HTTPException(status_code=404, detail='Room not found')
+ review_stats = db.query(func.avg(Review.rating).label('average_rating'), func.count(Review.id).label('total_reviews')).filter(and_(Review.room_id == room.id, Review.status == ReviewStatus.approved)).first()
base_url = get_base_url(request)
-
- room_dict = {
- "id": room.id,
- "room_type_id": room.room_type_id,
- "room_number": room.room_number,
- "floor": room.floor,
- "status": room.status.value if isinstance(room.status, RoomStatus) else room.status,
- "price": float(room.price) if room.price is not None and room.price > 0 else None,
- "featured": room.featured,
- "description": room.description,
- "capacity": room.capacity,
- "room_size": room.room_size,
- "view": room.view,
- "amenities": room.amenities,
- "created_at": room.created_at.isoformat() if room.created_at else None,
- "updated_at": room.updated_at.isoformat() if room.updated_at else None,
- "average_rating": round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None,
- "total_reviews": review_stats.total_reviews or 0 if review_stats else 0,
- }
-
- # Normalize images
+ room_dict = {'id': room.id, 'room_type_id': room.room_type_id, 'room_number': room.room_number, 'floor': room.floor, 'status': room.status.value if isinstance(room.status, RoomStatus) else room.status, 'price': float(room.price) if room.price is not None and room.price > 0 else None, 'featured': room.featured, 'description': room.description, 'capacity': room.capacity, 'room_size': room.room_size, 'view': room.view, 'amenities': room.amenities, 'created_at': room.created_at.isoformat() if room.created_at else None, 'updated_at': room.updated_at.isoformat() if room.updated_at else None, 'average_rating': round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None, 'total_reviews': review_stats.total_reviews or 0 if review_stats else 0}
try:
- room_dict["images"] = normalize_images(room.images, base_url)
+ room_dict['images'] = normalize_images(room.images, base_url)
except:
- room_dict["images"] = []
-
- # Add room type
+ room_dict['images'] = []
if room.room_type:
- room_dict["room_type"] = {
- "id": room.room_type.id,
- "name": room.room_type.name,
- "description": room.room_type.description,
- "base_price": float(room.room_type.base_price) if room.room_type.base_price else 0.0,
- "capacity": room.room_type.capacity,
- "amenities": room.room_type.amenities,
- "images": [] # RoomType doesn't have images column in DB
- }
-
- return {
- "status": "success",
- "data": {"room": room_dict}
- }
+ room_dict['room_type'] = {'id': room.room_type.id, 'name': room.room_type.name, 'description': room.room_type.description, 'base_price': float(room.room_type.base_price) if room.room_type.base_price else 0.0, 'capacity': room.room_type.capacity, 'amenities': room.room_type.amenities, 'images': []}
+ return {'status': 'success', 'data': {'room': room_dict}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{room_number}")
-async def get_room_by_number(room_number: str, request: Request, db: Session = Depends(get_db)):
- """Get room by room number"""
+@router.get('/{room_number}')
+async def get_room_by_number(room_number: str, request: Request, db: Session=Depends(get_db)):
try:
room = db.query(Room).filter(Room.room_number == room_number).first()
-
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Get review stats
- review_stats = db.query(
- func.avg(Review.rating).label('average_rating'),
- func.count(Review.id).label('total_reviews')
- ).filter(
- and_(
- Review.room_id == room.id,
- Review.status == ReviewStatus.approved
- )
- ).first()
-
+ raise HTTPException(status_code=404, detail='Room not found')
+ review_stats = db.query(func.avg(Review.rating).label('average_rating'), func.count(Review.id).label('total_reviews')).filter(and_(Review.room_id == room.id, Review.status == ReviewStatus.approved)).first()
base_url = get_base_url(request)
-
- room_dict = {
- "id": room.id,
- "room_type_id": room.room_type_id,
- "room_number": room.room_number,
- "floor": room.floor,
- "status": room.status.value if isinstance(room.status, RoomStatus) else room.status,
- "price": float(room.price) if room.price is not None and room.price > 0 else None,
- "featured": room.featured,
- "description": room.description,
- "capacity": room.capacity,
- "room_size": room.room_size,
- "view": room.view,
- "amenities": room.amenities,
- "created_at": room.created_at.isoformat() if room.created_at else None,
- "updated_at": room.updated_at.isoformat() if room.updated_at else None,
- "average_rating": round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None,
- "total_reviews": review_stats.total_reviews or 0 if review_stats else 0,
- }
-
- # Normalize images
+ room_dict = {'id': room.id, 'room_type_id': room.room_type_id, 'room_number': room.room_number, 'floor': room.floor, 'status': room.status.value if isinstance(room.status, RoomStatus) else room.status, 'price': float(room.price) if room.price is not None and room.price > 0 else None, 'featured': room.featured, 'description': room.description, 'capacity': room.capacity, 'room_size': room.room_size, 'view': room.view, 'amenities': room.amenities, 'created_at': room.created_at.isoformat() if room.created_at else None, 'updated_at': room.updated_at.isoformat() if room.updated_at else None, 'average_rating': round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None, 'total_reviews': review_stats.total_reviews or 0 if review_stats else 0}
try:
- room_dict["images"] = normalize_images(room.images, base_url)
+ room_dict['images'] = normalize_images(room.images, base_url)
except:
- room_dict["images"] = []
-
- # Add room type
+ room_dict['images'] = []
if room.room_type:
- room_dict["room_type"] = {
- "id": room.room_type.id,
- "name": room.room_type.name,
- "description": room.room_type.description,
- "base_price": float(room.room_type.base_price) if room.room_type.base_price else 0.0,
- "capacity": room.room_type.capacity,
- "amenities": room.room_type.amenities,
- "images": [] # RoomType doesn't have images column in DB
- }
-
- return {
- "status": "success",
- "data": {"room": room_dict}
- }
+ room_dict['room_type'] = {'id': room.room_type.id, 'name': room.room_type.name, 'description': room.room_type.description, 'base_price': float(room.room_type.base_price) if room.room_type.base_price else 0.0, 'capacity': room.room_type.capacity, 'amenities': room.room_type.amenities, 'images': []}
+ return {'status': 'success', 'data': {'room': room_dict}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/", dependencies=[Depends(authorize_roles("admin"))])
-async def create_room(
- room_data: dict,
- request: Request,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Create new room (Admin only)"""
+@router.post('/', dependencies=[Depends(authorize_roles('admin'))])
+async def create_room(room_data: dict, request: Request, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Check if room type exists
- room_type = db.query(RoomType).filter(RoomType.id == room_data.get("room_type_id")).first()
+ room_type = db.query(RoomType).filter(RoomType.id == room_data.get('room_type_id')).first()
if not room_type:
- raise HTTPException(status_code=404, detail="Room type not found")
-
- # Check if room number exists
- existing = db.query(Room).filter(Room.room_number == room_data.get("room_number")).first()
+ raise HTTPException(status_code=404, detail='Room type not found')
+ existing = db.query(Room).filter(Room.room_number == room_data.get('room_number')).first()
if existing:
- raise HTTPException(status_code=400, detail="Room number already exists")
-
- # Ensure amenities is always a list
- amenities_value = room_data.get("amenities", [])
+ raise HTTPException(status_code=400, detail='Room number already exists')
+ amenities_value = room_data.get('amenities', [])
if amenities_value is None:
amenities_value = []
elif not isinstance(amenities_value, list):
amenities_value = []
-
- room = Room(
- room_type_id=room_data.get("room_type_id"),
- room_number=room_data.get("room_number"),
- floor=room_data.get("floor"),
- status=RoomStatus(room_data.get("status", "available")),
- featured=room_data.get("featured", False),
- price=room_data.get("price", room_type.base_price),
- description=room_data.get("description"),
- capacity=room_data.get("capacity"),
- room_size=room_data.get("room_size"),
- view=room_data.get("view"),
- amenities=amenities_value,
- )
-
+ room = Room(room_type_id=room_data.get('room_type_id'), room_number=room_data.get('room_number'), floor=room_data.get('floor'), status=RoomStatus(room_data.get('status', 'available')), featured=room_data.get('featured', False), price=room_data.get('price', room_type.base_price), description=room_data.get('description'), capacity=room_data.get('capacity'), room_size=room_data.get('room_size'), view=room_data.get('view'), amenities=amenities_value)
db.add(room)
db.commit()
db.refresh(room)
-
- # Get base URL for proper response
base_url = get_base_url(request)
-
- # Serialize room data
- room_dict = {
- "id": room.id,
- "room_type_id": room.room_type_id,
- "room_number": room.room_number,
- "floor": room.floor,
- "status": room.status.value if isinstance(room.status, RoomStatus) else room.status,
- "price": float(room.price) if room.price is not None and room.price > 0 else None,
- "featured": room.featured,
- "description": room.description,
- "capacity": room.capacity,
- "room_size": room.room_size,
- "view": room.view,
- "amenities": room.amenities if room.amenities else [],
- "created_at": room.created_at.isoformat() if room.created_at else None,
- "updated_at": room.updated_at.isoformat() if room.updated_at else None,
- }
-
- # Normalize images
+ room_dict = {'id': room.id, 'room_type_id': room.room_type_id, 'room_number': room.room_number, 'floor': room.floor, 'status': room.status.value if isinstance(room.status, RoomStatus) else room.status, 'price': float(room.price) if room.price is not None and room.price > 0 else None, 'featured': room.featured, 'description': room.description, 'capacity': room.capacity, 'room_size': room.room_size, 'view': room.view, 'amenities': room.amenities if room.amenities else [], 'created_at': room.created_at.isoformat() if room.created_at else None, 'updated_at': room.updated_at.isoformat() if room.updated_at else None}
try:
- room_dict["images"] = normalize_images(room.images, base_url)
+ room_dict['images'] = normalize_images(room.images, base_url)
except:
- room_dict["images"] = []
-
- # Add room type info
+ room_dict['images'] = []
if room.room_type:
- room_dict["room_type"] = {
- "id": room.room_type.id,
- "name": room.room_type.name,
- "description": room.room_type.description,
- "base_price": float(room.room_type.base_price) if room.room_type.base_price else 0.0,
- "capacity": room.room_type.capacity,
- "amenities": room.room_type.amenities if room.room_type.amenities else [],
- "images": []
- }
-
- return {
- "status": "success",
- "message": "Room created successfully",
- "data": {"room": room_dict}
- }
+ room_dict['room_type'] = {'id': room.room_type.id, 'name': room.room_type.name, 'description': room.room_type.description, 'base_price': float(room.room_type.base_price) if room.room_type.base_price else 0.0, 'capacity': room.room_type.capacity, 'amenities': room.room_type.amenities if room.room_type.amenities else [], 'images': []}
+ return {'status': 'success', 'message': 'Room created successfully', 'data': {'room': room_dict}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def update_room(
- id: int,
- room_data: dict,
- request: Request,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Update room (Admin only)"""
+@router.put('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def update_room(id: int, room_data: dict, request: Request, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
room = db.query(Room).filter(Room.id == id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- if room_data.get("room_type_id"):
- room_type = db.query(RoomType).filter(RoomType.id == room_data["room_type_id"]).first()
+ raise HTTPException(status_code=404, detail='Room not found')
+ if room_data.get('room_type_id'):
+ room_type = db.query(RoomType).filter(RoomType.id == room_data['room_type_id']).first()
if not room_type:
- raise HTTPException(status_code=404, detail="Room type not found")
-
- # Update fields
- if "room_type_id" in room_data:
- room.room_type_id = room_data["room_type_id"]
- if "room_number" in room_data:
- room.room_number = room_data["room_number"]
- if "floor" in room_data:
- room.floor = room_data["floor"]
- if "status" in room_data:
- room.status = RoomStatus(room_data["status"])
- if "featured" in room_data:
- room.featured = room_data["featured"]
- if "price" in room_data:
- room.price = room_data["price"]
- if "description" in room_data:
- room.description = room_data["description"]
- if "capacity" in room_data:
- room.capacity = room_data["capacity"]
- if "room_size" in room_data:
- room.room_size = room_data["room_size"]
- if "view" in room_data:
- room.view = room_data["view"]
- if "amenities" in room_data:
- # Ensure amenities is always a list
- amenities_value = room_data["amenities"]
+ raise HTTPException(status_code=404, detail='Room type not found')
+ if 'room_type_id' in room_data:
+ room.room_type_id = room_data['room_type_id']
+ if 'room_number' in room_data:
+ room.room_number = room_data['room_number']
+ if 'floor' in room_data:
+ room.floor = room_data['floor']
+ if 'status' in room_data:
+ room.status = RoomStatus(room_data['status'])
+ if 'featured' in room_data:
+ room.featured = room_data['featured']
+ if 'price' in room_data:
+ room.price = room_data['price']
+ if 'description' in room_data:
+ room.description = room_data['description']
+ if 'capacity' in room_data:
+ room.capacity = room_data['capacity']
+ if 'room_size' in room_data:
+ room.room_size = room_data['room_size']
+ if 'view' in room_data:
+ room.view = room_data['view']
+ if 'amenities' in room_data:
+ amenities_value = room_data['amenities']
if amenities_value is None:
room.amenities = []
elif isinstance(amenities_value, list):
room.amenities = amenities_value
else:
room.amenities = []
-
db.commit()
db.refresh(room)
-
- # Get base URL for proper response
base_url = get_base_url(request)
-
- # Serialize room data similar to get_room_by_id
- room_dict = {
- "id": room.id,
- "room_type_id": room.room_type_id,
- "room_number": room.room_number,
- "floor": room.floor,
- "status": room.status.value if isinstance(room.status, RoomStatus) else room.status,
- "price": float(room.price) if room.price is not None and room.price > 0 else None,
- "featured": room.featured,
- "description": room.description,
- "capacity": room.capacity,
- "room_size": room.room_size,
- "view": room.view,
- "amenities": room.amenities if room.amenities else [],
- "created_at": room.created_at.isoformat() if room.created_at else None,
- "updated_at": room.updated_at.isoformat() if room.updated_at else None,
- }
-
- # Normalize images
+ room_dict = {'id': room.id, 'room_type_id': room.room_type_id, 'room_number': room.room_number, 'floor': room.floor, 'status': room.status.value if isinstance(room.status, RoomStatus) else room.status, 'price': float(room.price) if room.price is not None and room.price > 0 else None, 'featured': room.featured, 'description': room.description, 'capacity': room.capacity, 'room_size': room.room_size, 'view': room.view, 'amenities': room.amenities if room.amenities else [], 'created_at': room.created_at.isoformat() if room.created_at else None, 'updated_at': room.updated_at.isoformat() if room.updated_at else None}
try:
- room_dict["images"] = normalize_images(room.images, base_url)
+ room_dict['images'] = normalize_images(room.images, base_url)
except:
- room_dict["images"] = []
-
- # Add room type info
+ room_dict['images'] = []
if room.room_type:
- room_dict["room_type"] = {
- "id": room.room_type.id,
- "name": room.room_type.name,
- "description": room.room_type.description,
- "base_price": float(room.room_type.base_price) if room.room_type.base_price else 0.0,
- "capacity": room.room_type.capacity,
- "amenities": room.room_type.amenities if room.room_type.amenities else [],
- "images": []
- }
-
- return {
- "status": "success",
- "message": "Room updated successfully",
- "data": {"room": room_dict}
- }
+ room_dict['room_type'] = {'id': room.room_type.id, 'name': room.room_type.name, 'description': room.room_type.description, 'base_price': float(room.room_type.base_price) if room.room_type.base_price else 0.0, 'capacity': room.room_type.capacity, 'amenities': room.room_type.amenities if room.room_type.amenities else [], 'images': []}
+ return {'status': 'success', 'message': 'Room updated successfully', 'data': {'room': room_dict}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def delete_room(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Delete room (Admin only)"""
+@router.delete('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def delete_room(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
room = db.query(Room).filter(Room.id == id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
+ raise HTTPException(status_code=404, detail='Room not found')
db.delete(room)
db.commit()
-
- return {
- "status": "success",
- "message": "Room deleted successfully"
- }
+ return {'status': 'success', 'message': 'Room deleted successfully'}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/bulk-delete", dependencies=[Depends(authorize_roles("admin"))])
-async def bulk_delete_rooms(
- room_ids: dict,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Bulk delete rooms (Admin only)"""
+@router.post('/bulk-delete', dependencies=[Depends(authorize_roles('admin'))])
+async def bulk_delete_rooms(room_ids: dict, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
- ids = room_ids.get("ids", [])
+ ids = room_ids.get('ids', [])
if not ids or not isinstance(ids, list):
- raise HTTPException(status_code=400, detail="Invalid room IDs provided")
-
+ raise HTTPException(status_code=400, detail='Invalid room IDs provided')
if len(ids) == 0:
- raise HTTPException(status_code=400, detail="No room IDs provided")
-
- # Validate all IDs are integers
+ raise HTTPException(status_code=400, detail='No room IDs provided')
try:
ids = [int(id) for id in ids]
except (ValueError, TypeError):
- raise HTTPException(status_code=400, detail="All room IDs must be integers")
-
- # Check if all rooms exist
+ raise HTTPException(status_code=400, detail='All room IDs must be integers')
rooms = db.query(Room).filter(Room.id.in_(ids)).all()
found_ids = [room.id for room in rooms]
not_found_ids = [id for id in ids if id not in found_ids]
-
if not_found_ids:
- raise HTTPException(
- status_code=404,
- detail=f"Rooms with IDs {not_found_ids} not found"
- )
-
- # Delete all rooms
+ raise HTTPException(status_code=404, detail=f'Rooms with IDs {not_found_ids} not found')
deleted_count = db.query(Room).filter(Room.id.in_(ids)).delete(synchronize_session=False)
db.commit()
-
- return {
- "status": "success",
- "message": f"Successfully deleted {deleted_count} room(s)",
- "data": {
- "deleted_count": deleted_count,
- "deleted_ids": ids
- }
- }
+ return {'status': 'success', 'message': f'Successfully deleted {deleted_count} room(s)', 'data': {'deleted_count': deleted_count, 'deleted_ids': ids}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/{id}/images", dependencies=[Depends(authorize_roles("admin", "staff"))])
-async def upload_room_images(
- id: int,
- images: List[UploadFile] = File(...),
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Upload room images (Admin/Staff only)"""
+@router.post('/{id}/images', dependencies=[Depends(authorize_roles('admin', 'staff'))])
+async def upload_room_images(id: int, images: List[UploadFile]=File(...), current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
room = db.query(Room).filter(Room.id == id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Create uploads directory
- upload_dir = Path(__file__).parent.parent.parent / "uploads" / "rooms"
+ raise HTTPException(status_code=404, detail='Room not found')
+ upload_dir = Path(__file__).parent.parent.parent / 'uploads' / 'rooms'
upload_dir.mkdir(parents=True, exist_ok=True)
-
image_urls = []
for image in images:
- # Validate file type
if not image.content_type or not image.content_type.startswith('image/'):
continue
-
- # Validate filename
if not image.filename:
continue
-
- # Generate filename
import uuid
ext = Path(image.filename).suffix or '.jpg'
- filename = f"room-{uuid.uuid4()}{ext}"
+ filename = f'room-{uuid.uuid4()}{ext}'
file_path = upload_dir / filename
-
- # Save file
async with aiofiles.open(file_path, 'wb') as f:
content = await image.read()
if not content:
continue
await f.write(content)
-
- image_urls.append(f"/uploads/rooms/{filename}")
-
- # Update room images (images are stored on Room, not RoomType)
+ image_urls.append(f'/uploads/rooms/{filename}')
existing_images = room.images or []
updated_images = existing_images + image_urls
room.images = updated_images
db.commit()
-
- return {
- "success": True,
- "status": "success",
- "message": "Images uploaded successfully",
- "data": {"images": updated_images}
- }
+ return {'success': True, 'status': 'success', 'message': 'Images uploaded successfully', 'data': {'images': updated_images}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{id}/images", dependencies=[Depends(authorize_roles("admin", "staff"))])
-async def delete_room_images(
- id: int,
- image_url: str = Query(..., description="Image URL or path to delete"),
- current_user: User = Depends(authorize_roles("admin", "staff")),
- db: Session = Depends(get_db)
-):
- """Delete room images (Admin/Staff only)"""
+@router.delete('/{id}/images', dependencies=[Depends(authorize_roles('admin', 'staff'))])
+async def delete_room_images(id: int, image_url: str=Query(..., description='Image URL or path to delete'), current_user: User=Depends(authorize_roles('admin', 'staff')), db: Session=Depends(get_db)):
try:
room = db.query(Room).filter(Room.id == id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Normalize the incoming image_url to extract the path
- # Handle both full URLs and relative paths
+ raise HTTPException(status_code=404, detail='Room not found')
normalized_url = image_url
if image_url.startswith('http://') or image_url.startswith('https://'):
- # Extract path from URL
from urllib.parse import urlparse
parsed = urlparse(image_url)
normalized_url = parsed.path
-
- # Normalize paths for comparison (ensure leading slash)
if not normalized_url.startswith('/'):
- normalized_url = f"/{normalized_url}"
-
- # Get filename from normalized path
+ normalized_url = f'/{normalized_url}'
filename = Path(normalized_url).name
-
- # Update room images - compare by filename or full path
existing_images = room.images or []
updated_images = []
-
for img in existing_images:
- # Normalize stored image path
- stored_path = img if img.startswith('/') else f"/{img}"
+ stored_path = img if img.startswith('/') else f'/{img}'
stored_filename = Path(stored_path).name
-
- # Compare by filename or full path
- # Keep images that don't match
- if (img != normalized_url and
- stored_path != normalized_url and
- stored_filename != filename):
+ if img != normalized_url and stored_path != normalized_url and (stored_filename != filename):
updated_images.append(img)
-
- # Delete file from disk
- file_path = Path(__file__).parent.parent.parent / "uploads" / "rooms" / filename
+ file_path = Path(__file__).parent.parent.parent / 'uploads' / 'rooms' / filename
if file_path.exists():
file_path.unlink()
-
room.images = updated_images
db.commit()
-
- return {
- "status": "success",
- "message": "Image deleted successfully",
- "data": {"images": updated_images}
- }
+ return {'status': 'success', 'message': 'Image deleted successfully', 'data': {'images': updated_images}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{id}/booked-dates")
-async def get_room_booked_dates(
- id: int,
- db: Session = Depends(get_db)
-):
- """Get all booked dates for a specific room"""
+@router.get('/{id}/booked-dates')
+async def get_room_booked_dates(id: int, db: Session=Depends(get_db)):
try:
- # Check if room exists
room = db.query(Room).filter(Room.id == id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- # Get all non-cancelled bookings for this room
- bookings = db.query(Booking).filter(
- and_(
- Booking.room_id == id,
- Booking.status != BookingStatus.cancelled
- )
- ).all()
-
- # Generate list of all booked dates
+ raise HTTPException(status_code=404, detail='Room not found')
+ bookings = db.query(Booking).filter(and_(Booking.room_id == id, Booking.status != BookingStatus.cancelled)).all()
booked_dates = []
for booking in bookings:
- # Parse dates
check_in = booking.check_in_date
check_out = booking.check_out_date
-
- # Generate all dates between check-in and check-out (exclusive of check-out)
current_date = check_in.date()
end_date = check_out.date()
-
while current_date < end_date:
booked_dates.append(current_date.isoformat())
- # Move to next day
from datetime import timedelta
current_date += timedelta(days=1)
-
- # Remove duplicates and sort
booked_dates = sorted(list(set(booked_dates)))
-
- return {
- "status": "success",
- "data": {
- "room_id": id,
- "booked_dates": booked_dates
- }
- }
+ return {'status': 'success', 'data': {'room_id': id, 'booked_dates': booked_dates}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{id}/reviews")
-async def get_room_reviews_route(
- id: int,
- db: Session = Depends(get_db)
-):
- """Get reviews for a specific room"""
+@router.get('/{id}/reviews')
+async def get_room_reviews_route(id: int, db: Session=Depends(get_db)):
from ..models.review import Review, ReviewStatus
try:
room = db.query(Room).filter(Room.id == id).first()
if not room:
- raise HTTPException(status_code=404, detail="Room not found")
-
- reviews = db.query(Review).filter(
- Review.room_id == id,
- Review.status == ReviewStatus.approved
- ).order_by(Review.created_at.desc()).all()
-
+ raise HTTPException(status_code=404, detail='Room not found')
+ reviews = db.query(Review).filter(Review.room_id == id, Review.status == ReviewStatus.approved).order_by(Review.created_at.desc()).all()
result = []
for review in reviews:
- review_dict = {
- "id": review.id,
- "user_id": review.user_id,
- "room_id": review.room_id,
- "rating": review.rating,
- "comment": review.comment,
- "status": review.status.value if isinstance(review.status, ReviewStatus) else review.status,
- "created_at": review.created_at.isoformat() if review.created_at else None,
- }
+ review_dict = {'id': review.id, 'user_id': review.user_id, 'room_id': review.room_id, 'rating': review.rating, 'comment': review.comment, 'status': review.status.value if isinstance(review.status, ReviewStatus) else review.status, 'created_at': review.created_at.isoformat() if review.created_at else None}
if review.user:
- review_dict["user"] = {
- "id": review.user.id,
- "full_name": review.user.full_name,
- "email": review.user.email,
- }
+ review_dict['user'] = {'id': review.user.id, 'full_name': review.user.full_name, 'email': review.user.email}
result.append(review_dict)
-
- return {
- "status": "success",
- "data": {"reviews": result}
- }
+ return {'status': 'success', 'data': {'reviews': result}}
except HTTPException:
raise
except Exception as e:
- raise HTTPException(status_code=500, detail=str(e))
-
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/service_booking_routes.py b/Backend/src/routes/service_booking_routes.py
index c50f8d68..2d66de0b 100644
--- a/Backend/src/routes/service_booking_routes.py
+++ b/Backend/src/routes/service_booking_routes.py
@@ -21,22 +21,18 @@ from ..config.settings import settings
router = APIRouter(prefix="/service-bookings", tags=["service-bookings"])
-
def generate_service_booking_number() -> str:
- """Generate unique service booking number"""
prefix = "SB"
timestamp = datetime.utcnow().strftime("%Y%m%d")
random_suffix = random.randint(1000, 9999)
return f"{prefix}{timestamp}{random_suffix}"
-
@router.post("/")
async def create_service_booking(
booking_data: dict,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
- """Create a new service booking"""
try:
services = booking_data.get("services", [])
total_amount = float(booking_data.get("total_amount", 0))
@@ -48,7 +44,7 @@ async def create_service_booking(
if total_amount <= 0:
raise HTTPException(status_code=400, detail="Total amount must be greater than 0")
- # Validate services and calculate total
+
calculated_total = 0
service_items_data = []
@@ -59,7 +55,7 @@ async def create_service_booking(
if not service_id:
raise HTTPException(status_code=400, detail="Service ID is required for each item")
- # Check if service exists and is active
+
service = db.query(Service).filter(Service.id == service_id).first()
if not service:
raise HTTPException(status_code=404, detail=f"Service with ID {service_id} not found")
@@ -78,17 +74,17 @@ async def create_service_booking(
"total_price": item_total
})
- # Verify calculated total matches provided total (with small tolerance for floating point)
+
if abs(calculated_total - total_amount) > 0.01:
raise HTTPException(
status_code=400,
detail=f"Total amount mismatch. Calculated: {calculated_total}, Provided: {total_amount}"
)
- # Generate booking number
+
booking_number = generate_service_booking_number()
- # Create service booking
+
service_booking = ServiceBooking(
booking_number=booking_number,
user_id=current_user.id,
@@ -98,9 +94,9 @@ async def create_service_booking(
)
db.add(service_booking)
- db.flush() # Flush to get the ID
+ db.flush()
- # Create service booking items
+
for item_data in service_items_data:
booking_item = ServiceBookingItem(
service_booking_id=service_booking.id,
@@ -114,12 +110,12 @@ async def create_service_booking(
db.commit()
db.refresh(service_booking)
- # Load relationships
+
service_booking = db.query(ServiceBooking).options(
joinedload(ServiceBooking.service_items).joinedload(ServiceBookingItem.service)
).filter(ServiceBooking.id == service_booking.id).first()
- # Format response
+
booking_dict = {
"id": service_booking.id,
"booking_number": service_booking.booking_number,
@@ -157,13 +153,11 @@ async def create_service_booking(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/me")
async def get_my_service_bookings(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
- """Get all service bookings for current user"""
try:
bookings = db.query(ServiceBooking).options(
joinedload(ServiceBooking.service_items).joinedload(ServiceBookingItem.service)
@@ -204,14 +198,12 @@ async def get_my_service_bookings(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/{id}")
async def get_service_booking_by_id(
id: int,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
- """Get service booking by ID"""
try:
booking = db.query(ServiceBooking).options(
joinedload(ServiceBooking.service_items).joinedload(ServiceBookingItem.service)
@@ -220,7 +212,7 @@ async def get_service_booking_by_id(
if not booking:
raise HTTPException(status_code=404, detail="Service booking not found")
- # Check access
+
if booking.user_id != current_user.id and current_user.role_id != 1:
raise HTTPException(status_code=403, detail="Forbidden")
@@ -259,7 +251,6 @@ async def get_service_booking_by_id(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.post("/{id}/payment/stripe/create-intent")
async def create_service_stripe_payment_intent(
id: int,
@@ -267,9 +258,8 @@ async def create_service_stripe_payment_intent(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
- """Create Stripe payment intent for service booking"""
try:
- # Check if Stripe is configured
+
secret_key = get_stripe_secret_key(db)
if not secret_key:
secret_key = settings.STRIPE_SECRET_KEY
@@ -286,7 +276,7 @@ async def create_service_stripe_payment_intent(
if amount <= 0:
raise HTTPException(status_code=400, detail="Amount must be greater than 0")
- # Verify service booking exists and user has access
+
booking = db.query(ServiceBooking).filter(ServiceBooking.id == id).first()
if not booking:
raise HTTPException(status_code=404, detail="Service booking not found")
@@ -294,22 +284,22 @@ async def create_service_stripe_payment_intent(
if booking.user_id != current_user.id and current_user.role_id != 1:
raise HTTPException(status_code=403, detail="Forbidden")
- # Verify amount matches booking total
+
if abs(float(booking.total_amount) - amount) > 0.01:
raise HTTPException(
status_code=400,
detail=f"Amount mismatch. Booking total: {booking.total_amount}, Provided: {amount}"
)
- # Create payment intent
+
intent = StripeService.create_payment_intent(
amount=amount,
currency=currency,
- description=f"Service Booking #{booking.booking_number}",
+ description=f"Service Booking
db=db
)
- # Get publishable key
+
publishable_key = get_stripe_publishable_key(db)
if not publishable_key:
publishable_key = settings.STRIPE_PUBLISHABLE_KEY
@@ -333,7 +323,6 @@ async def create_service_stripe_payment_intent(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.post("/{id}/payment/stripe/confirm")
async def confirm_service_stripe_payment(
id: int,
@@ -341,14 +330,13 @@ async def confirm_service_stripe_payment(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
- """Confirm Stripe payment for service booking"""
try:
payment_intent_id = payment_data.get("payment_intent_id")
if not payment_intent_id:
raise HTTPException(status_code=400, detail="payment_intent_id is required")
- # Verify service booking exists and user has access
+
booking = db.query(ServiceBooking).filter(ServiceBooking.id == id).first()
if not booking:
raise HTTPException(status_code=404, detail="Service booking not found")
@@ -356,7 +344,7 @@ async def confirm_service_stripe_payment(
if booking.user_id != current_user.id and current_user.role_id != 1:
raise HTTPException(status_code=403, detail="Forbidden")
- # Retrieve and verify payment intent
+
intent_data = StripeService.retrieve_payment_intent(payment_intent_id, db)
if intent_data["status"] != "succeeded":
@@ -365,15 +353,15 @@ async def confirm_service_stripe_payment(
detail=f"Payment intent status is {intent_data['status']}, expected 'succeeded'"
)
- # Verify amount matches
- amount_paid = intent_data["amount"] / 100 # Convert from cents
+
+ amount_paid = intent_data["amount"] / 100
if abs(float(booking.total_amount) - amount_paid) > 0.01:
raise HTTPException(
status_code=400,
detail="Payment amount does not match booking total"
)
- # Create payment record
+
payment = ServicePayment(
service_booking_id=booking.id,
amount=booking.total_amount,
@@ -386,7 +374,7 @@ async def confirm_service_stripe_payment(
db.add(payment)
- # Update booking status
+
booking.status = ServiceBookingStatus.confirmed
db.commit()
diff --git a/Backend/src/routes/service_routes.py b/Backend/src/routes/service_routes.py
index 86f33871..d0ba3886 100644
--- a/Backend/src/routes/service_routes.py
+++ b/Backend/src/routes/service_routes.py
@@ -2,276 +2,133 @@ from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional
-
from ..config.database import get_db
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
from ..models.service import Service
from ..models.service_usage import ServiceUsage
from ..models.booking import Booking, BookingStatus
+router = APIRouter(prefix='/services', tags=['services'])
-router = APIRouter(prefix="/services", tags=["services"])
-
-
-@router.get("/")
-async def get_services(
- search: Optional[str] = Query(None),
- status_filter: Optional[str] = Query(None, alias="status"),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- db: Session = Depends(get_db)
-):
- """Get all services with filters"""
+@router.get('/')
+async def get_services(search: Optional[str]=Query(None), status_filter: Optional[str]=Query(None, alias='status'), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), db: Session=Depends(get_db)):
try:
query = db.query(Service)
-
- # Filter by search (name or description)
if search:
- query = query.filter(
- or_(
- Service.name.like(f"%{search}%"),
- Service.description.like(f"%{search}%")
- )
- )
-
- # Filter by status (is_active)
+ query = query.filter(or_(Service.name.like(f'%{search}%'), Service.description.like(f'%{search}%')))
if status_filter:
- is_active = status_filter == "active"
+ is_active = status_filter == 'active'
query = query.filter(Service.is_active == is_active)
-
total = query.count()
offset = (page - 1) * limit
services = query.order_by(Service.created_at.desc()).offset(offset).limit(limit).all()
-
result = []
for service in services:
- service_dict = {
- "id": service.id,
- "name": service.name,
- "description": service.description,
- "price": float(service.price) if service.price else 0.0,
- "category": service.category,
- "is_active": service.is_active,
- "created_at": service.created_at.isoformat() if service.created_at else None,
- }
+ service_dict = {'id': service.id, 'name': service.name, 'description': service.description, 'price': float(service.price) if service.price else 0.0, 'category': service.category, 'is_active': service.is_active, 'created_at': service.created_at.isoformat() if service.created_at else None}
result.append(service_dict)
-
- return {
- "status": "success",
- "data": {
- "services": result,
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'services': result, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{id}")
-async def get_service_by_id(id: int, db: Session = Depends(get_db)):
- """Get service by ID"""
+@router.get('/{id}')
+async def get_service_by_id(id: int, db: Session=Depends(get_db)):
try:
service = db.query(Service).filter(Service.id == id).first()
if not service:
- raise HTTPException(status_code=404, detail="Service not found")
-
- service_dict = {
- "id": service.id,
- "name": service.name,
- "description": service.description,
- "price": float(service.price) if service.price else 0.0,
- "category": service.category,
- "is_active": service.is_active,
- "created_at": service.created_at.isoformat() if service.created_at else None,
- }
-
- return {
- "status": "success",
- "data": {"service": service_dict}
- }
+ raise HTTPException(status_code=404, detail='Service not found')
+ service_dict = {'id': service.id, 'name': service.name, 'description': service.description, 'price': float(service.price) if service.price else 0.0, 'category': service.category, 'is_active': service.is_active, 'created_at': service.created_at.isoformat() if service.created_at else None}
+ return {'status': 'success', 'data': {'service': service_dict}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/", dependencies=[Depends(authorize_roles("admin"))])
-async def create_service(
- service_data: dict,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Create new service (Admin only)"""
+@router.post('/', dependencies=[Depends(authorize_roles('admin'))])
+async def create_service(service_data: dict, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
- name = service_data.get("name")
-
- # Check if name exists
+ name = service_data.get('name')
existing = db.query(Service).filter(Service.name == name).first()
if existing:
- raise HTTPException(status_code=400, detail="Service name already exists")
-
- service = Service(
- name=name,
- description=service_data.get("description"),
- price=float(service_data.get("price", 0)),
- category=service_data.get("category"),
- is_active=service_data.get("status") == "active" if service_data.get("status") else True,
- )
-
+ raise HTTPException(status_code=400, detail='Service name already exists')
+ service = Service(name=name, description=service_data.get('description'), price=float(service_data.get('price', 0)), category=service_data.get('category'), is_active=service_data.get('status') == 'active' if service_data.get('status') else True)
db.add(service)
db.commit()
db.refresh(service)
-
- return {
- "status": "success",
- "message": "Service created successfully",
- "data": {"service": service}
- }
+ return {'status': 'success', 'message': 'Service created successfully', 'data': {'service': service}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def update_service(
- id: int,
- service_data: dict,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Update service (Admin only)"""
+@router.put('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def update_service(id: int, service_data: dict, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
service = db.query(Service).filter(Service.id == id).first()
if not service:
- raise HTTPException(status_code=404, detail="Service not found")
-
- # Check if new name exists (excluding current)
- name = service_data.get("name")
+ raise HTTPException(status_code=404, detail='Service not found')
+ name = service_data.get('name')
if name and name != service.name:
- existing = db.query(Service).filter(
- Service.name == name,
- Service.id != id
- ).first()
+ existing = db.query(Service).filter(Service.name == name, Service.id != id).first()
if existing:
- raise HTTPException(status_code=400, detail="Service name already exists")
-
- # Update fields
- if "name" in service_data:
- service.name = service_data["name"]
- if "description" in service_data:
- service.description = service_data["description"]
- if "price" in service_data:
- service.price = float(service_data["price"])
- if "category" in service_data:
- service.category = service_data["category"]
- if "status" in service_data:
- service.is_active = service_data["status"] == "active"
-
+ raise HTTPException(status_code=400, detail='Service name already exists')
+ if 'name' in service_data:
+ service.name = service_data['name']
+ if 'description' in service_data:
+ service.description = service_data['description']
+ if 'price' in service_data:
+ service.price = float(service_data['price'])
+ if 'category' in service_data:
+ service.category = service_data['category']
+ if 'status' in service_data:
+ service.is_active = service_data['status'] == 'active'
db.commit()
db.refresh(service)
-
- return {
- "status": "success",
- "message": "Service updated successfully",
- "data": {"service": service}
- }
+ return {'status': 'success', 'message': 'Service updated successfully', 'data': {'service': service}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def delete_service(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Delete service (Admin only)"""
+@router.delete('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def delete_service(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
service = db.query(Service).filter(Service.id == id).first()
if not service:
- raise HTTPException(status_code=404, detail="Service not found")
-
- # Check if service is used in active bookings
- active_usage = db.query(ServiceUsage).join(Booking).filter(
- ServiceUsage.service_id == id,
- Booking.status.in_([BookingStatus.pending, BookingStatus.confirmed, BookingStatus.checked_in])
- ).count()
-
+ raise HTTPException(status_code=404, detail='Service not found')
+ active_usage = db.query(ServiceUsage).join(Booking).filter(ServiceUsage.service_id == id, Booking.status.in_([BookingStatus.pending, BookingStatus.confirmed, BookingStatus.checked_in])).count()
if active_usage > 0:
- raise HTTPException(
- status_code=400,
- detail="Cannot delete service that is used in active bookings"
- )
-
+ raise HTTPException(status_code=400, detail='Cannot delete service that is used in active bookings')
db.delete(service)
db.commit()
-
- return {
- "status": "success",
- "message": "Service deleted successfully"
- }
+ return {'status': 'success', 'message': 'Service deleted successfully'}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/use")
-async def use_service(
- usage_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Add service to booking"""
+@router.post('/use')
+async def use_service(usage_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- booking_id = usage_data.get("booking_id")
- service_id = usage_data.get("service_id")
- quantity = usage_data.get("quantity", 1)
-
- # Check if booking exists
+ booking_id = usage_data.get('booking_id')
+ service_id = usage_data.get('service_id')
+ quantity = usage_data.get('quantity', 1)
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise HTTPException(status_code=404, detail="Booking not found")
-
- # Check if service exists and is active
+ raise HTTPException(status_code=404, detail='Booking not found')
service = db.query(Service).filter(Service.id == service_id).first()
if not service or not service.is_active:
- raise HTTPException(status_code=404, detail="Service not found or inactive")
-
- # Calculate total price
+ raise HTTPException(status_code=404, detail='Service not found or inactive')
total_price = float(service.price) * quantity
-
- # Create service usage
- service_usage = ServiceUsage(
- booking_id=booking_id,
- service_id=service_id,
- quantity=quantity,
- unit_price=service.price,
- total_price=total_price,
- )
-
+ service_usage = ServiceUsage(booking_id=booking_id, service_id=service_id, quantity=quantity, unit_price=service.price, total_price=total_price)
db.add(service_usage)
db.commit()
db.refresh(service_usage)
-
- return {
- "status": "success",
- "message": "Service added to booking successfully",
- "data": {"bookingService": service_usage}
- }
+ return {'status': 'success', 'message': 'Service added to booking successfully', 'data': {'bookingService': service_usage}}
except HTTPException:
raise
except Exception as e:
db.rollback()
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/routes/system_settings_routes.py b/Backend/src/routes/system_settings_routes.py
index bb87387b..b56b4513 100644
--- a/Backend/src/routes/system_settings_routes.py
+++ b/Backend/src/routes/system_settings_routes.py
@@ -16,9 +16,7 @@ from ..models.system_settings import SystemSettings
from ..utils.mailer import send_email
from ..services.room_service import get_base_url
-
def normalize_image_url(image_url: str, base_url: str) -> str:
- """Normalize image URL to absolute URL"""
if not image_url:
return image_url
if image_url.startswith('http://') or image_url.startswith('https://'):
@@ -31,19 +29,17 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/admin/system-settings", tags=["admin-system-settings"])
-
@router.get("/currency")
async def get_platform_currency(
db: Session = Depends(get_db)
):
- """Get platform currency setting (public endpoint for frontend)"""
try:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "platform_currency"
).first()
if not setting:
- # Default to VND if not set
+
return {
"status": "success",
"data": {
@@ -64,25 +60,23 @@ async def get_platform_currency(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.put("/currency")
async def update_platform_currency(
currency_data: dict,
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Update platform currency (Admin only)"""
try:
currency = currency_data.get("currency", "").upper()
- # Validate currency code
+
if not currency or len(currency) != 3 or not currency.isalpha():
raise HTTPException(
status_code=400,
detail="Invalid currency code. Must be a 3-letter ISO 4217 code (e.g., USD, EUR, VND)"
)
- # Get or create setting
+
setting = db.query(SystemSettings).filter(
SystemSettings.key == "platform_currency"
).first()
@@ -117,13 +111,11 @@ async def update_platform_currency(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/")
async def get_all_settings(
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Get all system settings (Admin only)"""
try:
settings = db.query(SystemSettings).all()
@@ -146,13 +138,11 @@ async def get_all_settings(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/stripe")
async def get_stripe_settings(
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Get Stripe payment settings (Admin only)"""
try:
secret_key_setting = db.query(SystemSettings).filter(
SystemSettings.key == "stripe_secret_key"
@@ -166,7 +156,7 @@ async def get_stripe_settings(
SystemSettings.key == "stripe_webhook_secret"
).first()
- # Mask secret keys for security (only show last 4 characters)
+
def mask_key(key_value: str) -> str:
if not key_value or len(key_value) < 4:
return ""
@@ -206,41 +196,39 @@ async def get_stripe_settings(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.put("/stripe")
async def update_stripe_settings(
stripe_data: dict,
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Update Stripe payment settings (Admin only)"""
try:
secret_key = stripe_data.get("stripe_secret_key", "").strip()
publishable_key = stripe_data.get("stripe_publishable_key", "").strip()
webhook_secret = stripe_data.get("stripe_webhook_secret", "").strip()
- # Validate secret key format (should start with sk_)
+
if secret_key and not secret_key.startswith("sk_"):
raise HTTPException(
status_code=400,
detail="Invalid Stripe secret key format. Must start with 'sk_'"
)
- # Validate publishable key format (should start with pk_)
+
if publishable_key and not publishable_key.startswith("pk_"):
raise HTTPException(
status_code=400,
detail="Invalid Stripe publishable key format. Must start with 'pk_'"
)
- # Validate webhook secret format (should start with whsec_)
+
if webhook_secret and not webhook_secret.startswith("whsec_"):
raise HTTPException(
status_code=400,
detail="Invalid Stripe webhook secret format. Must start with 'whsec_'"
)
- # Update or create secret key setting
+
if secret_key:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "stripe_secret_key"
@@ -258,7 +246,7 @@ async def update_stripe_settings(
)
db.add(setting)
- # Update or create publishable key setting
+
if publishable_key:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "stripe_publishable_key"
@@ -276,7 +264,7 @@ async def update_stripe_settings(
)
db.add(setting)
- # Update or create webhook secret setting
+
if webhook_secret:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "stripe_webhook_secret"
@@ -296,7 +284,7 @@ async def update_stripe_settings(
db.commit()
- # Return masked values
+
def mask_key(key_value: str) -> str:
if not key_value or len(key_value) < 4:
return ""
@@ -322,13 +310,11 @@ async def update_stripe_settings(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/paypal")
async def get_paypal_settings(
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Get PayPal payment settings (Admin only)"""
try:
client_id_setting = db.query(SystemSettings).filter(
SystemSettings.key == "paypal_client_id"
@@ -342,7 +328,7 @@ async def get_paypal_settings(
SystemSettings.key == "paypal_mode"
).first()
- # Mask secret for security (only show last 4 characters)
+
def mask_key(key_value: str) -> str:
if not key_value or len(key_value) < 4:
return ""
@@ -378,27 +364,25 @@ async def get_paypal_settings(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.put("/paypal")
async def update_paypal_settings(
paypal_data: dict,
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Update PayPal payment settings (Admin only)"""
try:
client_id = paypal_data.get("paypal_client_id", "").strip()
client_secret = paypal_data.get("paypal_client_secret", "").strip()
mode = paypal_data.get("paypal_mode", "sandbox").strip().lower()
- # Validate mode
+
if mode and mode not in ["sandbox", "live"]:
raise HTTPException(
status_code=400,
detail="Invalid PayPal mode. Must be 'sandbox' or 'live'"
)
- # Update or create client ID setting
+
if client_id:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "paypal_client_id"
@@ -416,7 +400,7 @@ async def update_paypal_settings(
)
db.add(setting)
- # Update or create client secret setting
+
if client_secret:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "paypal_client_secret"
@@ -434,7 +418,7 @@ async def update_paypal_settings(
)
db.add(setting)
- # Update or create mode setting
+
if mode:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "paypal_mode"
@@ -454,7 +438,7 @@ async def update_paypal_settings(
db.commit()
- # Return masked values
+
def mask_key(key_value: str) -> str:
if not key_value or len(key_value) < 4:
return ""
@@ -478,15 +462,13 @@ async def update_paypal_settings(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/smtp")
async def get_smtp_settings(
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Get SMTP email server settings (Admin only)"""
try:
- # Get all SMTP settings
+
smtp_settings = {}
setting_keys = [
"smtp_host",
@@ -505,7 +487,7 @@ async def get_smtp_settings(
if setting:
smtp_settings[key] = setting.value
- # Mask password for security (only show last 4 characters if set)
+
def mask_password(password_value: str) -> str:
if not password_value or len(password_value) < 4:
return ""
@@ -525,7 +507,7 @@ async def get_smtp_settings(
"has_password": bool(smtp_settings.get("smtp_password")),
}
- # Get updated_at and updated_by from any setting (prefer password setting if exists)
+
password_setting = db.query(SystemSettings).filter(
SystemSettings.key == "smtp_password"
).first()
@@ -534,7 +516,7 @@ async def get_smtp_settings(
result["updated_at"] = password_setting.updated_at.isoformat() if password_setting.updated_at else None
result["updated_by"] = password_setting.updated_by.full_name if password_setting.updated_by else None
else:
- # Try to get from any other SMTP setting
+
any_setting = db.query(SystemSettings).filter(
SystemSettings.key.in_(setting_keys)
).first()
@@ -552,14 +534,12 @@ async def get_smtp_settings(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.put("/smtp")
async def update_smtp_settings(
smtp_data: dict,
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Update SMTP email server settings (Admin only)"""
try:
smtp_host = smtp_data.get("smtp_host", "").strip()
smtp_port = smtp_data.get("smtp_port", "").strip()
@@ -569,7 +549,7 @@ async def update_smtp_settings(
smtp_from_name = smtp_data.get("smtp_from_name", "").strip()
smtp_use_tls = smtp_data.get("smtp_use_tls", True)
- # Validate required fields if provided
+
if smtp_host and not smtp_host:
raise HTTPException(
status_code=400,
@@ -591,14 +571,14 @@ async def update_smtp_settings(
)
if smtp_from_email:
- # Basic email validation
+
if "@" not in smtp_from_email or "." not in smtp_from_email.split("@")[1]:
raise HTTPException(
status_code=400,
detail="Invalid email address format for 'From Email'"
)
- # Helper function to update or create setting
+
def update_setting(key: str, value: str, description: str):
setting = db.query(SystemSettings).filter(
SystemSettings.key == key
@@ -616,7 +596,7 @@ async def update_smtp_settings(
)
db.add(setting)
- # Update or create settings (only update if value is provided)
+
if smtp_host:
update_setting(
"smtp_host",
@@ -659,7 +639,7 @@ async def update_smtp_settings(
"Default 'From' name for outgoing emails"
)
- # Update TLS setting (convert boolean to string)
+
if smtp_use_tls is not None:
update_setting(
"smtp_use_tls",
@@ -669,13 +649,13 @@ async def update_smtp_settings(
db.commit()
- # Return updated settings with masked password
+
def mask_password(password_value: str) -> str:
if not password_value or len(password_value) < 4:
return ""
return "*" * (len(password_value) - 4) + password_value[-4:]
- # Get updated settings
+
updated_settings = {}
for key in ["smtp_host", "smtp_port", "smtp_user", "smtp_password", "smtp_from_email", "smtp_from_name", "smtp_use_tls"]:
setting = db.query(SystemSettings).filter(
@@ -698,7 +678,7 @@ async def update_smtp_settings(
"has_password": bool(updated_settings.get("smtp_password")),
}
- # Get updated_by from password setting if it exists
+
password_setting = db.query(SystemSettings).filter(
SystemSettings.key == "smtp_password"
).first()
@@ -717,131 +697,28 @@ async def update_smtp_settings(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
class TestEmailRequest(BaseModel):
email: EmailStr
-
@router.post("/smtp/test")
async def test_smtp_email(
request: TestEmailRequest,
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Send a test email to verify SMTP settings (Admin only)"""
try:
test_email = str(request.email)
admin_name = str(current_user.full_name or current_user.email or "Admin")
timestamp_str = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
- # Create test email HTML content
- test_html = f"""
-
-
-
-
-
-
-
-
-
✅ SMTP Test Email
-
-
-
-
🎉
-
Email Configuration Test Successful!
-
-
-
This is a test email sent from your Hotel Booking system to verify that the SMTP email settings are configured correctly.
-
-
- 📧 Test Details:
-
-
Recipient: {test_email}
-
Sent by: {admin_name}
-
Time: {timestamp_str}
-
-
-
-
If you received this email, it means your SMTP server settings are working correctly and the system can send emails through your configured email server.
-
-
What's next?
-
-
Welcome emails for new user registrations
-
Password reset emails
-
Booking confirmation emails
-
Payment notifications
-
And other system notifications
-
-
-
-
-
-
- """
+
+ test_html = f
- # Plain text version
- test_text = f"""
-SMTP Test Email
-This is a test email sent from your Hotel Booking system to verify that the SMTP email settings are configured correctly.
-
-Test Details:
-- Recipient: {test_email}
-- Sent by: {admin_name}
-- Time: {timestamp_str}
-
-If you received this email, it means your SMTP server settings are working correctly and the system can send emails through your configured email server.
-
-This is an automated test email from Hotel Booking System
-If you did not request this test, please ignore this email.
- """.strip()
+ test_text = f
+.strip()
- # Send the test email
+
await send_email(
to=test_email,
subject="SMTP Test Email - Hotel Booking System",
@@ -860,13 +737,13 @@ If you did not request this test, please ignore this email.
}
}
except HTTPException:
- # Re-raise HTTP exceptions (like validation errors from send_email)
+
raise
except Exception as e:
error_msg = str(e)
logger.error(f"Error sending test email: {type(e).__name__}: {error_msg}", exc_info=True)
- # Provide more user-friendly error messages
+
if "SMTP mailer not configured" in error_msg:
raise HTTPException(
status_code=400,
@@ -888,7 +765,6 @@ If you did not request this test, please ignore this email.
detail=f"Failed to send test email: {error_msg}"
)
-
class UpdateCompanySettingsRequest(BaseModel):
company_name: Optional[str] = None
company_tagline: Optional[str] = None
@@ -897,12 +773,10 @@ class UpdateCompanySettingsRequest(BaseModel):
company_address: Optional[str] = None
tax_rate: Optional[float] = None
-
@router.get("/company")
async def get_company_settings(
db: Session = Depends(get_db)
):
- """Get company settings (public endpoint for frontend)"""
try:
setting_keys = [
"company_name",
@@ -925,7 +799,7 @@ async def get_company_settings(
else:
settings_dict[key] = None
- # Get updated_at and updated_by from logo setting if exists
+
logo_setting = db.query(SystemSettings).filter(
SystemSettings.key == "company_logo_url"
).first()
@@ -954,14 +828,12 @@ async def get_company_settings(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.put("/company")
async def update_company_settings(
request_data: UpdateCompanySettingsRequest,
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Update company settings (Admin only)"""
try:
db_settings = {}
@@ -979,18 +851,18 @@ async def update_company_settings(
db_settings["tax_rate"] = str(request_data.tax_rate)
for key, value in db_settings.items():
- # Find or create setting
+
setting = db.query(SystemSettings).filter(
SystemSettings.key == key
).first()
if setting:
- # Update existing
+
setting.value = value if value else None
setting.updated_at = datetime.utcnow()
setting.updated_by_id = current_user.id
else:
- # Create new
+
setting = SystemSettings(
key=key,
value=value if value else None,
@@ -1000,7 +872,7 @@ async def update_company_settings(
db.commit()
- # Get updated settings
+
updated_settings = {}
for key in ["company_name", "company_tagline", "company_logo_url", "company_favicon_url", "company_phone", "company_email", "company_address", "tax_rate"]:
setting = db.query(SystemSettings).filter(
@@ -1011,7 +883,7 @@ async def update_company_settings(
else:
updated_settings[key] = None
- # Get updated_at and updated_by
+
logo_setting = db.query(SystemSettings).filter(
SystemSettings.key == "company_logo_url"
).first()
@@ -1048,7 +920,6 @@ async def update_company_settings(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
@router.post("/company/logo")
async def upload_company_logo(
request: Request,
@@ -1056,28 +927,27 @@ async def upload_company_logo(
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Upload company logo (Admin only)"""
try:
- # Validate file type
+
if not image.content_type or not image.content_type.startswith('image/'):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="File must be an image"
)
- # Validate file size (max 2MB)
+
content = await image.read()
- if len(content) > 2 * 1024 * 1024: # 2MB
+ if len(content) > 2 * 1024 * 1024:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Logo file size must be less than 2MB"
)
- # Create uploads directory
+
upload_dir = Path(__file__).parent.parent.parent / "uploads" / "company"
upload_dir.mkdir(parents=True, exist_ok=True)
- # Delete old logo if exists
+
old_logo_setting = db.query(SystemSettings).filter(
SystemSettings.key == "company_logo_url"
).first()
@@ -1090,20 +960,20 @@ async def upload_company_logo(
except Exception as e:
logger.warning(f"Could not delete old logo: {e}")
- # Generate filename
+
ext = Path(image.filename).suffix or '.png'
- # Always use logo.png to ensure we only have one logo
+
filename = "logo.png"
file_path = upload_dir / filename
- # Save file
+
async with aiofiles.open(file_path, 'wb') as f:
await f.write(content)
- # Store the URL in system_settings
+
image_url = f"/uploads/company/{filename}"
- # Update or create setting
+
logo_setting = db.query(SystemSettings).filter(
SystemSettings.key == "company_logo_url"
).first()
@@ -1122,7 +992,7 @@ async def upload_company_logo(
db.commit()
- # Return the image URL
+
base_url = get_base_url(request)
full_url = normalize_image_url(image_url, base_url)
@@ -1142,7 +1012,6 @@ async def upload_company_logo(
logger.error(f"Error uploading logo: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
-
@router.post("/company/favicon")
async def upload_company_favicon(
request: Request,
@@ -1150,9 +1019,8 @@ async def upload_company_favicon(
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Upload company favicon (Admin only)"""
try:
- # Validate file type (favicon can be ico, png, svg)
+
if not image.content_type:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -1161,7 +1029,7 @@ async def upload_company_favicon(
allowed_types = ['image/x-icon', 'image/vnd.microsoft.icon', 'image/png', 'image/svg+xml', 'image/ico']
if image.content_type not in allowed_types:
- # Check filename extension as fallback
+
filename_lower = (image.filename or '').lower()
if not any(filename_lower.endswith(ext) for ext in ['.ico', '.png', '.svg']):
raise HTTPException(
@@ -1169,19 +1037,19 @@ async def upload_company_favicon(
detail="Favicon must be .ico, .png, or .svg file"
)
- # Validate file size (max 500KB)
+
content = await image.read()
- if len(content) > 500 * 1024: # 500KB
+ if len(content) > 500 * 1024:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Favicon file size must be less than 500KB"
)
- # Create uploads directory
+
upload_dir = Path(__file__).parent.parent.parent / "uploads" / "company"
upload_dir.mkdir(parents=True, exist_ok=True)
- # Delete old favicon if exists
+
old_favicon_setting = db.query(SystemSettings).filter(
SystemSettings.key == "company_favicon_url"
).first()
@@ -1194,7 +1062,7 @@ async def upload_company_favicon(
except Exception as e:
logger.warning(f"Could not delete old favicon: {e}")
- # Generate filename - preserve extension but use standard name
+
filename_lower = (image.filename or '').lower()
if filename_lower.endswith('.ico'):
filename = "favicon.ico"
@@ -1205,14 +1073,14 @@ async def upload_company_favicon(
file_path = upload_dir / filename
- # Save file
+
async with aiofiles.open(file_path, 'wb') as f:
await f.write(content)
- # Store the URL in system_settings
+
image_url = f"/uploads/company/{filename}"
- # Update or create setting
+
favicon_setting = db.query(SystemSettings).filter(
SystemSettings.key == "company_favicon_url"
).first()
@@ -1231,7 +1099,7 @@ async def upload_company_favicon(
db.commit()
- # Return the image URL
+
base_url = get_base_url(request)
full_url = normalize_image_url(image_url, base_url)
@@ -1251,12 +1119,10 @@ async def upload_company_favicon(
logger.error(f"Error uploading favicon: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/recaptcha")
async def get_recaptcha_settings(
db: Session = Depends(get_db)
):
- """Get reCAPTCHA settings (Public endpoint for frontend)"""
try:
site_key_setting = db.query(SystemSettings).filter(
SystemSettings.key == "recaptcha_site_key"
@@ -1284,13 +1150,11 @@ async def get_recaptcha_settings(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.get("/recaptcha/admin")
async def get_recaptcha_settings_admin(
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Get reCAPTCHA settings (Admin only - includes secret key)"""
try:
site_key_setting = db.query(SystemSettings).filter(
SystemSettings.key == "recaptcha_site_key"
@@ -1304,7 +1168,7 @@ async def get_recaptcha_settings_admin(
SystemSettings.key == "recaptcha_enabled"
).first()
- # Mask secret for security (only show last 4 characters)
+
def mask_key(key_value: str) -> str:
if not key_value or len(key_value) < 4:
return ""
@@ -1340,20 +1204,18 @@ async def get_recaptcha_settings_admin(
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
@router.put("/recaptcha")
async def update_recaptcha_settings(
recaptcha_data: dict,
current_user: User = Depends(authorize_roles("admin")),
db: Session = Depends(get_db)
):
- """Update reCAPTCHA settings (Admin only)"""
try:
site_key = recaptcha_data.get("recaptcha_site_key", "").strip()
secret_key = recaptcha_data.get("recaptcha_secret_key", "").strip()
enabled = recaptcha_data.get("recaptcha_enabled", False)
- # Update or create site key setting
+
if site_key:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "recaptcha_site_key"
@@ -1371,7 +1233,7 @@ async def update_recaptcha_settings(
)
db.add(setting)
- # Update or create secret key setting
+
if secret_key:
setting = db.query(SystemSettings).filter(
SystemSettings.key == "recaptcha_secret_key"
@@ -1389,7 +1251,7 @@ async def update_recaptcha_settings(
)
db.add(setting)
- # Update or create enabled setting
+
setting = db.query(SystemSettings).filter(
SystemSettings.key == "recaptcha_enabled"
).first()
@@ -1408,7 +1270,7 @@ async def update_recaptcha_settings(
db.commit()
- # Return masked values
+
def mask_key(key_value: str) -> str:
if not key_value or len(key_value) < 4:
return ""
@@ -1432,13 +1294,11 @@ async def update_recaptcha_settings(
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
@router.post("/recaptcha/verify")
async def verify_recaptcha(
verification_data: dict,
db: Session = Depends(get_db)
):
- """Verify reCAPTCHA token (Public endpoint)"""
try:
token = verification_data.get("token", "").strip()
@@ -1448,7 +1308,7 @@ async def verify_recaptcha(
detail="reCAPTCHA token is required"
)
- # Get reCAPTCHA settings
+
enabled_setting = db.query(SystemSettings).filter(
SystemSettings.key == "recaptcha_enabled"
).first()
@@ -1457,13 +1317,13 @@ async def verify_recaptcha(
SystemSettings.key == "recaptcha_secret_key"
).first()
- # Check if reCAPTCHA is enabled
+
is_enabled = False
if enabled_setting:
is_enabled = enabled_setting.value.lower() == "true" if enabled_setting.value else False
if not is_enabled:
- # If disabled, always return success
+
return {
"status": "success",
"data": {
@@ -1478,7 +1338,7 @@ async def verify_recaptcha(
detail="reCAPTCHA secret key is not configured"
)
- # Verify with Google reCAPTCHA API
+
import httpx
async with httpx.AsyncClient() as client:
@@ -1498,8 +1358,8 @@ async def verify_recaptcha(
"status": "success",
"data": {
"verified": True,
- "score": result.get("score"), # For v3
- "action": result.get("action") # For v3
+ "score": result.get("score"),
+ "action": result.get("action")
}
}
else:
diff --git a/Backend/src/routes/user_routes.py b/Backend/src/routes/user_routes.py
index d908d115..3ceb586e 100644
--- a/Backend/src/routes/user_routes.py
+++ b/Backend/src/routes/user_routes.py
@@ -3,323 +3,136 @@ from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional
import bcrypt
-
from ..config.database import get_db
from ..middleware.auth import get_current_user, authorize_roles
from ..models.user import User
from ..models.role import Role
from ..models.booking import Booking, BookingStatus
+router = APIRouter(prefix='/users', tags=['users'])
-router = APIRouter(prefix="/users", tags=["users"])
-
-
-@router.get("/", dependencies=[Depends(authorize_roles("admin"))])
-async def get_users(
- search: Optional[str] = Query(None),
- role: Optional[str] = Query(None),
- status_filter: Optional[str] = Query(None, alias="status"),
- page: int = Query(1, ge=1),
- limit: int = Query(10, ge=1, le=100),
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Get all users with filters and pagination (Admin only)"""
+@router.get('/', dependencies=[Depends(authorize_roles('admin'))])
+async def get_users(search: Optional[str]=Query(None), role: Optional[str]=Query(None), status_filter: Optional[str]=Query(None, alias='status'), page: int=Query(1, ge=1), limit: int=Query(10, ge=1, le=100), current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
query = db.query(User)
-
- # Filter by search (full_name, email, phone)
if search:
- query = query.filter(
- or_(
- User.full_name.like(f"%{search}%"),
- User.email.like(f"%{search}%"),
- User.phone.like(f"%{search}%")
- )
- )
-
- # Filter by role
+ query = query.filter(or_(User.full_name.like(f'%{search}%'), User.email.like(f'%{search}%'), User.phone.like(f'%{search}%')))
if role:
- role_map = {"admin": 1, "staff": 2, "customer": 3}
+ role_map = {'admin': 1, 'staff': 2, 'customer': 3}
if role in role_map:
query = query.filter(User.role_id == role_map[role])
-
- # Filter by status
if status_filter:
- is_active = status_filter == "active"
+ is_active = status_filter == 'active'
query = query.filter(User.is_active == is_active)
-
- # Get total count
total = query.count()
-
- # Apply pagination
offset = (page - 1) * limit
users = query.order_by(User.created_at.desc()).offset(offset).limit(limit).all()
-
- # Transform users
result = []
for user in users:
- user_dict = {
- "id": user.id,
- "email": user.email,
- "full_name": user.full_name,
- "phone": user.phone,
- "phone_number": user.phone, # For frontend compatibility
- "address": user.address,
- "avatar": user.avatar,
- "currency": getattr(user, 'currency', 'VND'),
- "is_active": user.is_active,
- "status": "active" if user.is_active else "inactive",
- "role_id": user.role_id,
- "role": user.role.name if user.role else "customer",
- "created_at": user.created_at.isoformat() if user.created_at else None,
- "updated_at": user.updated_at.isoformat() if user.updated_at else None,
- }
+ user_dict = {'id': user.id, 'email': user.email, 'full_name': user.full_name, 'phone': user.phone, 'phone_number': user.phone, 'address': user.address, 'avatar': user.avatar, 'currency': getattr(user, 'currency', 'VND'), 'is_active': user.is_active, 'status': 'active' if user.is_active else 'inactive', 'role_id': user.role_id, 'role': user.role.name if user.role else 'customer', 'created_at': user.created_at.isoformat() if user.created_at else None, 'updated_at': user.updated_at.isoformat() if user.updated_at else None}
result.append(user_dict)
-
- return {
- "status": "success",
- "data": {
- "users": result,
- "pagination": {
- "total": total,
- "page": page,
- "limit": limit,
- "totalPages": (total + limit - 1) // limit,
- },
- },
- }
+ return {'status': 'success', 'data': {'users': result, 'pagination': {'total': total, 'page': page, 'limit': limit, 'totalPages': (total + limit - 1) // limit}}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.get("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def get_user_by_id(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Get user by ID (Admin only)"""
+@router.get('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def get_user_by_id(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
user = db.query(User).filter(User.id == id).first()
-
if not user:
- raise HTTPException(status_code=404, detail="User not found")
-
- # Get recent bookings
- bookings = db.query(Booking).filter(
- Booking.user_id == id
- ).order_by(Booking.created_at.desc()).limit(5).all()
-
- user_dict = {
- "id": user.id,
- "email": user.email,
- "full_name": user.full_name,
- "phone": user.phone,
- "phone_number": user.phone,
- "address": user.address,
- "avatar": user.avatar,
- "currency": getattr(user, 'currency', 'VND'),
- "is_active": user.is_active,
- "status": "active" if user.is_active else "inactive",
- "role_id": user.role_id,
- "role": user.role.name if user.role else "customer",
- "created_at": user.created_at.isoformat() if user.created_at else None,
- "updated_at": user.updated_at.isoformat() if user.updated_at else None,
- "bookings": [
- {
- "id": b.id,
- "booking_number": b.booking_number,
- "status": b.status.value if isinstance(b.status, BookingStatus) else b.status,
- "created_at": b.created_at.isoformat() if b.created_at else None,
- }
- for b in bookings
- ],
- }
-
- return {
- "status": "success",
- "data": {"user": user_dict}
- }
+ raise HTTPException(status_code=404, detail='User not found')
+ bookings = db.query(Booking).filter(Booking.user_id == id).order_by(Booking.created_at.desc()).limit(5).all()
+ user_dict = {'id': user.id, 'email': user.email, 'full_name': user.full_name, 'phone': user.phone, 'phone_number': user.phone, 'address': user.address, 'avatar': user.avatar, 'currency': getattr(user, 'currency', 'VND'), 'is_active': user.is_active, 'status': 'active' if user.is_active else 'inactive', 'role_id': user.role_id, 'role': user.role.name if user.role else 'customer', 'created_at': user.created_at.isoformat() if user.created_at else None, 'updated_at': user.updated_at.isoformat() if user.updated_at else None, 'bookings': [{'id': b.id, 'booking_number': b.booking_number, 'status': b.status.value if isinstance(b.status, BookingStatus) else b.status, 'created_at': b.created_at.isoformat() if b.created_at else None} for b in bookings]}
+ return {'status': 'success', 'data': {'user': user_dict}}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
-
-@router.post("/", dependencies=[Depends(authorize_roles("admin"))])
-async def create_user(
- user_data: dict,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Create new user (Admin only)"""
+@router.post('/', dependencies=[Depends(authorize_roles('admin'))])
+async def create_user(user_data: dict, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
- email = user_data.get("email")
- password = user_data.get("password")
- full_name = user_data.get("full_name")
- phone_number = user_data.get("phone_number")
- role = user_data.get("role", "customer")
- status = user_data.get("status", "active")
-
- # Map role string to role_id
- role_map = {"admin": 1, "staff": 2, "customer": 3}
+ email = user_data.get('email')
+ password = user_data.get('password')
+ full_name = user_data.get('full_name')
+ phone_number = user_data.get('phone_number')
+ role = user_data.get('role', 'customer')
+ status = user_data.get('status', 'active')
+ role_map = {'admin': 1, 'staff': 2, 'customer': 3}
role_id = role_map.get(role, 3)
-
- # Check if email exists
existing = db.query(User).filter(User.email == email).first()
if existing:
- raise HTTPException(status_code=400, detail="Email already exists")
-
- # Hash password
+ raise HTTPException(status_code=400, detail='Email already exists')
password_bytes = password.encode('utf-8')
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')
-
- # Create user
- user = User(
- email=email,
- password=hashed_password,
- full_name=full_name,
- phone=phone_number,
- role_id=role_id,
- is_active=status == "active",
- )
-
+ user = User(email=email, password=hashed_password, full_name=full_name, phone=phone_number, role_id=role_id, is_active=status == 'active')
db.add(user)
db.commit()
db.refresh(user)
-
- # Remove password from response
- user_dict = {
- "id": user.id,
- "email": user.email,
- "full_name": user.full_name,
- "phone": user.phone,
- "phone_number": user.phone,
- "currency": getattr(user, 'currency', 'VND'),
- "role_id": user.role_id,
- "is_active": user.is_active,
- }
-
- return {
- "status": "success",
- "message": "User created successfully",
- "data": {"user": user_dict}
- }
+ user_dict = {'id': user.id, 'email': user.email, 'full_name': user.full_name, 'phone': user.phone, 'phone_number': user.phone, 'currency': getattr(user, 'currency', 'VND'), 'role_id': user.role_id, 'is_active': user.is_active}
+ return {'status': 'success', 'message': 'User created successfully', 'data': {'user': user_dict}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.put("/{id}")
-async def update_user(
- id: int,
- user_data: dict,
- current_user: User = Depends(get_current_user),
- db: Session = Depends(get_db)
-):
- """Update user"""
+@router.put('/{id}')
+async def update_user(id: int, user_data: dict, current_user: User=Depends(get_current_user), db: Session=Depends(get_db)):
try:
- # Users can only update themselves unless they're admin
if current_user.role_id != 1 and current_user.id != id:
- raise HTTPException(status_code=403, detail="Forbidden")
-
+ raise HTTPException(status_code=403, detail='Forbidden')
user = db.query(User).filter(User.id == id).first()
if not user:
- raise HTTPException(status_code=404, detail="User not found")
-
- # Check if email is being changed and if it's taken
- email = user_data.get("email")
+ raise HTTPException(status_code=404, detail='User not found')
+ email = user_data.get('email')
if email and email != user.email:
existing = db.query(User).filter(User.email == email).first()
if existing:
- raise HTTPException(status_code=400, detail="Email already exists")
-
- # Map role string to role_id (only admin can change role)
- role_map = {"admin": 1, "staff": 2, "customer": 3}
-
- # Update fields
- if "full_name" in user_data:
- user.full_name = user_data["full_name"]
- if "email" in user_data and current_user.role_id == 1:
- user.email = user_data["email"]
- if "phone_number" in user_data:
- user.phone = user_data["phone_number"]
- if "role" in user_data and current_user.role_id == 1:
- user.role_id = role_map.get(user_data["role"], 3)
- if "status" in user_data and current_user.role_id == 1:
- user.is_active = user_data["status"] == "active"
- if "currency" in user_data:
- currency = user_data["currency"]
+ raise HTTPException(status_code=400, detail='Email already exists')
+ role_map = {'admin': 1, 'staff': 2, 'customer': 3}
+ if 'full_name' in user_data:
+ user.full_name = user_data['full_name']
+ if 'email' in user_data and current_user.role_id == 1:
+ user.email = user_data['email']
+ if 'phone_number' in user_data:
+ user.phone = user_data['phone_number']
+ if 'role' in user_data and current_user.role_id == 1:
+ user.role_id = role_map.get(user_data['role'], 3)
+ if 'status' in user_data and current_user.role_id == 1:
+ user.is_active = user_data['status'] == 'active'
+ if 'currency' in user_data:
+ currency = user_data['currency']
if len(currency) == 3 and currency.isalpha():
user.currency = currency.upper()
- if "password" in user_data:
- password_bytes = user_data["password"].encode('utf-8')
+ if 'password' in user_data:
+ password_bytes = user_data['password'].encode('utf-8')
salt = bcrypt.gensalt()
user.password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')
-
db.commit()
db.refresh(user)
-
- # Remove password from response
- user_dict = {
- "id": user.id,
- "email": user.email,
- "full_name": user.full_name,
- "phone": user.phone,
- "phone_number": user.phone,
- "currency": getattr(user, 'currency', 'VND'),
- "role_id": user.role_id,
- "is_active": user.is_active,
- }
-
- return {
- "status": "success",
- "message": "User updated successfully",
- "data": {"user": user_dict}
- }
+ user_dict = {'id': user.id, 'email': user.email, 'full_name': user.full_name, 'phone': user.phone, 'phone_number': user.phone, 'currency': getattr(user, 'currency', 'VND'), 'role_id': user.role_id, 'is_active': user.is_active}
+ return {'status': 'success', 'message': 'User updated successfully', 'data': {'user': user_dict}}
except HTTPException:
raise
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=str(e))
-
-@router.delete("/{id}", dependencies=[Depends(authorize_roles("admin"))])
-async def delete_user(
- id: int,
- current_user: User = Depends(authorize_roles("admin")),
- db: Session = Depends(get_db)
-):
- """Delete user (Admin only)"""
+@router.delete('/{id}', dependencies=[Depends(authorize_roles('admin'))])
+async def delete_user(id: int, current_user: User=Depends(authorize_roles('admin')), db: Session=Depends(get_db)):
try:
user = db.query(User).filter(User.id == id).first()
if not user:
- raise HTTPException(status_code=404, detail="User not found")
-
- # Check if user has active bookings
- active_bookings = db.query(Booking).filter(
- Booking.user_id == id,
- Booking.status.in_([BookingStatus.pending, BookingStatus.confirmed, BookingStatus.checked_in])
- ).count()
-
+ raise HTTPException(status_code=404, detail='User not found')
+ active_bookings = db.query(Booking).filter(Booking.user_id == id, Booking.status.in_([BookingStatus.pending, BookingStatus.confirmed, BookingStatus.checked_in])).count()
if active_bookings > 0:
- raise HTTPException(
- status_code=400,
- detail="Cannot delete user with active bookings"
- )
-
+ raise HTTPException(status_code=400, detail='Cannot delete user with active bookings')
db.delete(user)
db.commit()
-
- return {
- "status": "success",
- "message": "User deleted successfully"
- }
+ return {'status': 'success', 'message': 'User deleted successfully'}
except HTTPException:
raise
except Exception as e:
db.rollback()
- raise HTTPException(status_code=500, detail=str(e))
+ raise HTTPException(status_code=500, detail=str(e))
\ No newline at end of file
diff --git a/Backend/src/schemas/admin_privacy.py b/Backend/src/schemas/admin_privacy.py
index 7000a19b..c9f813f4 100644
--- a/Backend/src/schemas/admin_privacy.py
+++ b/Backend/src/schemas/admin_privacy.py
@@ -1,68 +1,32 @@
from datetime import datetime
from typing import Optional
-
from pydantic import BaseModel, Field
-
class CookiePolicySettings(BaseModel):
- """
- Admin-configurable global cookie policy.
- Controls which categories can be used in the application.
- """
-
- analytics_enabled: bool = Field(
- default=True,
- description="If false, analytics cookies/scripts should not be used at all.",
- )
- marketing_enabled: bool = Field(
- default=True,
- description="If false, marketing cookies/scripts should not be used at all.",
- )
- preferences_enabled: bool = Field(
- default=True,
- description="If false, preference cookies should not be used at all.",
- )
-
+ analytics_enabled: bool = Field(default=True, description='If false, analytics cookies/scripts should not be used at all.')
+ marketing_enabled: bool = Field(default=True, description='If false, marketing cookies/scripts should not be used at all.')
+ preferences_enabled: bool = Field(default=True, description='If false, preference cookies should not be used at all.')
class CookiePolicySettingsResponse(BaseModel):
- status: str = Field(default="success")
+ status: str = Field(default='success')
data: CookiePolicySettings
updated_at: Optional[datetime] = None
updated_by: Optional[str] = None
-
class CookieIntegrationSettings(BaseModel):
- """
- IDs for well-known third-party integrations, configured by admin.
- """
-
- ga_measurement_id: Optional[str] = Field(
- default=None, description="Google Analytics 4 measurement ID (e.g. G-XXXXXXX)."
- )
- fb_pixel_id: Optional[str] = Field(
- default=None, description="Meta (Facebook) Pixel ID."
- )
-
+ ga_measurement_id: Optional[str] = Field(default=None, description='Google Analytics 4 measurement ID (e.g. G-XXXXXXX).')
+ fb_pixel_id: Optional[str] = Field(default=None, description='Meta (Facebook) Pixel ID.')
class CookieIntegrationSettingsResponse(BaseModel):
- status: str = Field(default="success")
+ status: str = Field(default='success')
data: CookieIntegrationSettings
updated_at: Optional[datetime] = None
updated_by: Optional[str] = None
-
class PublicPrivacyConfig(BaseModel):
- """
- Publicly consumable privacy configuration for the frontend.
- Does not expose any secrets, only IDs and flags.
- """
-
policy: CookiePolicySettings
integrations: CookieIntegrationSettings
-
class PublicPrivacyConfigResponse(BaseModel):
- status: str = Field(default="success")
- data: PublicPrivacyConfig
-
-
+ status: str = Field(default='success')
+ data: PublicPrivacyConfig
\ No newline at end of file
diff --git a/Backend/src/schemas/auth.py b/Backend/src/schemas/auth.py
index 6f0e28f3..a5b7e9da 100644
--- a/Backend/src/schemas/auth.py
+++ b/Backend/src/schemas/auth.py
@@ -1,64 +1,58 @@
from pydantic import BaseModel, EmailStr, Field, validator
from typing import Optional
-
class RegisterRequest(BaseModel):
name: str = Field(..., min_length=2, max_length=50)
email: EmailStr
password: str = Field(..., min_length=8)
phone: Optional[str] = None
- @validator("password")
+ @validator('password')
def validate_password(cls, v):
if len(v) < 8:
- raise ValueError("Password must be at least 8 characters")
- if not any(c.isupper() for c in v):
- raise ValueError("Password must contain at least one uppercase letter")
- if not any(c.islower() for c in v):
- raise ValueError("Password must contain at least one lowercase letter")
- if not any(c.isdigit() for c in v):
- raise ValueError("Password must contain at least one number")
+ raise ValueError('Password must be at least 8 characters')
+ if not any((c.isupper() for c in v)):
+ raise ValueError('Password must contain at least one uppercase letter')
+ if not any((c.islower() for c in v)):
+ raise ValueError('Password must contain at least one lowercase letter')
+ if not any((c.isdigit() for c in v)):
+ raise ValueError('Password must contain at least one number')
return v
- @validator("phone")
+ @validator('phone')
def validate_phone(cls, v):
- if v and not v.isdigit() or (v and len(v) not in [10, 11]):
- raise ValueError("Phone must be 10-11 digits")
+ if v and (not v.isdigit()) or (v and len(v) not in [10, 11]):
+ raise ValueError('Phone must be 10-11 digits')
return v
-
class LoginRequest(BaseModel):
email: EmailStr
password: str
rememberMe: Optional[bool] = False
mfaToken: Optional[str] = None
-
class RefreshTokenRequest(BaseModel):
refreshToken: Optional[str] = None
-
class ForgotPasswordRequest(BaseModel):
email: EmailStr
-
class ResetPasswordRequest(BaseModel):
token: str
password: str = Field(..., min_length=8)
- @validator("password")
+ @validator('password')
def validate_password(cls, v):
if len(v) < 8:
- raise ValueError("Password must be at least 8 characters")
- if not any(c.isupper() for c in v):
- raise ValueError("Password must contain at least one uppercase letter")
- if not any(c.islower() for c in v):
- raise ValueError("Password must contain at least one lowercase letter")
- if not any(c.isdigit() for c in v):
- raise ValueError("Password must contain at least one number")
+ raise ValueError('Password must be at least 8 characters')
+ if not any((c.isupper() for c in v)):
+ raise ValueError('Password must contain at least one uppercase letter')
+ if not any((c.islower() for c in v)):
+ raise ValueError('Password must contain at least one lowercase letter')
+ if not any((c.isdigit() for c in v)):
+ raise ValueError('Password must contain at least one number')
return v
-
class UserResponse(BaseModel):
id: int
name: str
@@ -71,38 +65,30 @@ class UserResponse(BaseModel):
class Config:
from_attributes = True
-
class AuthResponse(BaseModel):
user: UserResponse
token: str
refreshToken: Optional[str] = None
-
class TokenResponse(BaseModel):
token: str
-
class MessageResponse(BaseModel):
status: str
message: str
-
class MFAInitResponse(BaseModel):
secret: str
- qr_code: str # Base64 data URL
-
+ qr_code: str
class EnableMFARequest(BaseModel):
secret: str
verification_token: str
-
class VerifyMFARequest(BaseModel):
token: str
is_backup_code: Optional[bool] = False
-
class MFAStatusResponse(BaseModel):
mfa_enabled: bool
- backup_codes_count: int
-
+ backup_codes_count: int
\ No newline at end of file
diff --git a/Backend/src/schemas/privacy.py b/Backend/src/schemas/privacy.py
index b03d35d9..48162b2c 100644
--- a/Backend/src/schemas/privacy.py
+++ b/Backend/src/schemas/privacy.py
@@ -1,70 +1,24 @@
from datetime import datetime
from typing import Optional
-
from pydantic import BaseModel, Field
-
class CookieCategoryPreferences(BaseModel):
- """
- Granular consent for different cookie categories.
-
- - necessary: required for the site to function (always true, not revocable)
- - analytics: usage analytics, performance tracking
- - marketing: advertising, remarketing cookies
- - preferences: UI / language / personalization preferences
- """
-
- necessary: bool = Field(
- default=True,
- description="Strictly necessary cookies (always enabled as they are required for core functionality).",
- )
- analytics: bool = Field(
- default=False, description="Allow anonymous analytics and performance cookies."
- )
- marketing: bool = Field(
- default=False, description="Allow marketing and advertising cookies."
- )
- preferences: bool = Field(
- default=False,
- description="Allow preference cookies (e.g. language, layout settings).",
- )
-
+ necessary: bool = Field(default=True, description='Strictly necessary cookies (always enabled as they are required for core functionality).')
+ analytics: bool = Field(default=False, description='Allow anonymous analytics and performance cookies.')
+ marketing: bool = Field(default=False, description='Allow marketing and advertising cookies.')
+ preferences: bool = Field(default=False, description='Allow preference cookies (e.g. language, layout settings).')
class CookieConsent(BaseModel):
- """
- Persisted cookie consent state.
- Stored in an HttpOnly cookie and exposed via the API.
- """
-
- version: int = Field(
- default=1, description="Consent schema version for future migrations."
- )
- updated_at: datetime = Field(
- default_factory=datetime.utcnow, description="Last time consent was updated."
- )
- has_decided: bool = Field(
- default=False,
- description="Whether the user has actively made a consent choice.",
- )
- categories: CookieCategoryPreferences = Field(
- default_factory=CookieCategoryPreferences,
- description="Granular per-category consent.",
- )
-
+ version: int = Field(default=1, description='Consent schema version for future migrations.')
+ updated_at: datetime = Field(default_factory=datetime.utcnow, description='Last time consent was updated.')
+ has_decided: bool = Field(default=False, description='Whether the user has actively made a consent choice.')
+ categories: CookieCategoryPreferences = Field(default_factory=CookieCategoryPreferences, description='Granular per-category consent.')
class CookieConsentResponse(BaseModel):
- status: str = Field(default="success")
+ status: str = Field(default='success')
data: CookieConsent
-
class UpdateCookieConsentRequest(BaseModel):
- """
- Request body for updating cookie consent.
- 'necessary' is ignored on write and always treated as True by the server.
- """
-
analytics: Optional[bool] = None
marketing: Optional[bool] = None
- preferences: Optional[bool] = None
-
-
+ preferences: Optional[bool] = None
\ No newline at end of file
diff --git a/Backend/src/services/audit_service.py b/Backend/src/services/audit_service.py
index 98d52b2b..cfcc404a 100644
--- a/Backend/src/services/audit_service.py
+++ b/Backend/src/services/audit_service.py
@@ -1,82 +1,20 @@
-"""
-Audit logging service for tracking important actions
-"""
from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from datetime import datetime
from ..models.audit_log import AuditLog
from ..config.logging_config import get_logger
-
logger = get_logger(__name__)
-
class AuditService:
- """Service for creating audit log entries"""
-
+
@staticmethod
- async def log_action(
- db: Session,
- action: str,
- resource_type: str,
- user_id: Optional[int] = None,
- resource_id: Optional[int] = None,
- ip_address: Optional[str] = None,
- user_agent: Optional[str] = None,
- request_id: Optional[str] = None,
- details: Optional[Dict[str, Any]] = None,
- status: str = "success",
- error_message: Optional[str] = None
- ):
- """
- Create an audit log entry
-
- Args:
- db: Database session
- action: Action performed (e.g., "user.created", "booking.cancelled")
- resource_type: Type of resource (e.g., "user", "booking")
- user_id: ID of user who performed the action
- resource_id: ID of the resource affected
- ip_address: IP address of the request
- user_agent: User agent string
- request_id: Request ID for tracing
- details: Additional context as dictionary
- status: Status of the action (success, failed, error)
- error_message: Error message if action failed
- """
+ async def log_action(db: Session, action: str, resource_type: str, user_id: Optional[int]=None, resource_id: Optional[int]=None, ip_address: Optional[str]=None, user_agent: Optional[str]=None, request_id: Optional[str]=None, details: Optional[Dict[str, Any]]=None, status: str='success', error_message: Optional[str]=None):
try:
- audit_log = AuditLog(
- user_id=user_id,
- action=action,
- resource_type=resource_type,
- resource_id=resource_id,
- ip_address=ip_address,
- user_agent=user_agent,
- request_id=request_id,
- details=details,
- status=status,
- error_message=error_message
- )
-
+ audit_log = AuditLog(user_id=user_id, action=action, resource_type=resource_type, resource_id=resource_id, ip_address=ip_address, user_agent=user_agent, request_id=request_id, details=details, status=status, error_message=error_message)
db.add(audit_log)
db.commit()
-
- logger.info(
- f"Audit log created: {action} on {resource_type}",
- extra={
- "action": action,
- "resource_type": resource_type,
- "resource_id": resource_id,
- "user_id": user_id,
- "status": status,
- "request_id": request_id
- }
- )
+ logger.info(f'Audit log created: {action} on {resource_type}', extra={'action': action, 'resource_type': resource_type, 'resource_id': resource_id, 'user_id': user_id, 'status': status, 'request_id': request_id})
except Exception as e:
- logger.error(f"Failed to create audit log: {str(e)}", exc_info=True)
+ logger.error(f'Failed to create audit log: {str(e)}', exc_info=True)
db.rollback()
- # Don't raise exception - audit logging failures shouldn't break the app
-
-
-# Global audit service instance
-audit_service = AuditService()
-
+audit_service = AuditService()
\ No newline at end of file
diff --git a/Backend/src/services/auth_service.py b/Backend/src/services/auth_service.py
index f8fc7cf0..57cf5ab6 100644
--- a/Backend/src/services/auth_service.py
+++ b/Backend/src/services/auth_service.py
@@ -22,17 +22,15 @@ import os
logger = logging.getLogger(__name__)
-
class AuthService:
def __init__(self):
- # Use settings, fallback to env vars, then to defaults for development
+
self.jwt_secret = getattr(settings, 'JWT_SECRET', None) or os.getenv("JWT_SECRET", "dev-secret-key-change-in-production-12345")
self.jwt_refresh_secret = os.getenv("JWT_REFRESH_SECRET") or (self.jwt_secret + "-refresh")
self.jwt_expires_in = os.getenv("JWT_EXPIRES_IN", "1h")
self.jwt_refresh_expires_in = os.getenv("JWT_REFRESH_EXPIRES_IN", "7d")
def generate_tokens(self, user_id: int) -> dict:
- """Generate JWT tokens"""
access_token = jwt.encode(
{"userId": user_id},
self.jwt_secret,
@@ -48,24 +46,20 @@ class AuthService:
return {"accessToken": access_token, "refreshToken": refresh_token}
def verify_access_token(self, token: str) -> dict:
- """Verify JWT access token"""
return jwt.decode(token, self.jwt_secret, algorithms=["HS256"])
def verify_refresh_token(self, token: str) -> dict:
- """Verify JWT refresh token"""
return jwt.decode(token, self.jwt_refresh_secret, algorithms=["HS256"])
def hash_password(self, password: str) -> str:
- """Hash password using bcrypt"""
- # bcrypt has 72 byte limit, but it handles truncation automatically
+
password_bytes = password.encode('utf-8')
- # Generate salt and hash password
+
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password_bytes, salt)
return hashed.decode('utf-8')
def verify_password(self, plain_password: str, hashed_password: str) -> bool:
- """Verify password using bcrypt"""
try:
password_bytes = plain_password.encode('utf-8')
hashed_bytes = hashed_password.encode('utf-8')
@@ -74,7 +68,6 @@ class AuthService:
return False
def format_user_response(self, user: User) -> dict:
- """Format user response"""
return {
"id": user.id,
"name": user.full_name,
@@ -88,34 +81,28 @@ class AuthService:
}
async def register(self, db: Session, name: str, email: str, password: str, phone: Optional[str] = None) -> dict:
- """Register new user"""
- # Check if email exists
+
existing_user = db.query(User).filter(User.email == email).first()
if existing_user:
raise ValueError("Email already registered")
- # Hash password
hashed_password = self.hash_password(password)
- # Create user (default role_id = 3 for customer)
user = User(
full_name=name,
email=email,
password=hashed_password,
phone=phone,
- role_id=3 # Customer role
+ role_id=3
)
db.add(user)
db.commit()
db.refresh(user)
- # Load role
user.role = db.query(Role).filter(Role.id == user.role_id).first()
- # Generate tokens
tokens = self.generate_tokens(user.id)
- # Save refresh token (expires in 7 days)
expires_at = datetime.utcnow() + timedelta(days=7)
refresh_token = RefreshToken(
user_id=user.id,
@@ -125,7 +112,6 @@ class AuthService:
db.add(refresh_token)
db.commit()
- # Send welcome email (non-blocking)
try:
client_url = settings.CLIENT_URL or os.getenv("CLIENT_URL", "http://localhost:5173")
email_html = welcome_email_template(user.full_name, user.email, client_url)
@@ -145,62 +131,52 @@ class AuthService:
}
async def login(self, db: Session, email: str, password: str, remember_me: bool = False, mfa_token: str = None) -> dict:
- """Login user with optional MFA verification"""
- # Normalize email (lowercase and strip whitespace)
+
email = email.lower().strip() if email else ""
if not email:
raise ValueError("Invalid email or password")
- # Find user with role and password
+
user = db.query(User).filter(User.email == email).first()
if not user:
logger.warning(f"Login attempt with non-existent email: {email}")
raise ValueError("Invalid email or password")
- # Check if user is active
if not user.is_active:
logger.warning(f"Login attempt for inactive user: {email}")
raise ValueError("Account is disabled. Please contact support.")
- # Load role
user.role = db.query(Role).filter(Role.id == user.role_id).first()
- # Check password
if not self.verify_password(password, user.password):
logger.warning(f"Login attempt with invalid password for user: {email}")
raise ValueError("Invalid email or password")
- # Check if MFA is enabled
if user.mfa_enabled:
if not mfa_token:
- # Return special response indicating MFA is required
+
return {
"requires_mfa": True,
"user_id": user.id
}
- # Verify MFA token
+
from ..services.mfa_service import mfa_service
- is_backup_code = len(mfa_token) == 8 # Backup codes are 8 characters
+ is_backup_code = len(mfa_token) == 8
if not mfa_service.verify_mfa(db, user.id, mfa_token, is_backup_code):
raise ValueError("Invalid MFA token")
- # Generate tokens
tokens = self.generate_tokens(user.id)
- # Calculate expiry based on remember_me
expiry_days = 7 if remember_me else 1
expires_at = datetime.utcnow() + timedelta(days=expiry_days)
- # Delete old/expired refresh tokens for this user to prevent duplicates
- # This ensures we don't have multiple active tokens and prevents unique constraint violations
try:
db.query(RefreshToken).filter(
RefreshToken.user_id == user.id
).delete()
- db.flush() # Flush to ensure deletion happens before insert
+ db.flush()
- # Save new refresh token
refresh_token = RefreshToken(
user_id=user.id,
token=tokens["refreshToken"],
@@ -211,7 +187,6 @@ class AuthService:
except Exception as e:
db.rollback()
logger.error(f"Error saving refresh token for user {user.id}: {str(e)}", exc_info=True)
- # If there's still a duplicate, try to delete and retry once
try:
db.query(RefreshToken).filter(
RefreshToken.token == tokens["refreshToken"]
@@ -236,14 +211,11 @@ class AuthService:
}
async def refresh_access_token(self, db: Session, refresh_token_str: str) -> dict:
- """Refresh access token"""
if not refresh_token_str:
raise ValueError("Refresh token is required")
- # Verify refresh token
decoded = self.verify_refresh_token(refresh_token_str)
- # Check if refresh token exists in database
stored_token = db.query(RefreshToken).filter(
RefreshToken.token == refresh_token_str,
RefreshToken.user_id == decoded["userId"]
@@ -252,13 +224,11 @@ class AuthService:
if not stored_token:
raise ValueError("Invalid refresh token")
- # Check if token is expired
if datetime.utcnow() > stored_token.expires_at:
db.delete(stored_token)
db.commit()
raise ValueError("Refresh token expired")
- # Generate new access token
access_token = jwt.encode(
{"userId": decoded["userId"]},
self.jwt_secret,
@@ -268,19 +238,16 @@ class AuthService:
return {"token": access_token}
async def logout(self, db: Session, refresh_token_str: str) -> bool:
- """Logout user"""
if refresh_token_str:
db.query(RefreshToken).filter(RefreshToken.token == refresh_token_str).delete()
db.commit()
return True
async def get_profile(self, db: Session, user_id: int) -> dict:
- """Get user profile"""
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise ValueError("User not found")
- # Load role
user.role = db.query(Role).filter(Role.id == user.role_id).first()
return self.format_user_response(user)
@@ -296,25 +263,22 @@ class AuthService:
current_password: Optional[str] = None,
currency: Optional[str] = None
) -> dict:
- """Update user profile"""
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise ValueError("User not found")
- # If password is being changed, verify current password
if password:
if not current_password:
raise ValueError("Current password is required to change password")
if not self.verify_password(current_password, user.password):
raise ValueError("Current password is incorrect")
- # Hash new password
+
user.password = self.hash_password(password)
- # Update other fields
if full_name is not None:
user.full_name = full_name
if email is not None:
- # Check if email is already taken by another user
+
existing_user = db.query(User).filter(
User.email == email,
User.id != user_id
@@ -325,7 +289,7 @@ class AuthService:
if phone_number is not None:
user.phone = phone_number
if currency is not None:
- # Validate currency code (ISO 4217, 3 characters)
+
if len(currency) == 3 and currency.isalpha():
user.currency = currency.upper()
else:
@@ -334,36 +298,29 @@ class AuthService:
db.commit()
db.refresh(user)
- # Load role
user.role = db.query(Role).filter(Role.id == user.role_id).first()
return self.format_user_response(user)
def generate_reset_token(self) -> tuple:
- """Generate reset token"""
reset_token = secrets.token_hex(32)
hashed_token = hashlib.sha256(reset_token.encode()).hexdigest()
return reset_token, hashed_token
async def forgot_password(self, db: Session, email: str) -> dict:
- """Forgot Password - Send reset link"""
- # Find user by email
+
user = db.query(User).filter(User.email == email).first()
- # Always return success to prevent email enumeration
if not user:
return {
"success": True,
"message": "If email exists, reset link has been sent"
}
- # Generate reset token
reset_token, hashed_token = self.generate_reset_token()
- # Delete old tokens
db.query(PasswordResetToken).filter(PasswordResetToken.user_id == user.id).delete()
- # Save token (expires in 1 hour)
expires_at = datetime.utcnow() + timedelta(hours=1)
reset_token_obj = PasswordResetToken(
user_id=user.id,
@@ -373,31 +330,17 @@ class AuthService:
db.add(reset_token_obj)
db.commit()
- # Build reset URL
client_url = settings.CLIENT_URL or os.getenv("CLIENT_URL", "http://localhost:5173")
reset_url = f"{client_url}/reset-password/{reset_token}"
- # Try to send email
try:
logger.info(f"Attempting to send password reset email to {user.email}")
logger.info(f"Reset URL: {reset_url}")
email_html = password_reset_email_template(reset_url)
- # Create plain text version for better email deliverability
- plain_text = f"""
-Password Reset Request
-You (or someone) has requested to reset your password for your Hotel Booking account.
-
-Click the link below to reset your password. This link will expire in 1 hour:
-
-{reset_url}
-
-If you did not request this, please ignore this email.
-
-Best regards,
-Hotel Booking Team
- """.strip()
+ plain_text = f
+.strip()
await send_email(
to=user.email,
@@ -408,7 +351,6 @@ Hotel Booking Team
logger.info(f"Password reset email sent successfully to {user.email} with reset URL: {reset_url}")
except Exception as e:
logger.error(f"Failed to send password reset email to {user.email}: {type(e).__name__}: {str(e)}", exc_info=True)
- # Still return success to prevent email enumeration, but log the error
return {
"success": True,
@@ -416,14 +358,11 @@ Hotel Booking Team
}
async def reset_password(self, db: Session, token: str, password: str) -> dict:
- """Reset Password - Update password with token"""
if not token or not password:
raise ValueError("Token and password are required")
- # Hash the token to compare
hashed_token = hashlib.sha256(token.encode()).hexdigest()
- # Find valid token
reset_token = db.query(PasswordResetToken).filter(
PasswordResetToken.token == hashed_token,
PasswordResetToken.expires_at > datetime.utcnow(),
@@ -433,27 +372,21 @@ Hotel Booking Team
if not reset_token:
raise ValueError("Invalid or expired reset token")
- # Find user
user = db.query(User).filter(User.id == reset_token.user_id).first()
if not user:
raise ValueError("User not found")
- # Check if new password matches old password
if self.verify_password(password, user.password):
raise ValueError("New password must be different from the old password")
- # Hash new password
hashed_password = self.hash_password(password)
- # Update password
user.password = hashed_password
db.commit()
- # Mark token as used
reset_token.used = True
db.commit()
- # Send confirmation email (non-blocking)
try:
logger.info(f"Attempting to send password changed confirmation email to {user.email}")
email_html = password_changed_email_template(user.email)
@@ -471,6 +404,5 @@ Hotel Booking Team
"message": "Password has been reset successfully"
}
-
auth_service = AuthService()
diff --git a/Backend/src/services/currency_service.py b/Backend/src/services/currency_service.py
index f45d8536..beba7cfe 100644
--- a/Backend/src/services/currency_service.py
+++ b/Backend/src/services/currency_service.py
@@ -1,101 +1,42 @@
-"""
-Currency conversion service
-Handles currency conversion between different currencies
-"""
from typing import Dict
from decimal import Decimal
-
-# Base currency is VND (Vietnamese Dong)
-# Exchange rates relative to VND (1 VND = base)
-# These are approximate rates - in production, fetch from an API like exchangerate-api.com
-EXCHANGE_RATES: Dict[str, Decimal] = {
- 'VND': Decimal('1.0'), # Base currency
- 'USD': Decimal('0.000041'), # 1 VND = 0.000041 USD (approx 24,000 VND = 1 USD)
- 'EUR': Decimal('0.000038'), # 1 VND = 0.000038 EUR (approx 26,000 VND = 1 EUR)
- 'GBP': Decimal('0.000033'), # 1 VND = 0.000033 GBP (approx 30,000 VND = 1 GBP)
- 'JPY': Decimal('0.0061'), # 1 VND = 0.0061 JPY (approx 164 VND = 1 JPY)
- 'CNY': Decimal('0.00029'), # 1 VND = 0.00029 CNY (approx 3,400 VND = 1 CNY)
- 'KRW': Decimal('0.055'), # 1 VND = 0.055 KRW (approx 18 VND = 1 KRW)
- 'SGD': Decimal('0.000055'), # 1 VND = 0.000055 SGD (approx 18,000 VND = 1 SGD)
- 'THB': Decimal('0.0015'), # 1 VND = 0.0015 THB (approx 667 VND = 1 THB)
- 'AUD': Decimal('0.000062'), # 1 VND = 0.000062 AUD (approx 16,000 VND = 1 AUD)
- 'CAD': Decimal('0.000056'), # 1 VND = 0.000056 CAD (approx 18,000 VND = 1 CAD)
-}
-
-# Supported currencies list
+EXCHANGE_RATES: Dict[str, Decimal] = {'VND': Decimal('1.0'), 'USD': Decimal('0.000041'), 'EUR': Decimal('0.000038'), 'GBP': Decimal('0.000033'), 'JPY': Decimal('0.0061'), 'CNY': Decimal('0.00029'), 'KRW': Decimal('0.055'), 'SGD': Decimal('0.000055'), 'THB': Decimal('0.0015'), 'AUD': Decimal('0.000062'), 'CAD': Decimal('0.000056')}
SUPPORTED_CURRENCIES = list(EXCHANGE_RATES.keys())
-
class CurrencyService:
- """Service for currency conversion"""
-
+
@staticmethod
def get_supported_currencies() -> list:
- """Get list of supported currency codes"""
return SUPPORTED_CURRENCIES
-
+
@staticmethod
def convert_amount(amount: float, from_currency: str, to_currency: str) -> float:
- """
- Convert amount from one currency to another
-
- Args:
- amount: Amount to convert
- from_currency: Source currency code (ISO 4217)
- to_currency: Target currency code (ISO 4217)
-
- Returns:
- Converted amount
- """
from_currency = from_currency.upper()
to_currency = to_currency.upper()
-
if from_currency == to_currency:
return amount
-
if from_currency not in EXCHANGE_RATES:
- raise ValueError(f"Unsupported source currency: {from_currency}")
+ raise ValueError(f'Unsupported source currency: {from_currency}')
if to_currency not in EXCHANGE_RATES:
- raise ValueError(f"Unsupported target currency: {to_currency}")
-
- # Convert to VND first, then to target currency
+ raise ValueError(f'Unsupported target currency: {to_currency}')
amount_vnd = Decimal(str(amount)) / EXCHANGE_RATES[from_currency]
converted_amount = amount_vnd * EXCHANGE_RATES[to_currency]
-
return float(converted_amount)
-
+
@staticmethod
def get_exchange_rate(from_currency: str, to_currency: str) -> float:
- """
- Get exchange rate between two currencies
-
- Args:
- from_currency: Source currency code
- to_currency: Target currency code
-
- Returns:
- Exchange rate (1 from_currency = X to_currency)
- """
from_currency = from_currency.upper()
to_currency = to_currency.upper()
-
if from_currency == to_currency:
return 1.0
-
if from_currency not in EXCHANGE_RATES:
- raise ValueError(f"Unsupported source currency: {from_currency}")
+ raise ValueError(f'Unsupported source currency: {from_currency}')
if to_currency not in EXCHANGE_RATES:
- raise ValueError(f"Unsupported target currency: {to_currency}")
-
- # Rate = (1 / from_rate) * to_rate
+ raise ValueError(f'Unsupported target currency: {to_currency}')
rate = EXCHANGE_RATES[to_currency] / EXCHANGE_RATES[from_currency]
return float(rate)
-
+
@staticmethod
def format_currency_code(currency: str) -> str:
- """Format currency code to uppercase"""
return currency.upper() if currency else 'VND'
-
-
-currency_service = CurrencyService()
-
+currency_service = CurrencyService()
\ No newline at end of file
diff --git a/Backend/src/services/invoice_service.py b/Backend/src/services/invoice_service.py
index 73fe769e..735cf69e 100644
--- a/Backend/src/services/invoice_service.py
+++ b/Backend/src/services/invoice_service.py
@@ -1,6 +1,3 @@
-"""
-Invoice service for managing invoices
-"""
from sqlalchemy.orm import Session
from sqlalchemy import func, and_, or_
from typing import Optional, Dict, Any, List
@@ -10,110 +7,46 @@ from ..models.booking import Booking
from ..models.payment import Payment, PaymentStatus
from ..models.user import User
-
-def generate_invoice_number(db: Session, is_proforma: bool = False) -> str:
- """Generate a unique invoice number"""
- # Format: INV-YYYYMMDD-XXXX or PRO-YYYYMMDD-XXXX for proforma
- prefix = "PRO" if is_proforma else "INV"
- today = datetime.utcnow().strftime("%Y%m%d")
-
- # Get the last invoice number for today
- last_invoice = db.query(Invoice).filter(
- Invoice.invoice_number.like(f"{prefix}-{today}-%")
- ).order_by(Invoice.invoice_number.desc()).first()
-
+def generate_invoice_number(db: Session, is_proforma: bool=False) -> str:
+ prefix = 'PRO' if is_proforma else 'INV'
+ today = datetime.utcnow().strftime('%Y%m%d')
+ last_invoice = db.query(Invoice).filter(Invoice.invoice_number.like(f'{prefix}-{today}-%')).order_by(Invoice.invoice_number.desc()).first()
if last_invoice:
- # Extract the sequence number and increment
try:
- sequence = int(last_invoice.invoice_number.split("-")[-1])
+ sequence = int(last_invoice.invoice_number.split('-')[-1])
sequence += 1
except (ValueError, IndexError):
sequence = 1
else:
sequence = 1
-
- return f"{prefix}-{today}-{sequence:04d}"
-
+ return f'{prefix}-{today}-{sequence:04d}'
class InvoiceService:
- """Service for managing invoices"""
-
+
@staticmethod
- def create_invoice_from_booking(
- booking_id: int,
- db: Session,
- created_by_id: Optional[int] = None,
- tax_rate: float = 0.0,
- discount_amount: float = 0.0,
- due_days: int = 30,
- is_proforma: bool = False,
- invoice_amount: Optional[float] = None, # For partial invoices (e.g., deposit)
- **kwargs
- ) -> Dict[str, Any]:
- """
- Create an invoice from a booking
-
- Args:
- booking_id: Booking ID
- db: Database session
- created_by_id: User ID who created the invoice
- tax_rate: Tax rate percentage (default: 0.0)
- discount_amount: Discount amount (default: 0.0)
- due_days: Number of days until due date (default: 30)
- **kwargs: Additional invoice fields (company info, notes, etc.)
-
- Returns:
- Invoice dictionary
- """
+ def create_invoice_from_booking(booking_id: int, db: Session, created_by_id: Optional[int]=None, tax_rate: float=0.0, discount_amount: float=0.0, due_days: int=30, is_proforma: bool=False, invoice_amount: Optional[float]=None, **kwargs) -> Dict[str, Any]:
from sqlalchemy.orm import selectinload
-
- booking = db.query(Booking).options(
- selectinload(Booking.service_usages).selectinload("service"),
- selectinload(Booking.room).selectinload("room_type"),
- selectinload(Booking.payments)
- ).filter(Booking.id == booking_id).first()
+ booking = db.query(Booking).options(selectinload(Booking.service_usages).selectinload('service'), selectinload(Booking.room).selectinload('room_type'), selectinload(Booking.payments)).filter(Booking.id == booking_id).first()
if not booking:
- raise ValueError("Booking not found")
-
+ raise ValueError('Booking not found')
user = db.query(User).filter(User.id == booking.user_id).first()
if not user:
- raise ValueError("User not found")
-
- # Generate invoice number
+ raise ValueError('User not found')
invoice_number = generate_invoice_number(db, is_proforma=is_proforma)
-
- # If invoice_amount is specified, we need to adjust item calculations
- # This will be handled in the item creation section below
-
- # Calculate amounts - subtotal will be recalculated after adding items
- # Initial subtotal is booking total (room + services) or invoice_amount if specified
booking_total = float(booking.total_price)
if invoice_amount is not None:
subtotal = float(invoice_amount)
- # For partial invoices, ensure discount is proportional
- # If discount_amount seems too large (greater than subtotal), recalculate proportionally
if invoice_amount < booking_total and discount_amount > 0:
- # Check if discount seems disproportionate (greater than 50% of subtotal suggests it's the full discount)
if discount_amount > subtotal * 0.5:
- # Recalculate proportionally from booking's original discount
proportion = float(invoice_amount) / booking_total
original_discount = float(booking.discount_amount) if booking.discount_amount else discount_amount
discount_amount = original_discount * proportion
else:
subtotal = booking_total
-
- # Calculate tax and total amounts
tax_amount = (subtotal - discount_amount) * (tax_rate / 100)
total_amount = subtotal + tax_amount - discount_amount
-
- # Calculate amount paid from completed payments
- amount_paid = sum(
- float(p.amount) for p in booking.payments
- if p.payment_status == PaymentStatus.completed
- )
+ amount_paid = sum((float(p.amount) for p in booking.payments if p.payment_status == PaymentStatus.completed))
balance_due = total_amount - amount_paid
-
- # Determine status
if balance_due <= 0:
status = InvoiceStatus.paid
paid_date = datetime.utcnow()
@@ -123,252 +56,99 @@ class InvoiceService:
else:
status = InvoiceStatus.draft
paid_date = None
-
- # Create invoice
- invoice = Invoice(
- invoice_number=invoice_number,
- booking_id=booking_id,
- user_id=booking.user_id,
- issue_date=datetime.utcnow(),
- due_date=datetime.utcnow() + timedelta(days=due_days),
- paid_date=paid_date,
- subtotal=subtotal,
- tax_rate=tax_rate,
- tax_amount=tax_amount,
- discount_amount=discount_amount,
- total_amount=total_amount,
- amount_paid=amount_paid,
- balance_due=balance_due,
- status=status,
- is_proforma=is_proforma,
- company_name=kwargs.get("company_name"),
- company_address=kwargs.get("company_address"),
- company_phone=kwargs.get("company_phone"),
- company_email=kwargs.get("company_email"),
- company_tax_id=kwargs.get("company_tax_id"),
- company_logo_url=kwargs.get("company_logo_url"),
- customer_name=user.full_name or f"{user.email}",
- customer_email=user.email,
- customer_address=user.address,
- customer_phone=user.phone,
- customer_tax_id=kwargs.get("customer_tax_id"),
- notes=kwargs.get("notes"),
- terms_and_conditions=kwargs.get("terms_and_conditions"),
- payment_instructions=kwargs.get("payment_instructions"),
- created_by_id=created_by_id,
- )
-
+ invoice = Invoice(invoice_number=invoice_number, booking_id=booking_id, user_id=booking.user_id, issue_date=datetime.utcnow(), due_date=datetime.utcnow() + timedelta(days=due_days), paid_date=paid_date, subtotal=subtotal, tax_rate=tax_rate, tax_amount=tax_amount, discount_amount=discount_amount, total_amount=total_amount, amount_paid=amount_paid, balance_due=balance_due, status=status, is_proforma=is_proforma, company_name=kwargs.get('company_name'), company_address=kwargs.get('company_address'), company_phone=kwargs.get('company_phone'), company_email=kwargs.get('company_email'), company_tax_id=kwargs.get('company_tax_id'), company_logo_url=kwargs.get('company_logo_url'), customer_name=user.full_name or f'{user.email}', customer_email=user.email, customer_address=user.address, customer_phone=user.phone, customer_tax_id=kwargs.get('customer_tax_id'), notes=kwargs.get('notes'), terms_and_conditions=kwargs.get('terms_and_conditions'), payment_instructions=kwargs.get('payment_instructions'), created_by_id=created_by_id)
db.add(invoice)
- db.flush() # Flush to get invoice.id before creating invoice items
-
- # Create invoice items from booking
- # Calculate room price (total_price includes services, so subtract services)
- services_total = sum(
- float(su.total_price) for su in booking.service_usages
- )
+ db.flush()
+ services_total = sum((float(su.total_price) for su in booking.service_usages))
booking_total = float(booking.total_price)
room_price = booking_total - services_total
-
- # Calculate number of nights
nights = (booking.check_out_date - booking.check_in_date).days
if nights <= 0:
nights = 1
-
- # If invoice_amount is specified (for partial invoices), calculate proportion
if invoice_amount is not None and invoice_amount < booking_total:
- # Calculate proportion for partial invoice
proportion = float(invoice_amount) / booking_total
room_price = room_price * proportion
services_total = services_total * proportion
- item_description_suffix = f" (Partial: {proportion * 100:.0f}%)"
+ item_description_suffix = f' (Partial: {proportion * 100:.0f}%)'
else:
- item_description_suffix = ""
-
- # Room item
- room_item = InvoiceItem(
- invoice_id=invoice.id,
- description=f"Room: {booking.room.room_number} - {booking.room.room_type.name if booking.room.room_type else 'N/A'} ({nights} night{'s' if nights > 1 else ''}){item_description_suffix}",
- quantity=nights,
- unit_price=room_price / nights if nights > 0 else room_price,
- tax_rate=tax_rate,
- discount_amount=0.0,
- line_total=room_price,
- room_id=booking.room_id,
- )
+ item_description_suffix = ''
+ room_item = InvoiceItem(invoice_id=invoice.id, description=f'Room: {booking.room.room_number} - {(booking.room.room_type.name if booking.room.room_type else 'N/A')} ({nights} night{('s' if nights > 1 else '')}){item_description_suffix}', quantity=nights, unit_price=room_price / nights if nights > 0 else room_price, tax_rate=tax_rate, discount_amount=0.0, line_total=room_price, room_id=booking.room_id)
db.add(room_item)
-
- # Add service items if any
for service_usage in booking.service_usages:
service_item_price = float(service_usage.total_price)
if invoice_amount is not None and invoice_amount < booking_total:
- # Apply proportion to service items
proportion = float(invoice_amount) / booking_total
service_item_price = service_item_price * proportion
-
- service_item = InvoiceItem(
- invoice_id=invoice.id,
- description=f"Service: {service_usage.service.name}{item_description_suffix}",
- quantity=float(service_usage.quantity),
- unit_price=service_item_price / float(service_usage.quantity) if service_usage.quantity > 0 else service_item_price,
- tax_rate=tax_rate,
- discount_amount=0.0,
- line_total=service_item_price,
- service_id=service_usage.service_id,
- )
+ service_item = InvoiceItem(invoice_id=invoice.id, description=f'Service: {service_usage.service.name}{item_description_suffix}', quantity=float(service_usage.quantity), unit_price=service_item_price / float(service_usage.quantity) if service_usage.quantity > 0 else service_item_price, tax_rate=tax_rate, discount_amount=0.0, line_total=service_item_price, service_id=service_usage.service_id)
db.add(service_item)
-
- # Recalculate subtotal from items (room + services)
subtotal = room_price + services_total
-
- # Recalculate tax and total amounts
tax_amount = (subtotal - discount_amount) * (tax_rate / 100)
total_amount = subtotal + tax_amount - discount_amount
balance_due = total_amount - amount_paid
-
- # Update invoice with correct amounts
invoice.subtotal = subtotal
invoice.tax_amount = tax_amount
invoice.total_amount = total_amount
invoice.balance_due = balance_due
-
db.commit()
db.refresh(invoice)
-
return InvoiceService.invoice_to_dict(invoice)
-
+
@staticmethod
- def update_invoice(
- invoice_id: int,
- db: Session,
- updated_by_id: Optional[int] = None,
- **kwargs
- ) -> Dict[str, Any]:
- """
- Update an invoice
-
- Args:
- invoice_id: Invoice ID
- db: Database session
- updated_by_id: User ID who updated the invoice
- **kwargs: Fields to update
-
- Returns:
- Updated invoice dictionary
- """
+ def update_invoice(invoice_id: int, db: Session, updated_by_id: Optional[int]=None, **kwargs) -> Dict[str, Any]:
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
if not invoice:
- raise ValueError("Invoice not found")
-
- # Update allowed fields
- allowed_fields = [
- "company_name", "company_address", "company_phone", "company_email",
- "company_tax_id", "company_logo_url", "notes", "terms_and_conditions",
- "payment_instructions", "status", "due_date", "tax_rate", "discount_amount"
- ]
-
+ raise ValueError('Invoice not found')
+ allowed_fields = ['company_name', 'company_address', 'company_phone', 'company_email', 'company_tax_id', 'company_logo_url', 'notes', 'terms_and_conditions', 'payment_instructions', 'status', 'due_date', 'tax_rate', 'discount_amount']
for field in allowed_fields:
if field in kwargs:
setattr(invoice, field, kwargs[field])
-
- # Recalculate if tax_rate or discount_amount changed
- if "tax_rate" in kwargs or "discount_amount" in kwargs:
- tax_rate = kwargs.get("tax_rate", invoice.tax_rate)
- discount_amount = kwargs.get("discount_amount", invoice.discount_amount)
-
+ if 'tax_rate' in kwargs or 'discount_amount' in kwargs:
+ tax_rate = kwargs.get('tax_rate', invoice.tax_rate)
+ discount_amount = kwargs.get('discount_amount', invoice.discount_amount)
invoice.tax_amount = (invoice.subtotal - discount_amount) * (float(tax_rate) / 100)
invoice.total_amount = invoice.subtotal + invoice.tax_amount - discount_amount
invoice.balance_due = invoice.total_amount - invoice.amount_paid
-
- # Update status based on balance
if invoice.balance_due <= 0 and invoice.status != InvoiceStatus.paid:
invoice.status = InvoiceStatus.paid
invoice.paid_date = datetime.utcnow()
elif invoice.balance_due > 0 and invoice.status == InvoiceStatus.paid:
invoice.status = InvoiceStatus.sent
invoice.paid_date = None
-
invoice.updated_by_id = updated_by_id
invoice.updated_at = datetime.utcnow()
-
db.commit()
db.refresh(invoice)
-
return InvoiceService.invoice_to_dict(invoice)
-
+
@staticmethod
- def mark_invoice_as_paid(
- invoice_id: int,
- db: Session,
- amount: Optional[float] = None,
- updated_by_id: Optional[int] = None
- ) -> Dict[str, Any]:
- """
- Mark an invoice as paid
-
- Args:
- invoice_id: Invoice ID
- db: Database session
- amount: Payment amount (if None, uses balance_due)
- updated_by_id: User ID who marked as paid
-
- Returns:
- Updated invoice dictionary
- """
+ def mark_invoice_as_paid(invoice_id: int, db: Session, amount: Optional[float]=None, updated_by_id: Optional[int]=None) -> Dict[str, Any]:
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
if not invoice:
- raise ValueError("Invoice not found")
-
+ raise ValueError('Invoice not found')
payment_amount = amount if amount is not None else float(invoice.balance_due)
invoice.amount_paid += payment_amount
invoice.balance_due = invoice.total_amount - invoice.amount_paid
-
if invoice.balance_due <= 0:
invoice.status = InvoiceStatus.paid
invoice.paid_date = datetime.utcnow()
else:
invoice.status = InvoiceStatus.sent
-
invoice.updated_by_id = updated_by_id
invoice.updated_at = datetime.utcnow()
-
db.commit()
db.refresh(invoice)
-
return InvoiceService.invoice_to_dict(invoice)
-
+
@staticmethod
def get_invoice(invoice_id: int, db: Session) -> Optional[Dict[str, Any]]:
- """Get invoice by ID"""
invoice = db.query(Invoice).filter(Invoice.id == invoice_id).first()
if not invoice:
return None
return InvoiceService.invoice_to_dict(invoice)
-
+
@staticmethod
- def get_invoices(
- db: Session,
- user_id: Optional[int] = None,
- booking_id: Optional[int] = None,
- status: Optional[str] = None,
- page: int = 1,
- limit: int = 10
- ) -> Dict[str, Any]:
- """
- Get invoices with filters
-
- Args:
- db: Database session
- user_id: Filter by user ID
- booking_id: Filter by booking ID
- status: Filter by status
- page: Page number
- limit: Items per page
-
- Returns:
- Dictionary with invoices and pagination info
- """
+ def get_invoices(db: Session, user_id: Optional[int]=None, booking_id: Optional[int]=None, status: Optional[str]=None, page: int=1, limit: int=10) -> Dict[str, Any]:
query = db.query(Invoice)
-
if user_id:
query = query.filter(Invoice.user_id == user_id)
if booking_id:
@@ -379,80 +159,17 @@ class InvoiceService:
query = query.filter(Invoice.status == status_enum)
except ValueError:
pass
-
- # Get total count
total = query.count()
-
- # Apply pagination
offset = (page - 1) * limit
invoices = query.order_by(Invoice.created_at.desc()).offset(offset).limit(limit).all()
-
- return {
- "invoices": [InvoiceService.invoice_to_dict(inv) for inv in invoices],
- "total": total,
- "page": page,
- "limit": limit,
- "total_pages": (total + limit - 1) // limit
- }
-
+ return {'invoices': [InvoiceService.invoice_to_dict(inv) for inv in invoices], 'total': total, 'page': page, 'limit': limit, 'total_pages': (total + limit - 1) // limit}
+
@staticmethod
def invoice_to_dict(invoice: Invoice) -> Dict[str, Any]:
- """Convert invoice model to dictionary"""
- # Extract promotion code from notes if present
promotion_code = None
- if invoice.notes and "Promotion Code:" in invoice.notes:
+ if invoice.notes and 'Promotion Code:' in invoice.notes:
try:
- promotion_code = invoice.notes.split("Promotion Code:")[1].split("\n")[0].strip()
+ promotion_code = invoice.notes.split('Promotion Code:')[1].split('\n')[0].strip()
except:
pass
-
- return {
- "id": invoice.id,
- "invoice_number": invoice.invoice_number,
- "booking_id": invoice.booking_id,
- "user_id": invoice.user_id,
- "issue_date": invoice.issue_date.isoformat() if invoice.issue_date else None,
- "due_date": invoice.due_date.isoformat() if invoice.due_date else None,
- "paid_date": invoice.paid_date.isoformat() if invoice.paid_date else None,
- "subtotal": float(invoice.subtotal) if invoice.subtotal else 0.0,
- "tax_rate": float(invoice.tax_rate) if invoice.tax_rate else 0.0,
- "tax_amount": float(invoice.tax_amount) if invoice.tax_amount else 0.0,
- "discount_amount": float(invoice.discount_amount) if invoice.discount_amount else 0.0,
- "total_amount": float(invoice.total_amount) if invoice.total_amount else 0.0,
- "amount_paid": float(invoice.amount_paid) if invoice.amount_paid else 0.0,
- "balance_due": float(invoice.balance_due) if invoice.balance_due else 0.0,
- "status": invoice.status.value if invoice.status else None,
- "company_name": invoice.company_name,
- "company_address": invoice.company_address,
- "company_phone": invoice.company_phone,
- "company_email": invoice.company_email,
- "company_tax_id": invoice.company_tax_id,
- "company_logo_url": invoice.company_logo_url,
- "customer_name": invoice.customer_name,
- "customer_email": invoice.customer_email,
- "customer_address": invoice.customer_address,
- "customer_phone": invoice.customer_phone,
- "customer_tax_id": invoice.customer_tax_id,
- "notes": invoice.notes,
- "terms_and_conditions": invoice.terms_and_conditions,
- "payment_instructions": invoice.payment_instructions,
- "is_proforma": invoice.is_proforma if hasattr(invoice, 'is_proforma') else False,
- "promotion_code": promotion_code,
- "items": [
- {
- "id": item.id,
- "description": item.description,
- "quantity": float(item.quantity) if item.quantity else 0.0,
- "unit_price": float(item.unit_price) if item.unit_price else 0.0,
- "tax_rate": float(item.tax_rate) if item.tax_rate else 0.0,
- "discount_amount": float(item.discount_amount) if item.discount_amount else 0.0,
- "line_total": float(item.line_total) if item.line_total else 0.0,
- "room_id": item.room_id,
- "service_id": item.service_id,
- }
- for item in invoice.items
- ],
- "created_at": invoice.created_at.isoformat() if invoice.created_at else None,
- "updated_at": invoice.updated_at.isoformat() if invoice.updated_at else None,
- }
-
+ return {'id': invoice.id, 'invoice_number': invoice.invoice_number, 'booking_id': invoice.booking_id, 'user_id': invoice.user_id, 'issue_date': invoice.issue_date.isoformat() if invoice.issue_date else None, 'due_date': invoice.due_date.isoformat() if invoice.due_date else None, 'paid_date': invoice.paid_date.isoformat() if invoice.paid_date else None, 'subtotal': float(invoice.subtotal) if invoice.subtotal else 0.0, 'tax_rate': float(invoice.tax_rate) if invoice.tax_rate else 0.0, 'tax_amount': float(invoice.tax_amount) if invoice.tax_amount else 0.0, 'discount_amount': float(invoice.discount_amount) if invoice.discount_amount else 0.0, 'total_amount': float(invoice.total_amount) if invoice.total_amount else 0.0, 'amount_paid': float(invoice.amount_paid) if invoice.amount_paid else 0.0, 'balance_due': float(invoice.balance_due) if invoice.balance_due else 0.0, 'status': invoice.status.value if invoice.status else None, 'company_name': invoice.company_name, 'company_address': invoice.company_address, 'company_phone': invoice.company_phone, 'company_email': invoice.company_email, 'company_tax_id': invoice.company_tax_id, 'company_logo_url': invoice.company_logo_url, 'customer_name': invoice.customer_name, 'customer_email': invoice.customer_email, 'customer_address': invoice.customer_address, 'customer_phone': invoice.customer_phone, 'customer_tax_id': invoice.customer_tax_id, 'notes': invoice.notes, 'terms_and_conditions': invoice.terms_and_conditions, 'payment_instructions': invoice.payment_instructions, 'is_proforma': invoice.is_proforma if hasattr(invoice, 'is_proforma') else False, 'promotion_code': promotion_code, 'items': [{'id': item.id, 'description': item.description, 'quantity': float(item.quantity) if item.quantity else 0.0, 'unit_price': float(item.unit_price) if item.unit_price else 0.0, 'tax_rate': float(item.tax_rate) if item.tax_rate else 0.0, 'discount_amount': float(item.discount_amount) if item.discount_amount else 0.0, 'line_total': float(item.line_total) if item.line_total else 0.0, 'room_id': item.room_id, 'service_id': item.service_id} for item in invoice.items], 'created_at': invoice.created_at.isoformat() if invoice.created_at else None, 'updated_at': invoice.updated_at.isoformat() if invoice.updated_at else None}
\ No newline at end of file
diff --git a/Backend/src/services/mfa_service.py b/Backend/src/services/mfa_service.py
index 6b252e89..e3e00fc2 100644
--- a/Backend/src/services/mfa_service.py
+++ b/Backend/src/services/mfa_service.py
@@ -1,7 +1,3 @@
-"""
-Multi-Factor Authentication (MFA) Service
-Handles TOTP-based MFA functionality
-"""
import pyotp
import qrcode
import secrets
@@ -13,287 +9,119 @@ from typing import List, Optional, Dict, Tuple
from sqlalchemy.orm import Session
from ..models.user import User
import logging
-
logger = logging.getLogger(__name__)
-
class MFAService:
- """Service for managing Multi-Factor Authentication"""
@staticmethod
def generate_secret() -> str:
- """Generate a new TOTP secret"""
return pyotp.random_base32()
@staticmethod
- def generate_qr_code(secret: str, email: str, app_name: str = "Hotel Booking") -> str:
- """
- Generate QR code data URL for TOTP setup
-
- Args:
- secret: TOTP secret key
- email: User's email address
- app_name: Application name for the authenticator app
-
- Returns:
- Base64 encoded QR code image data URL
- """
- # Create provisioning URI for authenticator apps
- totp_uri = pyotp.totp.TOTP(secret).provisioning_uri(
- name=email,
- issuer_name=app_name
- )
-
- # Generate QR code
- qr = qrcode.QRCode(
- version=1,
- error_correction=qrcode.constants.ERROR_CORRECT_L,
- box_size=10,
- border=4,
- )
+ def generate_qr_code(secret: str, email: str, app_name: str='Hotel Booking') -> str:
+ totp_uri = pyotp.totp.TOTP(secret).provisioning_uri(name=email, issuer_name=app_name)
+ qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4)
qr.add_data(totp_uri)
qr.make(fit=True)
-
- # Create image
- img = qr.make_image(fill_color="black", back_color="white")
-
- # Convert to base64 data URL
+ img = qr.make_image(fill_color='black', back_color='white')
buffer = io.BytesIO()
img.save(buffer, format='PNG')
img_data = base64.b64encode(buffer.getvalue()).decode()
-
- return f"data:image/png;base64,{img_data}"
+ return f'data:image/png;base64,{img_data}'
@staticmethod
- def generate_backup_codes(count: int = 10) -> List[str]:
- """
- Generate backup codes for MFA recovery
-
- Args:
- count: Number of backup codes to generate (default: 10)
-
- Returns:
- List of backup codes (8-character alphanumeric)
- """
+ def generate_backup_codes(count: int=10) -> List[str]:
codes = []
for _ in range(count):
- # Generate 8-character alphanumeric code
code = secrets.token_urlsafe(6).upper()[:8]
codes.append(code)
return codes
@staticmethod
def hash_backup_code(code: str) -> str:
- """
- Hash a backup code for storage (SHA-256)
-
- Args:
- code: Plain backup code
-
- Returns:
- Hashed backup code
- """
return hashlib.sha256(code.encode()).hexdigest()
@staticmethod
def verify_backup_code(code: str, hashed_codes: List[str]) -> bool:
- """
- Verify if a backup code matches any hashed code
-
- Args:
- code: Plain backup code to verify
- hashed_codes: List of hashed backup codes
-
- Returns:
- True if code matches, False otherwise
- """
code_hash = MFAService.hash_backup_code(code)
return code_hash in hashed_codes
@staticmethod
def verify_totp(token: str, secret: str) -> bool:
- """
- Verify a TOTP token
-
- Args:
- token: 6-digit TOTP token from authenticator app
- secret: User's TOTP secret
-
- Returns:
- True if token is valid, False otherwise
- """
try:
totp = pyotp.TOTP(secret)
- # Allow tokens from current and previous/next time window for clock skew
return totp.verify(token, valid_window=1)
except Exception as e:
- logger.error(f"Error verifying TOTP: {str(e)}")
+ logger.error(f'Error verifying TOTP: {str(e)}')
return False
@staticmethod
- def enable_mfa(
- db: Session,
- user_id: int,
- secret: str,
- verification_token: str
- ) -> Tuple[bool, List[str]]:
- """
- Enable MFA for a user after verifying the token
-
- Args:
- db: Database session
- user_id: User ID
- secret: TOTP secret
- verification_token: Token from authenticator app to verify
-
- Returns:
- Tuple of (success, backup_codes)
- """
+ def enable_mfa(db: Session, user_id: int, secret: str, verification_token: str) -> Tuple[bool, List[str]]:
user = db.query(User).filter(User.id == user_id).first()
if not user:
- raise ValueError("User not found")
-
- # Verify the token before enabling
+ raise ValueError('User not found')
if not MFAService.verify_totp(verification_token, secret):
- raise ValueError("Invalid verification token")
-
- # Generate backup codes
+ raise ValueError('Invalid verification token')
backup_codes = MFAService.generate_backup_codes()
hashed_codes = [MFAService.hash_backup_code(code) for code in backup_codes]
-
- # Update user
user.mfa_enabled = True
user.mfa_secret = secret
user.mfa_backup_codes = json.dumps(hashed_codes)
-
db.commit()
-
- # Return plain backup codes (only shown once)
- return True, backup_codes
+ return (True, backup_codes)
@staticmethod
def disable_mfa(db: Session, user_id: int) -> bool:
- """
- Disable MFA for a user
-
- Args:
- db: Database session
- user_id: User ID
-
- Returns:
- True if successful
- """
user = db.query(User).filter(User.id == user_id).first()
if not user:
- raise ValueError("User not found")
-
+ raise ValueError('User not found')
user.mfa_enabled = False
user.mfa_secret = None
user.mfa_backup_codes = None
-
db.commit()
return True
@staticmethod
- def verify_mfa(
- db: Session,
- user_id: int,
- token: str,
- is_backup_code: bool = False
- ) -> bool:
- """
- Verify MFA token or backup code for a user
-
- Args:
- db: Database session
- user_id: User ID
- token: TOTP token or backup code
- is_backup_code: Whether the token is a backup code
-
- Returns:
- True if verification successful, False otherwise
- """
+ def verify_mfa(db: Session, user_id: int, token: str, is_backup_code: bool=False) -> bool:
user = db.query(User).filter(User.id == user_id).first()
if not user:
- raise ValueError("User not found")
-
+ raise ValueError('User not found')
if not user.mfa_enabled or not user.mfa_secret:
- raise ValueError("MFA is not enabled for this user")
-
+ raise ValueError('MFA is not enabled for this user')
if is_backup_code:
- # Verify backup code
if not user.mfa_backup_codes:
return False
-
hashed_codes = json.loads(user.mfa_backup_codes)
if not MFAService.verify_backup_code(token, hashed_codes):
return False
-
- # Remove used backup code
code_hash = MFAService.hash_backup_code(token)
hashed_codes.remove(code_hash)
user.mfa_backup_codes = json.dumps(hashed_codes) if hashed_codes else None
db.commit()
return True
else:
- # Verify TOTP token
return MFAService.verify_totp(token, user.mfa_secret)
@staticmethod
def regenerate_backup_codes(db: Session, user_id: int) -> List[str]:
- """
- Regenerate backup codes for a user
-
- Args:
- db: Database session
- user_id: User ID
-
- Returns:
- List of new backup codes (plain, shown once)
- """
user = db.query(User).filter(User.id == user_id).first()
if not user:
- raise ValueError("User not found")
-
+ raise ValueError('User not found')
if not user.mfa_enabled:
- raise ValueError("MFA is not enabled for this user")
-
- # Generate new backup codes
+ raise ValueError('MFA is not enabled for this user')
backup_codes = MFAService.generate_backup_codes()
hashed_codes = [MFAService.hash_backup_code(code) for code in backup_codes]
-
user.mfa_backup_codes = json.dumps(hashed_codes)
db.commit()
-
- # Return plain backup codes (only shown once)
return backup_codes
@staticmethod
def get_mfa_status(db: Session, user_id: int) -> Dict:
- """
- Get MFA status for a user
-
- Args:
- db: Database session
- user_id: User ID
-
- Returns:
- Dictionary with MFA status information
- """
user = db.query(User).filter(User.id == user_id).first()
if not user:
- raise ValueError("User not found")
-
+ raise ValueError('User not found')
backup_codes_count = 0
if user.mfa_backup_codes:
backup_codes_count = len(json.loads(user.mfa_backup_codes))
-
- return {
- "mfa_enabled": user.mfa_enabled,
- "backup_codes_count": backup_codes_count
- }
-
-
-# Create singleton instance
-mfa_service = MFAService()
-
+ return {'mfa_enabled': user.mfa_enabled, 'backup_codes_count': backup_codes_count}
+mfa_service = MFAService()
\ No newline at end of file
diff --git a/Backend/src/services/paypal_service.py b/Backend/src/services/paypal_service.py
index 24c62f79..f494c60f 100644
--- a/Backend/src/services/paypal_service.py
+++ b/Backend/src/services/paypal_service.py
@@ -1,6 +1,3 @@
-"""
-PayPal payment service for processing PayPal payments
-"""
import logging
from paypalcheckoutsdk.core import PayPalHttpClient, SandboxEnvironment, LiveEnvironment
from paypalcheckoutsdk.orders import OrdersCreateRequest, OrdersGetRequest, OrdersCaptureRequest
@@ -13,434 +10,208 @@ from ..models.system_settings import SystemSettings
from sqlalchemy.orm import Session
from datetime import datetime
import json
-
logger = logging.getLogger(__name__)
-
def get_paypal_client_id(db: Session) -> Optional[str]:
- """Get PayPal client ID from database or environment variable"""
try:
- setting = db.query(SystemSettings).filter(
- SystemSettings.key == "paypal_client_id"
- ).first()
+ setting = db.query(SystemSettings).filter(SystemSettings.key == 'paypal_client_id').first()
if setting and setting.value:
return setting.value
except Exception:
pass
- # Fallback to environment variable
return settings.PAYPAL_CLIENT_ID if settings.PAYPAL_CLIENT_ID else None
-
def get_paypal_client_secret(db: Session) -> Optional[str]:
- """Get PayPal client secret from database or environment variable"""
try:
- setting = db.query(SystemSettings).filter(
- SystemSettings.key == "paypal_client_secret"
- ).first()
+ setting = db.query(SystemSettings).filter(SystemSettings.key == 'paypal_client_secret').first()
if setting and setting.value:
return setting.value
except Exception:
pass
- # Fallback to environment variable
return settings.PAYPAL_CLIENT_SECRET if settings.PAYPAL_CLIENT_SECRET else None
-
def get_paypal_mode(db: Session) -> str:
- """Get PayPal mode from database or environment variable"""
try:
- setting = db.query(SystemSettings).filter(
- SystemSettings.key == "paypal_mode"
- ).first()
+ setting = db.query(SystemSettings).filter(SystemSettings.key == 'paypal_mode').first()
if setting and setting.value:
return setting.value
except Exception:
pass
- # Fallback to environment variable
- return settings.PAYPAL_MODE if settings.PAYPAL_MODE else "sandbox"
+ return settings.PAYPAL_MODE if settings.PAYPAL_MODE else 'sandbox'
-
-def get_paypal_client(db: Optional[Session] = None) -> PayPalHttpClient:
- """
- Get PayPal HTTP client
-
- Args:
- db: Optional database session to get credentials from database
-
- Returns:
- PayPalHttpClient instance
- """
+def get_paypal_client(db: Optional[Session]=None) -> PayPalHttpClient:
client_id = None
client_secret = None
- mode = "sandbox"
-
+ mode = 'sandbox'
if db:
client_id = get_paypal_client_id(db)
client_secret = get_paypal_client_secret(db)
mode = get_paypal_mode(db)
-
if not client_id:
client_id = settings.PAYPAL_CLIENT_ID
if not client_secret:
client_secret = settings.PAYPAL_CLIENT_SECRET
if not mode:
- mode = settings.PAYPAL_MODE or "sandbox"
-
+ mode = settings.PAYPAL_MODE or 'sandbox'
if not client_id or not client_secret:
- raise ValueError("PayPal credentials are not configured")
-
- # Create environment based on mode
- if mode.lower() == "live":
+ raise ValueError('PayPal credentials are not configured')
+ if mode.lower() == 'live':
environment = LiveEnvironment(client_id=client_id, client_secret=client_secret)
else:
environment = SandboxEnvironment(client_id=client_id, client_secret=client_secret)
-
return PayPalHttpClient(environment)
-
class PayPalService:
- """Service for handling PayPal payments"""
-
+
@staticmethod
- def create_order(
- amount: float,
- currency: str = "USD",
- metadata: Optional[Dict[str, Any]] = None,
- db: Optional[Session] = None
- ) -> Dict[str, Any]:
- """
- Create a PayPal order
-
- Args:
- amount: Payment amount in currency units
- currency: Currency code (default: USD)
- metadata: Additional metadata to attach to the order
- db: Optional database session to get credentials from database
-
- Returns:
- Order object with approval URL and order ID
- """
+ def create_order(amount: float, currency: str='USD', metadata: Optional[Dict[str, Any]]=None, db: Optional[Session]=None) -> Dict[str, Any]:
client = get_paypal_client(db)
-
- # Validate amount
if amount <= 0:
- raise ValueError("Amount must be greater than 0")
+ raise ValueError('Amount must be greater than 0')
if amount > 100000:
raise ValueError(f"Amount ${amount:,.2f} exceeds PayPal's maximum of $100,000")
-
- # Create order request
request = OrdersCreateRequest()
- request.prefer("return=representation")
-
- # Build order body
- order_data = {
- "intent": "CAPTURE",
- "purchase_units": [
- {
- "amount": {
- "currency_code": currency.upper(),
- "value": f"{amount:.2f}"
- },
- "description": metadata.get("description", "Hotel Booking Payment") if metadata else "Hotel Booking Payment",
- "custom_id": metadata.get("booking_id") if metadata else None,
- }
- ],
- "application_context": {
- "brand_name": "Hotel Booking",
- "landing_page": "BILLING",
- "user_action": "PAY_NOW",
- "return_url": metadata.get("return_url") if metadata else None,
- "cancel_url": metadata.get("cancel_url") if metadata else None,
- }
- }
-
- # Add metadata if provided
+ request.prefer('return=representation')
+ order_data = {'intent': 'CAPTURE', 'purchase_units': [{'amount': {'currency_code': currency.upper(), 'value': f'{amount:.2f}'}, 'description': metadata.get('description', 'Hotel Booking Payment') if metadata else 'Hotel Booking Payment', 'custom_id': metadata.get('booking_id') if metadata else None}], 'application_context': {'brand_name': 'Hotel Booking', 'landing_page': 'BILLING', 'user_action': 'PAY_NOW', 'return_url': metadata.get('return_url') if metadata else None, 'cancel_url': metadata.get('cancel_url') if metadata else None}}
if metadata:
- order_data["purchase_units"][0]["invoice_id"] = metadata.get("booking_number")
-
+ order_data['purchase_units'][0]['invoice_id'] = metadata.get('booking_number')
request.request_body(order_data)
-
try:
response = client.execute(request)
order = response.result
-
- # Extract approval URL
approval_url = None
for link in order.links:
- if link.rel == "approve":
+ if link.rel == 'approve':
approval_url = link.href
break
-
- return {
- "id": order.id,
- "status": order.status,
- "approval_url": approval_url,
- "amount": amount,
- "currency": currency.upper(),
- }
+ return {'id': order.id, 'status': order.status, 'approval_url': approval_url, 'amount': amount, 'currency': currency.upper()}
except Exception as e:
error_msg = str(e)
- # Try to extract more details from PayPal error
if hasattr(e, 'message'):
error_msg = e.message
elif hasattr(e, 'details') and e.details:
error_msg = json.dumps(e.details)
- raise ValueError(f"PayPal error: {error_msg}")
-
+ raise ValueError(f'PayPal error: {error_msg}')
+
@staticmethod
- def get_order(
- order_id: str,
- db: Optional[Session] = None
- ) -> Dict[str, Any]:
- """
- Retrieve an order by ID
-
- Args:
- order_id: PayPal order ID
- db: Optional database session to get credentials from database
-
- Returns:
- Order object
- """
+ def get_order(order_id: str, db: Optional[Session]=None) -> Dict[str, Any]:
client = get_paypal_client(db)
-
request = OrdersGetRequest(order_id)
-
try:
response = client.execute(request)
order = response.result
-
- # Extract amount from purchase units
amount = 0.0
- currency = "USD"
+ currency = 'USD'
if order.purchase_units and len(order.purchase_units) > 0:
amount_str = order.purchase_units[0].amount.value
currency = order.purchase_units[0].amount.currency_code
amount = float(amount_str)
-
- return {
- "id": order.id,
- "status": order.status,
- "amount": amount,
- "currency": currency,
- "create_time": order.create_time,
- "update_time": order.update_time,
- }
+ return {'id': order.id, 'status': order.status, 'amount': amount, 'currency': currency, 'create_time': order.create_time, 'update_time': order.update_time}
except Exception as e:
error_msg = str(e)
if hasattr(e, 'message'):
error_msg = e.message
- raise ValueError(f"PayPal error: {error_msg}")
-
+ raise ValueError(f'PayPal error: {error_msg}')
+
@staticmethod
- def capture_order(
- order_id: str,
- db: Optional[Session] = None
- ) -> Dict[str, Any]:
- """
- Capture a PayPal order
-
- Args:
- order_id: PayPal order ID
- db: Optional database session to get credentials from database
-
- Returns:
- Capture details
- """
+ def capture_order(order_id: str, db: Optional[Session]=None) -> Dict[str, Any]:
client = get_paypal_client(db)
-
request = OrdersCaptureRequest(order_id)
- request.prefer("return=representation")
-
+ request.prefer('return=representation')
try:
response = client.execute(request)
order = response.result
-
- # Extract capture details
capture_id = None
amount = 0.0
- currency = "USD"
+ currency = 'USD'
status = order.status
-
if order.purchase_units and len(order.purchase_units) > 0:
payments = order.purchase_units[0].payments
- if payments and payments.captures and len(payments.captures) > 0:
+ if payments and payments.captures and (len(payments.captures) > 0):
capture = payments.captures[0]
capture_id = capture.id
amount_str = capture.amount.value
currency = capture.amount.currency_code
amount = float(amount_str)
status = capture.status
-
- return {
- "order_id": order.id,
- "capture_id": capture_id,
- "status": status,
- "amount": amount,
- "currency": currency,
- }
+ return {'order_id': order.id, 'capture_id': capture_id, 'status': status, 'amount': amount, 'currency': currency}
except Exception as e:
error_msg = str(e)
if hasattr(e, 'message'):
error_msg = e.message
- raise ValueError(f"PayPal error: {error_msg}")
-
+ raise ValueError(f'PayPal error: {error_msg}')
+
@staticmethod
- async def confirm_payment(
- order_id: str,
- db: Session,
- booking_id: Optional[int] = None
- ) -> Dict[str, Any]:
- """
- Confirm a payment and update database records
-
- Args:
- order_id: PayPal order ID
- db: Database session
- booking_id: Optional booking ID for metadata lookup
-
- Returns:
- Payment record dictionary
- """
+ async def confirm_payment(order_id: str, db: Session, booking_id: Optional[int]=None) -> Dict[str, Any]:
try:
- # First capture the order
capture_data = PayPalService.capture_order(order_id, db)
-
- # Get order details to extract booking_id from metadata if not provided
if not booking_id:
order_data = PayPalService.get_order(order_id, db)
- # Try to get booking_id from custom_id in purchase_units
- # Note: We'll need to store booking_id in the order metadata when creating
-
- # For now, we'll require booking_id to be passed
if not booking_id:
- raise ValueError("Booking ID is required")
-
+ raise ValueError('Booking ID is required')
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise ValueError("Booking not found")
-
- # Check capture status
- capture_status = capture_data.get("status")
- if capture_status not in ["COMPLETED", "PENDING"]:
- raise ValueError(f"Payment capture not in a valid state. Status: {capture_status}")
-
- # Find existing payment or create new one
- # First try to find by transaction_id (for already captured payments)
- payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.transaction_id == order_id,
- Payment.payment_method == PaymentMethod.paypal
- ).first()
-
- # If not found, try to find pending PayPal payment for this booking
+ raise ValueError('Booking not found')
+ capture_status = capture_data.get('status')
+ if capture_status not in ['COMPLETED', 'PENDING']:
+ raise ValueError(f'Payment capture not in a valid state. Status: {capture_status}')
+ payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.transaction_id == order_id, Payment.payment_method == PaymentMethod.paypal).first()
if not payment:
- payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.payment_method == PaymentMethod.paypal,
- Payment.payment_status == PaymentStatus.pending
- ).order_by(Payment.created_at.desc()).first()
-
- # If still not found, try to find pending deposit payment (for cash bookings with deposit)
- # This allows updating the payment_method from the default to paypal
+ payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.payment_method == PaymentMethod.paypal, Payment.payment_status == PaymentStatus.pending).order_by(Payment.created_at.desc()).first()
if not payment:
- payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.payment_type == PaymentType.deposit,
- Payment.payment_status == PaymentStatus.pending
- ).order_by(Payment.created_at.desc()).first()
-
- amount = capture_data["amount"]
- capture_id = capture_data.get("capture_id")
-
+ payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.payment_type == PaymentType.deposit, Payment.payment_status == PaymentStatus.pending).order_by(Payment.created_at.desc()).first()
+ amount = capture_data['amount']
+ capture_id = capture_data.get('capture_id')
if payment:
- # Update existing payment
- if capture_status == "COMPLETED":
+ if capture_status == 'COMPLETED':
payment.payment_status = PaymentStatus.completed
payment.payment_date = datetime.utcnow()
- # If pending, keep as pending
payment.amount = amount
- payment.payment_method = PaymentMethod.paypal # Update payment method to PayPal
+ payment.payment_method = PaymentMethod.paypal
if capture_id:
- payment.transaction_id = f"{order_id}|{capture_id}"
+ payment.transaction_id = f'{order_id}|{capture_id}'
else:
- # Create new payment record
payment_type = PaymentType.full
- if booking.requires_deposit and not booking.deposit_paid:
+ if booking.requires_deposit and (not booking.deposit_paid):
payment_type = PaymentType.deposit
-
- payment_status_enum = PaymentStatus.completed if capture_status == "COMPLETED" else PaymentStatus.pending
- payment_date = datetime.utcnow() if capture_status == "COMPLETED" else None
-
- transaction_id = f"{order_id}|{capture_id}" if capture_id else order_id
-
- payment = Payment(
- booking_id=booking_id,
- amount=amount,
- payment_method=PaymentMethod.paypal,
- payment_type=payment_type,
- payment_status=payment_status_enum,
- transaction_id=transaction_id,
- payment_date=payment_date,
- notes=f"PayPal payment - Order: {order_id}, Capture: {capture_id} (Status: {capture_status})",
- )
+ payment_status_enum = PaymentStatus.completed if capture_status == 'COMPLETED' else PaymentStatus.pending
+ payment_date = datetime.utcnow() if capture_status == 'COMPLETED' else None
+ transaction_id = f'{order_id}|{capture_id}' if capture_id else order_id
+ payment = Payment(booking_id=booking_id, amount=amount, payment_method=PaymentMethod.paypal, payment_type=payment_type, payment_status=payment_status_enum, transaction_id=transaction_id, payment_date=payment_date, notes=f'PayPal payment - Order: {order_id}, Capture: {capture_id} (Status: {capture_status})')
db.add(payment)
-
- # Commit payment first
db.commit()
db.refresh(payment)
-
- # Update booking status only if payment is completed
if payment.payment_status == PaymentStatus.completed:
db.refresh(booking)
-
- # Calculate total paid from all completed payments (now includes current payment)
- # This needs to be calculated before the if/elif blocks
- total_paid = sum(
- float(p.amount) for p in booking.payments
- if p.payment_status == PaymentStatus.completed
- )
-
- # Update invoice status based on payment
+ total_paid = sum((float(p.amount) for p in booking.payments if p.payment_status == PaymentStatus.completed))
from ..models.invoice import Invoice, InvoiceStatus
-
- # Find invoices for this booking and update their status
invoices = db.query(Invoice).filter(Invoice.booking_id == booking_id).all()
for invoice in invoices:
- # Update invoice amount_paid and balance_due
invoice.amount_paid = total_paid
invoice.balance_due = float(invoice.total_amount) - total_paid
-
- # Update invoice status
if invoice.balance_due <= 0:
invoice.status = InvoiceStatus.paid
invoice.paid_date = datetime.utcnow()
elif invoice.amount_paid > 0:
invoice.status = InvoiceStatus.sent
-
booking_was_confirmed = False
should_send_email = False
if payment.payment_type == PaymentType.deposit:
booking.deposit_paid = True
- # Restore cancelled bookings or confirm pending bookings
if booking.status in [BookingStatus.pending, BookingStatus.cancelled]:
booking.status = BookingStatus.confirmed
booking_was_confirmed = True
should_send_email = True
elif booking.status == BookingStatus.confirmed:
- # Booking already confirmed, but deposit was just paid
should_send_email = True
elif payment.payment_type == PaymentType.full:
- # Confirm booking and restore cancelled bookings when payment succeeds
if total_paid >= float(booking.total_price) or float(payment.amount) >= float(booking.total_price):
if booking.status in [BookingStatus.pending, BookingStatus.cancelled]:
booking.status = BookingStatus.confirmed
booking_was_confirmed = True
should_send_email = True
elif booking.status == BookingStatus.confirmed:
- # Booking already confirmed, but full payment was just completed
should_send_email = True
-
- # Send booking confirmation email if booking was just confirmed or payment completed
if should_send_email:
try:
from ..utils.mailer import send_email
@@ -450,143 +221,74 @@ class PayPalService:
from sqlalchemy.orm import selectinload
import os
from ..config.settings import settings
-
- # Get client URL from settings
- 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"))
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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')
+ 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)
-
- # Load booking with room details for email
- booking_with_room = db.query(Booking).options(
- selectinload(Booking.room).selectinload(Room.room_type)
- ).filter(Booking.id == booking_id).first()
-
+ 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"
-
- # Calculate amount paid and remaining due
+ room_type_name = room.room_type.name if room and room.room_type else 'Room'
amount_paid = total_paid
payment_type_str = payment.payment_type.value if payment.payment_type else None
-
- 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=False, # Payment completed, no deposit message needed
- deposit_amount=None,
- amount_paid=amount_paid,
- payment_type=payment_type_str,
- client_url=client_url,
- currency_symbol=currency_symbol
- )
+ 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=False, deposit_amount=None, amount_paid=amount_paid, payment_type=payment_type_str, client_url=client_url, currency_symbol=currency_symbol)
if booking.user:
- await send_email(
- to=booking.user.email,
- subject=f"Booking Confirmed - {booking.booking_number}",
- html=email_html
- )
- logger.info(f"Booking confirmation email sent to {booking.user.email}")
+ await send_email(to=booking.user.email, subject=f'Booking Confirmed - {booking.booking_number}', html=email_html)
+ logger.info(f'Booking confirmation email sent to {booking.user.email}')
except Exception as email_error:
- logger.error(f"Failed to send booking confirmation email: {str(email_error)}")
-
- # Send invoice email if payment is completed and invoice is now paid
+ logger.error(f'Failed to send booking confirmation email: {str(email_error)}')
from ..utils.mailer import send_email
from ..services.invoice_service import InvoiceService
from ..routes.booking_routes import _generate_invoice_email_html
-
- # Load user for email
from ..models.user import User
user = db.query(User).filter(User.id == booking.user_id).first()
-
for invoice in invoices:
if invoice.status == InvoiceStatus.paid and invoice.balance_due <= 0:
try:
invoice_dict = InvoiceService.invoice_to_dict(invoice)
invoice_html = _generate_invoice_email_html(invoice_dict, is_proforma=invoice.is_proforma)
- invoice_type = "Proforma Invoice" if invoice.is_proforma else "Invoice"
+ invoice_type = 'Proforma Invoice' if invoice.is_proforma else 'Invoice'
if user:
- await send_email(
- to=user.email,
- subject=f"{invoice_type} {invoice.invoice_number} - Payment Confirmed",
- html=invoice_html
- )
- logger.info(f"{invoice_type} {invoice.invoice_number} sent to {user.email}")
+ await send_email(to=user.email, subject=f'{invoice_type} {invoice.invoice_number} - Payment Confirmed', html=invoice_html)
+ logger.info(f'{invoice_type} {invoice.invoice_number} sent to {user.email}')
except Exception as email_error:
- logger.error(f"Failed to send invoice email: {str(email_error)}")
-
- # Send invoice email if payment is completed and invoice is now paid
+ logger.error(f'Failed to send invoice email: {str(email_error)}')
from ..utils.mailer import send_email
from ..services.invoice_service import InvoiceService
from ..models.invoice import InvoiceStatus
from ..routes.booking_routes import _generate_invoice_email_html
-
- # Load user for email
from ..models.user import User
user = db.query(User).filter(User.id == booking.user_id).first()
-
for invoice in invoices:
if invoice.status == InvoiceStatus.paid and invoice.balance_due <= 0:
try:
invoice_dict = InvoiceService.invoice_to_dict(invoice)
invoice_html = _generate_invoice_email_html(invoice_dict, is_proforma=invoice.is_proforma)
- invoice_type = "Proforma Invoice" if invoice.is_proforma else "Invoice"
+ invoice_type = 'Proforma Invoice' if invoice.is_proforma else 'Invoice'
if user:
- await send_email(
- to=user.email,
- subject=f"{invoice_type} {invoice.invoice_number} - Payment Confirmed",
- html=invoice_html
- )
- logger.info(f"{invoice_type} {invoice.invoice_number} sent to {user.email}")
+ await send_email(to=user.email, subject=f'{invoice_type} {invoice.invoice_number} - Payment Confirmed', html=invoice_html)
+ logger.info(f'{invoice_type} {invoice.invoice_number} sent to {user.email}')
except Exception as email_error:
- logger.error(f"Failed to send invoice email: {str(email_error)}")
-
+ logger.error(f'Failed to send invoice email: {str(email_error)}')
db.commit()
db.refresh(booking)
-
- # Safely get enum values
+
def get_enum_value(enum_obj):
if enum_obj is None:
return None
if isinstance(enum_obj, (PaymentMethod, PaymentType, PaymentStatus)):
return enum_obj.value
return enum_obj
-
- return {
- "id": payment.id,
- "booking_id": payment.booking_id,
- "amount": float(payment.amount) if payment.amount else 0.0,
- "payment_method": get_enum_value(payment.payment_method),
- "payment_type": get_enum_value(payment.payment_type),
- "payment_status": get_enum_value(payment.payment_status),
- "transaction_id": payment.transaction_id,
- "payment_date": payment.payment_date.isoformat() if payment.payment_date else None,
- }
-
+ return {'id': payment.id, 'booking_id': payment.booking_id, 'amount': float(payment.amount) if payment.amount else 0.0, 'payment_method': get_enum_value(payment.payment_method), 'payment_type': get_enum_value(payment.payment_type), 'payment_status': get_enum_value(payment.payment_status), 'transaction_id': payment.transaction_id, 'payment_date': payment.payment_date.isoformat() if payment.payment_date else None}
except ValueError as e:
db.rollback()
raise
except Exception as e:
import traceback
error_details = traceback.format_exc()
- error_msg = str(e) if str(e) else f"{type(e).__name__}: {repr(e)}"
- print(f"Error in confirm_payment: {error_msg}")
- print(f"Traceback: {error_details}")
+ error_msg = str(e) if str(e) else f'{type(e).__name__}: {repr(e)}'
+ print(f'Error in confirm_payment: {error_msg}')
+ print(f'Traceback: {error_details}')
db.rollback()
- raise ValueError(f"Error confirming payment: {error_msg}")
-
+ raise ValueError(f'Error confirming payment: {error_msg}')
\ No newline at end of file
diff --git a/Backend/src/services/privacy_admin_service.py b/Backend/src/services/privacy_admin_service.py
index 610c4b0b..006e985a 100644
--- a/Backend/src/services/privacy_admin_service.py
+++ b/Backend/src/services/privacy_admin_service.py
@@ -1,27 +1,16 @@
from sqlalchemy.orm import Session
-
from ..models.cookie_policy import CookiePolicy
from ..models.cookie_integration_config import CookieIntegrationConfig
from ..models.user import User
-from ..schemas.admin_privacy import (
- CookieIntegrationSettings,
- CookiePolicySettings,
- PublicPrivacyConfig,
-)
-
+from ..schemas.admin_privacy import CookieIntegrationSettings, CookiePolicySettings, PublicPrivacyConfig
class PrivacyAdminService:
- """
- Service layer for admin-controlled cookie policy and integrations.
- """
- # Policy
@staticmethod
def get_or_create_policy(db: Session) -> CookiePolicy:
policy = db.query(CookiePolicy).first()
if policy:
return policy
-
policy = CookiePolicy()
db.add(policy)
db.commit()
@@ -31,16 +20,10 @@ class PrivacyAdminService:
@staticmethod
def get_policy_settings(db: Session) -> CookiePolicySettings:
policy = PrivacyAdminService.get_or_create_policy(db)
- return CookiePolicySettings(
- analytics_enabled=policy.analytics_enabled,
- marketing_enabled=policy.marketing_enabled,
- preferences_enabled=policy.preferences_enabled,
- )
+ return CookiePolicySettings(analytics_enabled=policy.analytics_enabled, marketing_enabled=policy.marketing_enabled, preferences_enabled=policy.preferences_enabled)
@staticmethod
- def update_policy(
- db: Session, settings: CookiePolicySettings, updated_by: User | None
- ) -> CookiePolicy:
+ def update_policy(db: Session, settings: CookiePolicySettings, updated_by: User | None) -> CookiePolicy:
policy = PrivacyAdminService.get_or_create_policy(db)
policy.analytics_enabled = settings.analytics_enabled
policy.marketing_enabled = settings.marketing_enabled
@@ -52,7 +35,6 @@ class PrivacyAdminService:
db.refresh(policy)
return policy
- # Integrations
@staticmethod
def get_or_create_integrations(db: Session) -> CookieIntegrationConfig:
config = db.query(CookieIntegrationConfig).first()
@@ -67,15 +49,10 @@ class PrivacyAdminService:
@staticmethod
def get_integration_settings(db: Session) -> CookieIntegrationSettings:
cfg = PrivacyAdminService.get_or_create_integrations(db)
- return CookieIntegrationSettings(
- ga_measurement_id=cfg.ga_measurement_id,
- fb_pixel_id=cfg.fb_pixel_id,
- )
+ return CookieIntegrationSettings(ga_measurement_id=cfg.ga_measurement_id, fb_pixel_id=cfg.fb_pixel_id)
@staticmethod
- def update_integrations(
- db: Session, settings: CookieIntegrationSettings, updated_by: User | None
- ) -> CookieIntegrationConfig:
+ def update_integrations(db: Session, settings: CookieIntegrationSettings, updated_by: User | None) -> CookieIntegrationConfig:
cfg = PrivacyAdminService.get_or_create_integrations(db)
cfg.ga_measurement_id = settings.ga_measurement_id
cfg.fb_pixel_id = settings.fb_pixel_id
@@ -91,8 +68,4 @@ class PrivacyAdminService:
policy = PrivacyAdminService.get_policy_settings(db)
integrations = PrivacyAdminService.get_integration_settings(db)
return PublicPrivacyConfig(policy=policy, integrations=integrations)
-
-
-privacy_admin_service = PrivacyAdminService()
-
-
+privacy_admin_service = PrivacyAdminService()
\ No newline at end of file
diff --git a/Backend/src/services/room_service.py b/Backend/src/services/room_service.py
index 806fb97e..dfb77a20 100644
--- a/Backend/src/services/room_service.py
+++ b/Backend/src/services/room_service.py
@@ -3,17 +3,13 @@ from sqlalchemy import func, and_, or_
from typing import Optional, List, Dict
from datetime import datetime
import os
-
from ..models.room import Room, RoomStatus
from ..models.room_type import RoomType
from ..models.review import Review, ReviewStatus
-
def normalize_images(images, base_url: str) -> List[str]:
- """Normalize image paths to absolute URLs"""
if not images:
return []
-
imgs = images
if isinstance(images, str):
try:
@@ -21,10 +17,8 @@ def normalize_images(images, base_url: str) -> List[str]:
imgs = json.loads(images)
except:
imgs = [s.strip() for s in images.split(',') if s.strip()]
-
if not isinstance(imgs, list):
return []
-
result = []
for img in imgs:
if not img:
@@ -32,372 +26,39 @@ def normalize_images(images, base_url: str) -> List[str]:
if img.startswith('http://') or img.startswith('https://'):
result.append(img)
else:
- path_part = img if img.startswith('/') else f"/{img}"
- result.append(f"{base_url}{path_part}")
-
+ path_part = img if img.startswith('/') else f'/{img}'
+ result.append(f'{base_url}{path_part}')
return result
-
def get_base_url(request) -> str:
- """Get base URL for image normalization"""
- # Try to get from environment first
- server_url = os.getenv("SERVER_URL")
+ server_url = os.getenv('SERVER_URL')
if server_url:
return server_url.rstrip('/')
-
- # Get from request host header
host = request.headers.get('host', 'localhost:8000')
- # Ensure we use the backend port if host doesn't have a port
if ':' not in host:
- host = f"{host}:8000"
-
- # Use http or https based on scheme
+ host = f'{host}:8000'
scheme = request.url.scheme if hasattr(request.url, 'scheme') else 'http'
- return f"{scheme}://{host}"
+ return f'{scheme}://{host}'
-
-async def get_rooms_with_ratings(
- db: Session,
- rooms: List[Room],
- base_url: str
-) -> List[Dict]:
- """Get rooms with calculated ratings"""
+async def get_rooms_with_ratings(db: Session, rooms: List[Room], base_url: str) -> List[Dict]:
result = []
-
for room in rooms:
- # Get review stats
- review_stats = db.query(
- func.avg(Review.rating).label('average_rating'),
- func.count(Review.id).label('total_reviews')
- ).filter(
- and_(
- Review.room_id == room.id,
- Review.status == ReviewStatus.approved
- )
- ).first()
-
- room_dict = {
- "id": room.id,
- "room_type_id": room.room_type_id,
- "room_number": room.room_number,
- "floor": room.floor,
- "status": room.status.value if isinstance(room.status, RoomStatus) else room.status,
- "price": float(room.price) if room.price else 0.0,
- "featured": room.featured,
- "description": room.description,
- "capacity": room.capacity,
- "room_size": room.room_size,
- "view": room.view,
- "amenities": room.amenities,
- "created_at": room.created_at.isoformat() if room.created_at else None,
- "updated_at": room.updated_at.isoformat() if room.updated_at else None,
- "average_rating": round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None,
- "total_reviews": review_stats.total_reviews or 0 if review_stats else 0,
- }
-
- # Normalize images
+ review_stats = db.query(func.avg(Review.rating).label('average_rating'), func.count(Review.id).label('total_reviews')).filter(and_(Review.room_id == room.id, Review.status == ReviewStatus.approved)).first()
+ room_dict = {'id': room.id, 'room_type_id': room.room_type_id, 'room_number': room.room_number, 'floor': room.floor, 'status': room.status.value if isinstance(room.status, RoomStatus) else room.status, 'price': float(room.price) if room.price else 0.0, 'featured': room.featured, 'description': room.description, 'capacity': room.capacity, 'room_size': room.room_size, 'view': room.view, 'amenities': room.amenities, 'created_at': room.created_at.isoformat() if room.created_at else None, 'updated_at': room.updated_at.isoformat() if room.updated_at else None, 'average_rating': round(float(review_stats.average_rating or 0), 1) if review_stats and review_stats.average_rating else None, 'total_reviews': review_stats.total_reviews or 0 if review_stats else 0}
try:
- room_dict["images"] = normalize_images(room.images, base_url)
+ room_dict['images'] = normalize_images(room.images, base_url)
except:
- room_dict["images"] = []
-
- # Add room type info
+ room_dict['images'] = []
if room.room_type:
- room_dict["room_type"] = {
- "id": room.room_type.id,
- "name": room.room_type.name,
- "description": room.room_type.description,
- "base_price": float(room.room_type.base_price) if room.room_type.base_price else 0.0,
- "capacity": room.room_type.capacity,
- "amenities": room.room_type.amenities,
- "images": [] # RoomType doesn't have images column in DB
- }
-
+ room_dict['room_type'] = {'id': room.room_type.id, 'name': room.room_type.name, 'description': room.room_type.description, 'base_price': float(room.room_type.base_price) if room.room_type.base_price else 0.0, 'capacity': room.room_type.capacity, 'amenities': room.room_type.amenities, 'images': []}
result.append(room_dict)
-
return result
-
def get_predefined_amenities() -> List[str]:
- """Get comprehensive list of predefined hotel room amenities"""
- return [
- # Basic Amenities
- "Free WiFi",
- "WiFi",
- "High-Speed Internet",
- "WiFi in Room",
-
- # Entertainment
- "Flat-Screen TV",
- "TV",
- "Cable TV",
- "Satellite TV",
- "Smart TV",
- "Netflix",
- "Streaming Services",
- "DVD Player",
- "Stereo System",
- "Radio",
- "iPod Dock",
-
- # Climate Control
- "Air Conditioning",
- "AC",
- "Heating",
- "Climate Control",
- "Ceiling Fan",
- "Air Purifier",
-
- # Bathroom Features
- "Private Bathroom",
- "Ensuite Bathroom",
- "Bathtub",
- "Jacuzzi Bathtub",
- "Hot Tub",
- "Shower",
- "Rain Shower",
- "Walk-in Shower",
- "Bidet",
- "Hair Dryer",
- "Hairdryer",
- "Bathrobes",
- "Slippers",
- "Toiletries",
- "Premium Toiletries",
- "Towels",
-
- # Food & Beverage
- "Mini Bar",
- "Minibar",
- "Refrigerator",
- "Fridge",
- "Microwave",
- "Coffee Maker",
- "Electric Kettle",
- "Tea Making Facilities",
- "Coffee Machine",
- "Nespresso Machine",
- "Kitchenette",
- "Dining Table",
- "Room Service",
- "Breakfast Included",
- "Breakfast",
- "Complimentary Water",
- "Bottled Water",
-
- # Furniture & Space
- "Desk",
- "Writing Desk",
- "Office Desk",
- "Work Desk",
- "Sofa",
- "Sitting Area",
- "Lounge Area",
- "Dining Area",
- "Separate Living Area",
- "Wardrobe",
- "Closet",
- "Dresser",
- "Mirror",
- "Full-Length Mirror",
- "Seating Area",
-
- # Bed & Sleep
- "King Size Bed",
- "Queen Size Bed",
- "Double Bed",
- "Twin Beds",
- "Single Bed",
- "Extra Bedding",
- "Pillow Menu",
- "Premium Bedding",
- "Blackout Curtains",
- "Soundproofing",
-
- # Safety & Security
- "Safe",
- "In-Room Safe",
- "Safety Deposit Box",
- "Smoke Detector",
- "Fire Extinguisher",
- "Security System",
- "Key Card Access",
- "Door Lock",
- "Pepper Spray",
-
- # Technology
- "USB Charging Ports",
- "USB Ports",
- "USB Outlets",
- "Power Outlets",
- "Charging Station",
- "Laptop Safe",
- "HDMI Port",
- "Phone",
- "Desk Phone",
- "Wake-Up Service",
- "Alarm Clock",
- "Digital Clock",
-
- # View & Outdoor
- "Balcony",
- "Private Balcony",
- "Terrace",
- "Patio",
- "City View",
- "Ocean View",
- "Sea View",
- "Mountain View",
- "Garden View",
- "Pool View",
- "Park View",
- "Window",
- "Large Windows",
- "Floor-to-Ceiling Windows",
-
- # Services
- "24-Hour Front Desk",
- "24 Hour Front Desk",
- "24/7 Front Desk",
- "Concierge Service",
- "Butler Service",
- "Housekeeping",
- "Daily Housekeeping",
- "Turndown Service",
- "Laundry Service",
- "Dry Cleaning",
- "Ironing Service",
- "Luggage Storage",
- "Bell Service",
- "Valet Parking",
- "Parking",
- "Free Parking",
- "Airport Shuttle",
- "Shuttle Service",
- "Car Rental",
- "Taxi Service",
-
- # Fitness & Wellness
- "Gym Access",
- "Fitness Center",
- "Fitness Room",
- "Spa Access",
- "Spa",
- "Sauna",
- "Steam Room",
- "Hot Tub",
- "Massage Service",
- "Beauty Services",
-
- # Recreation
- "Swimming Pool",
- "Pool",
- "Indoor Pool",
- "Outdoor Pool",
- "Infinity Pool",
- "Pool Access",
- "Golf Course",
- "Tennis Court",
- "Beach Access",
- "Water Sports",
-
- # Business & Work
- "Business Center",
- "Meeting Room",
- "Conference Room",
- "Fax Service",
- "Photocopying",
- "Printing Service",
- "Secretarial Services",
-
- # Accessibility
- "Wheelchair Accessible",
- "Accessible Room",
- "Elevator Access",
- "Ramp Access",
- "Accessible Bathroom",
- "Lowered Sink",
- "Grab Bars",
- "Hearing Accessible",
- "Visual Alarm",
-
- # Family & Pets
- "Family Room",
- "Kids Welcome",
- "Baby Crib",
- "Extra Bed",
- "Crib",
- "Childcare Services",
- "Pets Allowed",
- "Pet Friendly",
-
- # Additional Features
- "Smoking Room",
- "Non-Smoking Room",
- "No Smoking",
- "Interconnecting Rooms",
- "Adjoining Rooms",
- "Suite",
- "Separate Bedroom",
- "Kitchen",
- "Full Kitchen",
- "Dishwasher",
- "Oven",
- "Stove",
- "Washing Machine",
- "Dryer",
- "Iron",
- "Ironing Board",
- "Clothes Rack",
- "Umbrella",
- "Shoe Shine Service",
-
- # Luxury Features
- "Fireplace",
- "Jacuzzi",
- "Steam Shower",
- "Spa Bath",
- "Bidet Toilet",
- "Smart Home System",
- "Lighting Control",
- "Curtain Control",
- "Automated Systems",
- "Personalized Service",
- "VIP Treatment",
- "Butler",
- "Private Entrance",
- "Private Elevator",
- "Panic Button",
-
- # Entertainment & Media
- "Blu-ray Player",
- "Gaming Console",
- "PlayStation",
- "Xbox",
- "Sound System",
- "Surround Sound",
- "Music System",
-
- # Special Features
- "Library",
- "Reading Room",
- "Study Room",
- "Private Pool",
- "Private Garden",
- "Yard",
- "Courtyard",
- "Outdoor Furniture",
- "BBQ Facilities",
- "Picnic Area",
- ]
-
+ return ['Free WiFi', 'WiFi', 'High-Speed Internet', 'WiFi in Room', 'Flat-Screen TV', 'TV', 'Cable TV', 'Satellite TV', 'Smart TV', 'Netflix', 'Streaming Services', 'DVD Player', 'Stereo System', 'Radio', 'iPod Dock', 'Air Conditioning', 'AC', 'Heating', 'Climate Control', 'Ceiling Fan', 'Air Purifier', 'Private Bathroom', 'Ensuite Bathroom', 'Bathtub', 'Jacuzzi Bathtub', 'Hot Tub', 'Shower', 'Rain Shower', 'Walk-in Shower', 'Bidet', 'Hair Dryer', 'Hairdryer', 'Bathrobes', 'Slippers', 'Toiletries', 'Premium Toiletries', 'Towels', 'Mini Bar', 'Minibar', 'Refrigerator', 'Fridge', 'Microwave', 'Coffee Maker', 'Electric Kettle', 'Tea Making Facilities', 'Coffee Machine', 'Nespresso Machine', 'Kitchenette', 'Dining Table', 'Room Service', 'Breakfast Included', 'Breakfast', 'Complimentary Water', 'Bottled Water', 'Desk', 'Writing Desk', 'Office Desk', 'Work Desk', 'Sofa', 'Sitting Area', 'Lounge Area', 'Dining Area', 'Separate Living Area', 'Wardrobe', 'Closet', 'Dresser', 'Mirror', 'Full-Length Mirror', 'Seating Area', 'King Size Bed', 'Queen Size Bed', 'Double Bed', 'Twin Beds', 'Single Bed', 'Extra Bedding', 'Pillow Menu', 'Premium Bedding', 'Blackout Curtains', 'Soundproofing', 'Safe', 'In-Room Safe', 'Safety Deposit Box', 'Smoke Detector', 'Fire Extinguisher', 'Security System', 'Key Card Access', 'Door Lock', 'Pepper Spray', 'USB Charging Ports', 'USB Ports', 'USB Outlets', 'Power Outlets', 'Charging Station', 'Laptop Safe', 'HDMI Port', 'Phone', 'Desk Phone', 'Wake-Up Service', 'Alarm Clock', 'Digital Clock', 'Balcony', 'Private Balcony', 'Terrace', 'Patio', 'City View', 'Ocean View', 'Sea View', 'Mountain View', 'Garden View', 'Pool View', 'Park View', 'Window', 'Large Windows', 'Floor-to-Ceiling Windows', '24-Hour Front Desk', '24 Hour Front Desk', '24/7 Front Desk', 'Concierge Service', 'Butler Service', 'Housekeeping', 'Daily Housekeeping', 'Turndown Service', 'Laundry Service', 'Dry Cleaning', 'Ironing Service', 'Luggage Storage', 'Bell Service', 'Valet Parking', 'Parking', 'Free Parking', 'Airport Shuttle', 'Shuttle Service', 'Car Rental', 'Taxi Service', 'Gym Access', 'Fitness Center', 'Fitness Room', 'Spa Access', 'Spa', 'Sauna', 'Steam Room', 'Hot Tub', 'Massage Service', 'Beauty Services', 'Swimming Pool', 'Pool', 'Indoor Pool', 'Outdoor Pool', 'Infinity Pool', 'Pool Access', 'Golf Course', 'Tennis Court', 'Beach Access', 'Water Sports', 'Business Center', 'Meeting Room', 'Conference Room', 'Fax Service', 'Photocopying', 'Printing Service', 'Secretarial Services', 'Wheelchair Accessible', 'Accessible Room', 'Elevator Access', 'Ramp Access', 'Accessible Bathroom', 'Lowered Sink', 'Grab Bars', 'Hearing Accessible', 'Visual Alarm', 'Family Room', 'Kids Welcome', 'Baby Crib', 'Extra Bed', 'Crib', 'Childcare Services', 'Pets Allowed', 'Pet Friendly', 'Smoking Room', 'Non-Smoking Room', 'No Smoking', 'Interconnecting Rooms', 'Adjoining Rooms', 'Suite', 'Separate Bedroom', 'Kitchen', 'Full Kitchen', 'Dishwasher', 'Oven', 'Stove', 'Washing Machine', 'Dryer', 'Iron', 'Ironing Board', 'Clothes Rack', 'Umbrella', 'Shoe Shine Service', 'Fireplace', 'Jacuzzi', 'Steam Shower', 'Spa Bath', 'Bidet Toilet', 'Smart Home System', 'Lighting Control', 'Curtain Control', 'Automated Systems', 'Personalized Service', 'VIP Treatment', 'Butler', 'Private Entrance', 'Private Elevator', 'Panic Button', 'Blu-ray Player', 'Gaming Console', 'PlayStation', 'Xbox', 'Sound System', 'Surround Sound', 'Music System', 'Library', 'Reading Room', 'Study Room', 'Private Pool', 'Private Garden', 'Yard', 'Courtyard', 'Outdoor Furniture', 'BBQ Facilities', 'Picnic Area']
async def get_amenities_list(db: Session) -> List[str]:
- """Get all unique amenities from room types and rooms, plus predefined amenities"""
- # Start with predefined comprehensive list
all_amenities = set(get_predefined_amenities())
-
- # Get from room types
room_types = db.query(RoomType.amenities).all()
for rt in room_types:
if rt.amenities:
@@ -413,8 +74,6 @@ async def get_amenities_list(db: Session) -> List[str]:
all_amenities.update([s.strip() for s in rt.amenities.split(',') if s.strip()])
except:
all_amenities.update([s.strip() for s in rt.amenities.split(',') if s.strip()])
-
- # Get from rooms
rooms = db.query(Room.amenities).all()
for r in rooms:
if r.amenities:
@@ -430,7 +89,4 @@ async def get_amenities_list(db: Session) -> List[str]:
all_amenities.update([s.strip() for s in r.amenities.split(',') if s.strip()])
except:
all_amenities.update([s.strip() for s in r.amenities.split(',') if s.strip()])
-
- # Return unique, sorted values
- return sorted(list(all_amenities))
-
+ return sorted(list(all_amenities))
\ No newline at end of file
diff --git a/Backend/src/services/stripe_service.py b/Backend/src/services/stripe_service.py
index fd94ea8e..a24cde4a 100644
--- a/Backend/src/services/stripe_service.py
+++ b/Backend/src/services/stripe_service.py
@@ -1,6 +1,3 @@
-"""
-Stripe payment service for processing card payments
-"""
import logging
import stripe
from typing import Optional, Dict, Any
@@ -10,333 +7,152 @@ from ..models.booking import Booking, BookingStatus
from ..models.system_settings import SystemSettings
from sqlalchemy.orm import Session
from datetime import datetime
-
logger = logging.getLogger(__name__)
-
def get_stripe_secret_key(db: Session) -> Optional[str]:
- """Get Stripe secret key from database or environment variable"""
try:
- setting = db.query(SystemSettings).filter(
- SystemSettings.key == "stripe_secret_key"
- ).first()
+ setting = db.query(SystemSettings).filter(SystemSettings.key == 'stripe_secret_key').first()
if setting and setting.value:
return setting.value
except Exception:
pass
- # Fallback to environment variable
return settings.STRIPE_SECRET_KEY if settings.STRIPE_SECRET_KEY else None
-
def get_stripe_publishable_key(db: Session) -> Optional[str]:
- """Get Stripe publishable key from database or environment variable"""
try:
- setting = db.query(SystemSettings).filter(
- SystemSettings.key == "stripe_publishable_key"
- ).first()
+ setting = db.query(SystemSettings).filter(SystemSettings.key == 'stripe_publishable_key').first()
if setting and setting.value:
return setting.value
except Exception:
pass
- # Fallback to environment variable
return settings.STRIPE_PUBLISHABLE_KEY if settings.STRIPE_PUBLISHABLE_KEY else None
-
def get_stripe_webhook_secret(db: Session) -> Optional[str]:
- """Get Stripe webhook secret from database or environment variable"""
try:
- setting = db.query(SystemSettings).filter(
- SystemSettings.key == "stripe_webhook_secret"
- ).first()
+ setting = db.query(SystemSettings).filter(SystemSettings.key == 'stripe_webhook_secret').first()
if setting and setting.value:
return setting.value
except Exception:
pass
- # Fallback to environment variable
return settings.STRIPE_WEBHOOK_SECRET if settings.STRIPE_WEBHOOK_SECRET else None
-
class StripeService:
- """Service for handling Stripe payments"""
-
+
@staticmethod
- def create_payment_intent(
- amount: float,
- currency: str = "usd",
- metadata: Optional[Dict[str, Any]] = None,
- customer_id: Optional[str] = None,
- db: Optional[Session] = None
- ) -> Dict[str, Any]:
- """
- Create a Stripe Payment Intent
-
- Args:
- amount: Payment amount in smallest currency unit (cents for USD)
- currency: Currency code (default: usd)
- metadata: Additional metadata to attach to the payment intent
- customer_id: Optional Stripe customer ID
- db: Optional database session to get keys from database
-
- Returns:
- Payment intent object
- """
- # Get secret key from database or environment
+ def create_payment_intent(amount: float, currency: str='usd', metadata: Optional[Dict[str, Any]]=None, customer_id: Optional[str]=None, db: Optional[Session]=None) -> Dict[str, Any]:
secret_key = None
if db:
secret_key = get_stripe_secret_key(db)
if not secret_key:
secret_key = settings.STRIPE_SECRET_KEY
-
if not secret_key:
- raise ValueError("Stripe secret key is not configured")
-
- # Set the API key for this request
+ raise ValueError('Stripe secret key is not configured')
stripe.api_key = secret_key
-
- # Validate amount is reasonable (Stripe max is $999,999.99)
if amount <= 0:
- raise ValueError("Amount must be greater than 0")
+ raise ValueError('Amount must be greater than 0')
if amount > 999999.99:
raise ValueError(f"Amount ${amount:,.2f} exceeds Stripe's maximum of $999,999.99")
-
- # Convert amount to cents (smallest currency unit)
- # Amount should be in dollars, so multiply by 100 to get cents
amount_in_cents = int(round(amount * 100))
-
- # Double-check the cents amount doesn't exceed Stripe's limit
- if amount_in_cents > 99999999: # $999,999.99 in cents
+ if amount_in_cents > 99999999:
raise ValueError(f"Amount ${amount:,.2f} (${amount_in_cents} cents) exceeds Stripe's maximum")
-
- intent_params = {
- "amount": amount_in_cents,
- "currency": currency,
- "automatic_payment_methods": {
- "enabled": True,
- },
- "metadata": metadata or {},
- }
-
+ intent_params = {'amount': amount_in_cents, 'currency': currency, 'automatic_payment_methods': {'enabled': True}, 'metadata': metadata or {}}
if customer_id:
- intent_params["customer"] = customer_id
-
+ intent_params['customer'] = customer_id
try:
intent = stripe.PaymentIntent.create(**intent_params)
- return {
- "client_secret": intent.client_secret,
- "id": intent.id,
- "status": intent.status,
- "amount": intent.amount,
- "currency": intent.currency,
- }
+ return {'client_secret': intent.client_secret, 'id': intent.id, 'status': intent.status, 'amount': intent.amount, 'currency': intent.currency}
except stripe.StripeError as e:
- raise ValueError(f"Stripe error: {str(e)}")
-
+ raise ValueError(f'Stripe error: {str(e)}')
+
@staticmethod
- def retrieve_payment_intent(
- payment_intent_id: str,
- db: Optional[Session] = None
- ) -> Dict[str, Any]:
- """
- Retrieve a payment intent by ID
-
- Args:
- payment_intent_id: Stripe payment intent ID
- db: Optional database session to get keys from database
-
- Returns:
- Payment intent object
- """
- # Get secret key from database or environment
+ def retrieve_payment_intent(payment_intent_id: str, db: Optional[Session]=None) -> Dict[str, Any]:
secret_key = None
if db:
secret_key = get_stripe_secret_key(db)
if not secret_key:
secret_key = settings.STRIPE_SECRET_KEY
-
if not secret_key:
- raise ValueError("Stripe secret key is not configured")
-
- # Set the API key for this request
+ raise ValueError('Stripe secret key is not configured')
stripe.api_key = secret_key
-
try:
intent = stripe.PaymentIntent.retrieve(payment_intent_id)
- # Safely access charges - they may not exist on all payment intents
charges = []
if hasattr(intent, 'charges') and intent.charges:
charges_data = getattr(intent.charges, 'data', [])
- charges = [
- {
- "id": charge.id,
- "paid": charge.paid,
- "status": charge.status,
- }
- for charge in charges_data
- ]
-
- return {
- "id": intent.id,
- "status": intent.status,
- "amount": intent.amount / 100, # Convert from cents
- "currency": intent.currency,
- "metadata": intent.metadata,
- "charges": charges,
- }
+ charges = [{'id': charge.id, 'paid': charge.paid, 'status': charge.status} for charge in charges_data]
+ return {'id': intent.id, 'status': intent.status, 'amount': intent.amount / 100, 'currency': intent.currency, 'metadata': intent.metadata, 'charges': charges}
except stripe.StripeError as e:
- raise ValueError(f"Stripe error: {str(e)}")
-
+ raise ValueError(f'Stripe error: {str(e)}')
+
@staticmethod
- async def confirm_payment(
- payment_intent_id: str,
- db: Session,
- booking_id: Optional[int] = None
- ) -> Dict[str, Any]:
- """
- Confirm a payment and update database records
-
- Args:
- payment_intent_id: Stripe payment intent ID
- db: Database session
- booking_id: Optional booking ID for metadata lookup
-
- Returns:
- Payment record dictionary
- """
+ async def confirm_payment(payment_intent_id: str, db: Session, booking_id: Optional[int]=None) -> Dict[str, Any]:
try:
intent_data = StripeService.retrieve_payment_intent(payment_intent_id, db)
-
- # Find or get booking_id from metadata
- if not booking_id and intent_data.get("metadata"):
- booking_id = intent_data["metadata"].get("booking_id")
+ if not booking_id and intent_data.get('metadata'):
+ booking_id = intent_data['metadata'].get('booking_id')
if booking_id:
booking_id = int(booking_id)
-
if not booking_id:
- raise ValueError("Booking ID is required")
-
+ raise ValueError('Booking ID is required')
booking = db.query(Booking).filter(Booking.id == booking_id).first()
if not booking:
- raise ValueError("Booking not found")
-
- # Check payment intent status
- payment_status = intent_data.get("status")
- print(f"Payment intent status: {payment_status}")
-
- # Accept succeeded or processing status (processing means payment is being processed)
- if payment_status not in ["succeeded", "processing"]:
- raise ValueError(f"Payment intent not in a valid state. Status: {payment_status}. Payment may still be processing or may have failed.")
-
- # Find existing payment or create new one
- payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.transaction_id == payment_intent_id,
- Payment.payment_method == PaymentMethod.stripe
- ).first()
-
- # If not found, try to find pending deposit payment (for cash bookings with deposit)
- # This allows updating the payment_method from the default to stripe
+ raise ValueError('Booking not found')
+ payment_status = intent_data.get('status')
+ print(f'Payment intent status: {payment_status}')
+ if payment_status not in ['succeeded', 'processing']:
+ raise ValueError(f'Payment intent not in a valid state. Status: {payment_status}. Payment may still be processing or may have failed.')
+ payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.transaction_id == payment_intent_id, Payment.payment_method == PaymentMethod.stripe).first()
if not payment:
- payment = db.query(Payment).filter(
- Payment.booking_id == booking_id,
- Payment.payment_type == PaymentType.deposit,
- Payment.payment_status == PaymentStatus.pending
- ).order_by(Payment.created_at.desc()).first()
-
- amount = intent_data["amount"]
-
+ payment = db.query(Payment).filter(Payment.booking_id == booking_id, Payment.payment_type == PaymentType.deposit, Payment.payment_status == PaymentStatus.pending).order_by(Payment.created_at.desc()).first()
+ amount = intent_data['amount']
if payment:
- # Update existing payment
- # Only mark as completed if payment intent succeeded
- if payment_status == "succeeded":
+ if payment_status == 'succeeded':
payment.payment_status = PaymentStatus.completed
payment.payment_date = datetime.utcnow()
- # If processing, keep as pending (will be updated by webhook)
payment.amount = amount
- payment.payment_method = PaymentMethod.stripe # Update payment method to Stripe
+ payment.payment_method = PaymentMethod.stripe
else:
- # Create new payment record
payment_type = PaymentType.full
- if booking.requires_deposit and not booking.deposit_paid:
+ if booking.requires_deposit and (not booking.deposit_paid):
payment_type = PaymentType.deposit
-
- # Only mark as completed if payment intent succeeded
- payment_status_enum = PaymentStatus.completed if payment_status == "succeeded" else PaymentStatus.pending
- payment_date = datetime.utcnow() if payment_status == "succeeded" else None
-
- payment = Payment(
- booking_id=booking_id,
- amount=amount,
- payment_method=PaymentMethod.stripe,
- payment_type=payment_type,
- payment_status=payment_status_enum,
- transaction_id=payment_intent_id,
- payment_date=payment_date,
- notes=f"Stripe payment - Intent: {payment_intent_id} (Status: {payment_status})",
- )
+ payment_status_enum = PaymentStatus.completed if payment_status == 'succeeded' else PaymentStatus.pending
+ payment_date = datetime.utcnow() if payment_status == 'succeeded' else None
+ payment = Payment(booking_id=booking_id, amount=amount, payment_method=PaymentMethod.stripe, payment_type=payment_type, payment_status=payment_status_enum, transaction_id=payment_intent_id, payment_date=payment_date, notes=f'Stripe payment - Intent: {payment_intent_id} (Status: {payment_status})')
db.add(payment)
-
- # Commit payment first to ensure it's saved
db.commit()
db.refresh(payment)
-
- # Update booking status only if payment is completed
if payment.payment_status == PaymentStatus.completed:
- # Refresh booking to get updated payments relationship
db.refresh(booking)
-
- # Calculate total paid from all completed payments (now includes current payment)
- # This needs to be calculated before the if/elif blocks
- total_paid = sum(
- float(p.amount) for p in booking.payments
- if p.payment_status == PaymentStatus.completed
- )
-
- # Update invoice status based on payment
+ total_paid = sum((float(p.amount) for p in booking.payments if p.payment_status == PaymentStatus.completed))
from ..models.invoice import Invoice, InvoiceStatus
from ..services.invoice_service import InvoiceService
-
- # Find invoices for this booking and update their status
invoices = db.query(Invoice).filter(Invoice.booking_id == booking_id).all()
for invoice in invoices:
- # Update invoice amount_paid and balance_due
invoice.amount_paid = total_paid
invoice.balance_due = float(invoice.total_amount) - total_paid
-
- # Update invoice status
if invoice.balance_due <= 0:
invoice.status = InvoiceStatus.paid
invoice.paid_date = datetime.utcnow()
elif invoice.amount_paid > 0:
invoice.status = InvoiceStatus.sent
-
booking_was_confirmed = False
should_send_email = False
if payment.payment_type == PaymentType.deposit:
- # Mark deposit as paid and confirm booking
booking.deposit_paid = True
- # Restore cancelled bookings or confirm pending bookings
if booking.status in [BookingStatus.pending, BookingStatus.cancelled]:
booking.status = BookingStatus.confirmed
booking_was_confirmed = True
should_send_email = True
elif booking.status == BookingStatus.confirmed:
- # Booking already confirmed, but deposit was just paid
should_send_email = True
elif payment.payment_type == PaymentType.full:
- # Confirm booking if:
- # 1. Total paid (all payments) covers the booking price, OR
- # 2. This single payment covers the entire booking amount
- # Also restore cancelled bookings when payment succeeds
if total_paid >= float(booking.total_price) or float(payment.amount) >= float(booking.total_price):
if booking.status in [BookingStatus.pending, BookingStatus.cancelled]:
booking.status = BookingStatus.confirmed
booking_was_confirmed = True
should_send_email = True
elif booking.status == BookingStatus.confirmed:
- # Booking already confirmed, but full payment was just completed
should_send_email = True
-
- # Send booking confirmation email if booking was just confirmed or payment completed
if should_send_email:
try:
from ..utils.mailer import send_email
@@ -346,208 +162,109 @@ class StripeService:
from sqlalchemy.orm import selectinload
import os
from ..config.settings import settings
-
- # Get client URL from settings
- 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"))
-
- # Get platform currency for email
- currency_setting = db.query(SystemSettings).filter(SystemSettings.key == "platform_currency").first()
- currency = currency_setting.value if currency_setting and currency_setting.value else "USD"
-
- # Get currency symbol
- currency_symbols = {
- "USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "¥",
- "KRW": "₩", "SGD": "S$", "THB": "฿", "AUD": "A$", "CAD": "C$",
- "VND": "₫", "INR": "₹", "CHF": "CHF", "NZD": "NZ$"
- }
+ 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')
+ 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)
-
- # Load booking with room details for email
- booking_with_room = db.query(Booking).options(
- selectinload(Booking.room).selectinload(Room.room_type)
- ).filter(Booking.id == booking_id).first()
-
+ 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"
-
- # Calculate amount paid and remaining due
+ room_type_name = room.room_type.name if room and room.room_type else 'Room'
amount_paid = total_paid
payment_type_str = payment.payment_type.value if payment.payment_type else None
-
- 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=False, # Payment completed, no deposit message needed
- deposit_amount=None,
- amount_paid=amount_paid,
- payment_type=payment_type_str,
- client_url=client_url,
- currency_symbol=currency_symbol
- )
+ 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=False, deposit_amount=None, amount_paid=amount_paid, payment_type=payment_type_str, client_url=client_url, currency_symbol=currency_symbol)
if booking.user:
- await send_email(
- to=booking.user.email,
- subject=f"Booking Confirmed - {booking.booking_number}",
- html=email_html
- )
- logger.info(f"Booking confirmation email sent to {booking.user.email}")
+ await send_email(to=booking.user.email, subject=f'Booking Confirmed - {booking.booking_number}', html=email_html)
+ logger.info(f'Booking confirmation email sent to {booking.user.email}')
except Exception as email_error:
- logger.error(f"Failed to send booking confirmation email: {str(email_error)}")
-
- # Send invoice email if payment is completed and invoice is now paid
+ logger.error(f'Failed to send booking confirmation email: {str(email_error)}')
from ..utils.mailer import send_email
from ..services.invoice_service import InvoiceService
from ..routes.booking_routes import _generate_invoice_email_html
-
- # Load user for email
from ..models.user import User
user = db.query(User).filter(User.id == booking.user_id).first()
-
for invoice in invoices:
if invoice.status == InvoiceStatus.paid and invoice.balance_due <= 0:
try:
invoice_dict = InvoiceService.invoice_to_dict(invoice)
invoice_html = _generate_invoice_email_html(invoice_dict, is_proforma=invoice.is_proforma)
- invoice_type = "Proforma Invoice" if invoice.is_proforma else "Invoice"
+ invoice_type = 'Proforma Invoice' if invoice.is_proforma else 'Invoice'
if user:
- await send_email(
- to=user.email,
- subject=f"{invoice_type} {invoice.invoice_number} - Payment Confirmed",
- html=invoice_html
- )
- logger.info(f"{invoice_type} {invoice.invoice_number} sent to {user.email}")
+ await send_email(to=user.email, subject=f'{invoice_type} {invoice.invoice_number} - Payment Confirmed', html=invoice_html)
+ logger.info(f'{invoice_type} {invoice.invoice_number} sent to {user.email}')
except Exception as email_error:
- logger.error(f"Failed to send invoice email: {str(email_error)}")
-
- # Commit booking and invoice status updates
+ logger.error(f'Failed to send invoice email: {str(email_error)}')
db.commit()
db.refresh(booking)
-
- # Safely get enum values
+
def get_enum_value(enum_obj):
- """Safely extract value from enum or return as-is"""
if enum_obj is None:
return None
if isinstance(enum_obj, (PaymentMethod, PaymentType, PaymentStatus)):
return enum_obj.value
return enum_obj
-
try:
- return {
- "id": payment.id,
- "booking_id": payment.booking_id,
- "amount": float(payment.amount) if payment.amount else 0.0,
- "payment_method": get_enum_value(payment.payment_method),
- "payment_type": get_enum_value(payment.payment_type),
- "payment_status": get_enum_value(payment.payment_status),
- "transaction_id": payment.transaction_id,
- "payment_date": payment.payment_date.isoformat() if payment.payment_date else None,
- }
+ return {'id': payment.id, 'booking_id': payment.booking_id, 'amount': float(payment.amount) if payment.amount else 0.0, 'payment_method': get_enum_value(payment.payment_method), 'payment_type': get_enum_value(payment.payment_type), 'payment_status': get_enum_value(payment.payment_status), 'transaction_id': payment.transaction_id, 'payment_date': payment.payment_date.isoformat() if payment.payment_date else None}
except AttributeError as ae:
- print(f"AttributeError accessing payment fields: {ae}")
- print(f"Payment object: {payment}")
- print(f"Payment payment_method: {payment.payment_method if hasattr(payment, 'payment_method') else 'missing'}")
- print(f"Payment payment_type: {payment.payment_type if hasattr(payment, 'payment_type') else 'missing'}")
- print(f"Payment payment_status: {payment.payment_status if hasattr(payment, 'payment_status') else 'missing'}")
+ print(f'AttributeError accessing payment fields: {ae}')
+ print(f'Payment object: {payment}')
+ print(f'Payment payment_method: {(payment.payment_method if hasattr(payment, 'payment_method') else 'missing')}')
+ print(f'Payment payment_type: {(payment.payment_type if hasattr(payment, 'payment_type') else 'missing')}')
+ print(f'Payment payment_status: {(payment.payment_status if hasattr(payment, 'payment_status') else 'missing')}')
raise
-
except ValueError as e:
- # Re-raise ValueError as-is (these are expected errors)
db.rollback()
raise
except Exception as e:
import traceback
error_details = traceback.format_exc()
- error_msg = str(e) if str(e) else f"{type(e).__name__}: {repr(e)}"
- print(f"Error in confirm_payment: {error_msg}")
- print(f"Traceback: {error_details}")
+ error_msg = str(e) if str(e) else f'{type(e).__name__}: {repr(e)}'
+ print(f'Error in confirm_payment: {error_msg}')
+ print(f'Traceback: {error_details}')
db.rollback()
- raise ValueError(f"Error confirming payment: {error_msg}")
-
+ raise ValueError(f'Error confirming payment: {error_msg}')
+
@staticmethod
- async def handle_webhook(
- payload: bytes,
- signature: str,
- db: Session
- ) -> Dict[str, Any]:
- """
- Handle Stripe webhook events
-
- Args:
- payload: Raw webhook payload
- signature: Stripe signature header
- db: Database session
-
- Returns:
- Webhook event data
- """
+ async def handle_webhook(payload: bytes, signature: str, db: Session) -> Dict[str, Any]:
webhook_secret = get_stripe_webhook_secret(db)
if not webhook_secret:
webhook_secret = settings.STRIPE_WEBHOOK_SECRET
-
if not webhook_secret:
- raise ValueError("Stripe webhook secret is not configured. Please configure it in Admin Panel (Settings > Stripe Settings) or set STRIPE_WEBHOOK_SECRET environment variable.")
-
+ raise ValueError('Stripe webhook secret is not configured. Please configure it in Admin Panel (Settings > Stripe Settings) or set STRIPE_WEBHOOK_SECRET environment variable.')
try:
- event = stripe.Webhook.construct_event(
- payload, signature, webhook_secret
- )
+ event = stripe.Webhook.construct_event(payload, signature, webhook_secret)
except ValueError as e:
- raise ValueError(f"Invalid payload: {str(e)}")
+ raise ValueError(f'Invalid payload: {str(e)}')
except stripe.SignatureVerificationError as e:
- raise ValueError(f"Invalid signature: {str(e)}")
-
- # Handle the event
- if event["type"] == "payment_intent.succeeded":
- payment_intent = event["data"]["object"]
- payment_intent_id = payment_intent["id"]
- metadata = payment_intent.get("metadata", {})
- booking_id = metadata.get("booking_id")
-
+ raise ValueError(f'Invalid signature: {str(e)}')
+ if event['type'] == 'payment_intent.succeeded':
+ payment_intent = event['data']['object']
+ payment_intent_id = payment_intent['id']
+ metadata = payment_intent.get('metadata', {})
+ booking_id = metadata.get('booking_id')
if booking_id:
- try:
- await StripeService.confirm_payment(
- payment_intent_id=payment_intent_id,
- db=db,
- booking_id=int(booking_id)
- )
- except Exception as e:
- import logging
- logger = logging.getLogger(__name__)
- logger.error(f"Error processing webhook for booking {booking_id}: {str(e)}")
-
- elif event["type"] == "payment_intent.payment_failed":
- payment_intent = event["data"]["object"]
- payment_intent_id = payment_intent["id"]
- metadata = payment_intent.get("metadata", {})
- booking_id = metadata.get("booking_id")
-
+ try:
+ await StripeService.confirm_payment(payment_intent_id=payment_intent_id, db=db, booking_id=int(booking_id))
+ except Exception as e:
+ import logging
+ logger = logging.getLogger(__name__)
+ logger.error(f'Error processing webhook for booking {booking_id}: {str(e)}')
+ elif event['type'] == 'payment_intent.payment_failed':
+ payment_intent = event['data']['object']
+ payment_intent_id = payment_intent['id']
+ metadata = payment_intent.get('metadata', {})
+ booking_id = metadata.get('booking_id')
if booking_id:
- # Update payment status to failed
- payment = db.query(Payment).filter(
- Payment.transaction_id == payment_intent_id,
- Payment.booking_id == int(booking_id)
- ).first()
-
+ payment = db.query(Payment).filter(Payment.transaction_id == payment_intent_id, Payment.booking_id == int(booking_id)).first()
if payment:
payment.payment_status = PaymentStatus.failed
db.commit()
-
- # Auto-cancel booking when payment fails
booking = db.query(Booking).filter(Booking.id == int(booking_id)).first()
if booking and booking.status != BookingStatus.cancelled:
booking.status = BookingStatus.cancelled
db.commit()
db.refresh(booking)
-
- # Send cancellation email (non-blocking)
try:
if booking.user:
from ..utils.mailer import send_email
@@ -555,30 +272,12 @@ class StripeService:
from ..models.system_settings import SystemSettings
from ..config.settings import settings
import os
-
- # Get client URL from settings
- 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"))
-
- 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,
- subject=f"Booking Cancelled - {booking.booking_number}",
- html=email_html
- )
+ 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')
+ 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, 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 cancellation email: {e}")
-
- return {
- "status": "success",
- "event_type": event["type"],
- "event_id": event["id"],
- }
-
+ logger.error(f'Failed to send cancellation email: {e}')
+ return {'status': 'success', 'event_type': event['type'], 'event_id': event['id']}
\ No newline at end of file
diff --git a/Backend/src/utils/email_templates.py b/Backend/src/utils/email_templates.py
index 4c9c97fb..18bda82f 100644
--- a/Backend/src/utils/email_templates.py
+++ b/Backend/src/utils/email_templates.py
@@ -1,14 +1,9 @@
-"""
-Email templates for various notifications
-"""
from datetime import datetime
from typing import Optional
from ..config.database import SessionLocal
from ..models.system_settings import SystemSettings
-
def _get_company_settings():
- """Get company settings from database"""
try:
db = SessionLocal()
try:
@@ -44,9 +39,7 @@ def _get_company_settings():
"company_address": None,
}
-
def get_base_template(content: str, title: str = "Hotel Booking", client_url: str = "http://localhost:5173") -> str:
- """Luxury HTML email template with premium company branding"""
company_settings = _get_company_settings()
company_name = company_settings.get("company_name") or "Hotel Booking"
company_tagline = company_settings.get("company_tagline") or "Excellence Redefined"
@@ -55,12 +48,12 @@ def get_base_template(content: str, title: str = "Hotel Booking", client_url: st
company_email = company_settings.get("company_email")
company_address = company_settings.get("company_address")
- # Build logo HTML if logo exists
+
logo_html = ""
if company_logo_url:
- # Convert relative URL to absolute if needed
+
if not company_logo_url.startswith('http'):
- # Try to construct full URL
+
server_url = client_url.replace('://localhost:5173', '').replace('://localhost:3000', '')
if not server_url.startswith('http'):
server_url = f"http://{server_url}" if ':' not in server_url.split('//')[-1] else server_url
@@ -68,187 +61,45 @@ def get_base_template(content: str, title: str = "Hotel Booking", client_url: st
else:
full_logo_url = company_logo_url
- logo_html = f'''
-
-
- {f'
{company_tagline}
' if company_tagline else ''}
-
- '''
+ logo_html = f
else:
- logo_html = f'''
-
-
{company_name}
- {f'
{company_tagline}
' if company_tagline else ''}
-
- '''
+ logo_html = f
- # Build footer contact info
+
footer_contact = ""
if company_phone or company_email or company_address:
- footer_contact = '''
-