
    jr                         d Z ddlmZ ddlmZmZmZ ddlmZm	Z	 ddl
mZ ddlmZ ddlmZmZ ddlmZ dd	lmZ  G d
 d      Zy)z
Overview service for Aimantis dashboard.

Calculates today's operational metrics:
- Check-ins and check-outs
- Guests currently in structure
- Room occupancy status
    )date)DictAnyOptional)CountQ)Booking)Guest)PropertyPropertyType)	Structure)	get_todayc                       e Zd ZdZddee   fdZdeee	f   fdZ
d ZdefdZdefd	Zdefd
ZdefdZdefdZdefdZdefdZdeee	f   fdZy)OverviewServicez
    Service for calculating dashboard overview metrics.
    
    All calculations are optimized to minimize database queries
    and avoid N+1 problems.
    Nstructure_idc                 0    || _         t               | _        y)z
        Initialize the overview service.
        
        Args:
            structure_id: Optional structure ID for multi-tenant filtering
        N)r   r   today)selfr   s     //backend/dashboard/services/overview_service.py__init__zOverviewService.__init__   s     )[
    returnc                 :    | j                   rd| j                   iS i S )z&Get structure filter dict for queries.r   r   r   s    r   _get_structure_filterz%OverviewService._get_structure_filter)   s     6:6G6G 1 12OROr   c                     t         j                  j                         }| j                  r|j	                  | j                        }|S )zGet filtered property queryset.r   )r   objectsallr   filter)r   qss     r   _get_property_querysetz&OverviewService._get_property_queryset-   s:    !!#(9(9:B	r   c                     t        j                  j                  dd| j                  i| j	                         j                         S )z
        Count bookings checking in today.
        
        Uses check_in_date == today.
        Counts all arrivals scheduled for today regardless of check-in status.
        check_in_date r	   r   r    r   r   countr   s    r   get_checkins_todayz"OverviewService.get_checkins_today4   sA     %% 
**
((*
 %'	r   c                     t        j                  j                  dd| j                  i| j	                         j                         S )zc
        Count bookings checking out today.
        
        Uses check_out_date == today.
        check_out_dater%   r&   r   s    r   get_checkouts_todayz#OverviewService.get_checkouts_today@   sA     %% 
::
((*
 %'	r   c                    t        j                  j                  d| j                  | j                  d| j	                         j                  d      }t        j                  j                  |      j                         S )a%  
        Count guests currently staying in the structure.
        
        Uses ACTIVE booking logic (date-based, not check-in status):
        - check_in_date <= today
        - check_out_date > today (exclusive)
        
        Counts all guests from active reservations for today.
        check_in_date__ltecheck_out_date__gtid)booking__inr%   )r	   r   r    r   r   onlyr
   r'   )r   current_bookingss     r   get_guests_in_structurez'OverviewService.get_guests_in_structureK   st     #??11 
#zz#zz
 ((*
 $t*	 	 }}##( $ 

%'	r   c                 >    | j                         j                         S )z#Count total rooms in the structure.)r"   r'   r   s    r   get_total_roomszOverviewService.get_total_rooms_   s    **,2244r   c                 (   t        j                  j                  d| j                  | j                  d| j	                         j                  dd      j                         }t        j                  j                  |      j                         }|S )aV  
        Count physically occupied rooms.
        
        Uses ACTIVE booking logic (date-based, not check-in status):
        - check_in_date <= today
        - check_out_date > today (exclusive)
        
        Counts all rooms with active reservations for today.
        Returns DISTINCT property count to avoid double-counting.
        r-   property_idT)flat)id__inr%   )	r	   r   r    r   r   values_listdistinctr   r'   )r   occupied_property_idsoccupied_counts      r   get_occupied_roomsz"OverviewService.get_occupied_roomsc   s     !( 6 6 !
#zz#zz!
 ((*!
 +m$+
/
	 	 "))00( 1 

%' 	 r   c                 `    | j                         }| j                         }t        d||z
        S )zV
        Count available rooms.
        
        Available = Total - Occupied
        r   )r6   r?   max)r   totaloccupieds      r   get_available_roomsz#OverviewService.get_available_rooms}   s2     $$&**,1eh&''r   c                     t         j                  j                  d      }| j                  r|j	                  | j                        }d}|D ]/  }|t        d |j                  j                         D              z  }1 |S )z
        Count total beds across all property types in the structure.
        
        Optimized to use prefetch_related to avoid N+1 queries.
        bedsr   r   c              3   4   K   | ]  }|j                     y wN)quantity).0beds     r   	<genexpr>z1OverviewService.get_total_beds.<locals>.<genexpr>   s     Dmscllms   )r   r   prefetch_relatedr   r    sumrF   r   )r   property_types
total_bedspts       r   get_total_bedszOverviewService.get_total_beds   sr     &-->>vF+22@Q@Q2RN
 B#DbggkkmDDDJ ! r   c                     | j                         }| j                         }t        d||z
        }| j                         | j	                         | j                         |||| j                         dS )z
        Get complete overview metrics in a single optimized call.
        
        Returns:
            Dict with all overview metrics
        r   )checkins_todaycheckouts_todayguests_in_structureavailable_roomsoccupied_roomstotal_roomsrP   )r?   r6   rA   r(   r+   r4   rR   )r   rX   rY   rW   s       r   get_overviewzOverviewService.get_overview   sv     002**,a~!=> #557#779#'#?#?#A.,&--/
 	
r   rH   )__name__
__module____qualname____doc__r   intr   r   strr   r   r"   r(   r+   r4   r6   r?   rD   rR   rZ   r%   r   r   r   r      s    !Xc] !PtCH~ P
C 
	S 	 (5 5C 4(S ( $
d38n 
r   r   N)r^   datetimer   typingr   r   r   django.db.modelsr   r   bookings.modelsr	   guests.modelsr
   properties.modelsr   r   structures.modelsr   dashboard.services.utilsr   r   r%   r   r   <module>ri      s3     & & % #  4 ' .W
 W
r   