from datetime import datetime, timedelta, date, time from sqlalchemy.orm import Session from sqlalchemy import select from typing import List, Dict, Any, Optional from app.models.ServiceModel import ServiceCatalog, ServiceAppointment, ServiceJobAssignment, ServiceJob from app.models.TechnicianModel import TechnicianProfile, TechnicianSkill, TechnicianWorkingHours, TechnicianLeave from app.repositories.ServiceRepository import ServiceRepository from app.repositories.TechnicianRepository import TechnicianRepository class SlotAllocationService: def __init__(self): self.service_repo = ServiceRepository() self.tech_repo = TechnicianRepository() def get_available_slots(self, db: Session, target_date: date, service_id: str, duration_override: Optional[int] = None) -> List[Dict[str, Any]]: # Sunday no slot if target_date.weekday() == 6: return [] day_start = datetime.combine(target_date, time(0, 0)) day_end = datetime.combine(target_date, time(23, 59, 59)) from app.models.ServiceModel import ServiceAppointment from sqlalchemy import or_ # Store time is IST (UTC + 5:30) now_utc = datetime.utcnow() now_ist = now_utc + timedelta(hours=5, minutes=30) # Fetch ALL appointments for the day that are CONFIRMED, COMPLETED, or currently HELD booked_stmt = select(ServiceAppointment).where( ServiceAppointment.scheduled_start < day_end, ServiceAppointment.scheduled_end > day_start, or_( ServiceAppointment.status.in_(["CONFIRMED", "COMPLETED"]), (ServiceAppointment.status == "HELD") & (ServiceAppointment.hold_expires_at > now_utc) ) ) active_appointments = db.execute(booked_stmt).scalars().all() available_slots = [] # Slots start from 10 AM to 7 PM, 1 hr gap. 2-3 PM excluded. slot_hours = [10, 11, 12, 13, 15, 16, 17, 18] for hour in slot_hours: slot_start = datetime.combine(target_date, time(hour, 0)) slot_end = datetime.combine(target_date, time(hour + 1, 0)) # Skip slots if current time is past the 30-minute mark of the slot # e.g. 10-11 slot is shown until 10:30. if now_ist > slot_start + timedelta(minutes=30): continue overlap = False for appt in active_appointments: if slot_start < appt.scheduled_end and slot_end > appt.scheduled_start: overlap = True break if not overlap: available_slots.append({ "start_time": slot_start.isoformat(), "end_time": slot_end.isoformat(), "technician_id": "STORE_CAPACITY" }) return available_slots