Fixed room upsert logic
This commit is contained in:
@@ -731,17 +731,10 @@ class ConversionService:
|
||||
# Flush to ensure conversion has an ID before creating room reservations
|
||||
await session.flush()
|
||||
|
||||
# Batch-load existing room reservations to avoid N+1 queries
|
||||
room_numbers = [
|
||||
rm.get("roomNumber") for rm in room_reservations.findall("roomReservation")
|
||||
]
|
||||
pms_hotel_reservation_ids = [
|
||||
f"{pms_reservation_id}_{room_num}" for room_num in room_numbers
|
||||
]
|
||||
|
||||
# Fetch ALL existing rooms for this conversion (not just the ones in current XML)
|
||||
existing_rooms_result = await session.execute(
|
||||
select(ConversionRoom).where(
|
||||
ConversionRoom.pms_hotel_reservation_id.in_(pms_hotel_reservation_ids)
|
||||
ConversionRoom.conversion_id == conversion.id
|
||||
)
|
||||
)
|
||||
existing_rooms = {
|
||||
@@ -749,6 +742,9 @@ class ConversionService:
|
||||
for room in existing_rooms_result.scalars().all()
|
||||
}
|
||||
|
||||
# Track which room IDs are present in the current XML
|
||||
current_pms_hotel_reservation_ids = set()
|
||||
|
||||
# Process room reservations
|
||||
for room_reservation in room_reservations.findall("roomReservation"):
|
||||
# Extract room reservation details
|
||||
@@ -786,6 +782,9 @@ class ConversionService:
|
||||
# This allows updating the same room reservation if it appears again
|
||||
pms_hotel_reservation_id = f"{pms_reservation_id}_{room_number}"
|
||||
|
||||
# Track this room as present in current XML
|
||||
current_pms_hotel_reservation_ids.add(pms_hotel_reservation_id)
|
||||
|
||||
# Process daily sales and extract total revenue
|
||||
daily_sales_elem = room_reservation.find("dailySales")
|
||||
daily_sales_list = []
|
||||
@@ -880,6 +879,24 @@ class ConversionService:
|
||||
num_adults,
|
||||
)
|
||||
|
||||
# Delete room entries that are no longer present in the current XML
|
||||
# This handles cases where a reservation is updated and room numbers change
|
||||
rooms_to_delete = [
|
||||
room
|
||||
for pms_id, room in existing_rooms.items()
|
||||
if pms_id not in current_pms_hotel_reservation_ids
|
||||
]
|
||||
|
||||
if rooms_to_delete:
|
||||
for room in rooms_to_delete:
|
||||
await session.delete(room)
|
||||
_LOGGER.debug(
|
||||
"Deleted room reservation %s (pms_id=%s, room=%s) - no longer in current XML",
|
||||
room.id,
|
||||
room.pms_hotel_reservation_id,
|
||||
room.room_number,
|
||||
)
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user