You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mysql/booking_management.py

63 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from .room_management import Room, Base # 假设room_management.py在同一包内或根据实际情况调整导入路径
# 预订模型
class Booking(Base):
__tablename__ = 'bookings' # 注意双下划线的正确使用
id = Column(Integer, primary_key=True)
room_id = Column(Integer, ForeignKey('rooms.id'), nullable=False)
guest_name = Column(String, nullable=False)
start_date = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc)) # 使用时区感知的默认值
end_date = Column(DateTime, nullable=False)
room = relationship("Room", back_populates="bookings")
def __repr__(self):
return f"Booking(id={self.id}, room={self.room.room_number}, guest='{self.guest_name}', start_date={self.start_date}, end_date={self.end_date})"
# 初始化Room模型与Booking之间的关系
Room.bookings = relationship("Booking", order_by=Booking.id, back_populates="room")
def make_booking(room_number, guest_name, start_date_str, end_date_str):
"""创建预订"""
from dateutil.parser import parse
try:
start_date = parse(start_date_str).replace(tzinfo=None)
end_date = parse(end_date_str).replace(tzinfo=None)
room = session.query(Room).filter_by(room_number=room_number, status='available').first()
if not room:
return "该房间不可用或不存在。"
new_booking = Booking(guest_name=guest_name, start_date=start_date, end_date=end_date, room=room)
room.status = 'occupied'
session.add(new_booking)
session.commit()
return f"{guest_name} 的预订成功,房间号:{room_number},时间:{start_date}{end_date}"
except Exception as e:
return str(e)
def cancel_booking(booking_id):
"""取消预订"""
booking = session.query(Booking).get(booking_id)
if not booking:
return "预订记录不存在。"
room = booking.room
room.status = 'available'
session.delete(booking)
session.commit()
return f"预订ID为{booking_id}的预订已取消。"
def get_bookings_by_guest(guest_name=None):
"""按客人姓名获取预订记录"""
query = session.query(Booking)
if guest_name:
query = query.filter_by(guest_name=guest_name)
return query.all()
def get_bookings_by_room(room_number):
"""按房间号获取预订记录"""
room = session.query(Room).filter_by(room_number=room_number).first()
if not room:
return []
return room.bookings