"""Construit un `SolverInput` depuis la base pour une édition. Couche de liaison : c'est le seul endroit du module `solver` qui connaît la base.""" from collections import defaultdict from sqlmodel import Session, select from app.models import ( Assignment, Availability, DayPart, Edition, Shift, Volunteer, VolunteerPositionWish, ) from app.solver.models import SolverInput, SolverShift, SolverVolunteer from app.validation.models import AvailabilityWindow, DayPartWindow, ShiftInfo def build_solver_input(*, session: Session, edition: Edition) -> SolverInput: day_parts = list( session.exec(select(DayPart).where(DayPart.edition_id == edition.id)) ) shifts = list(session.exec(select(Shift).where(Shift.edition_id == edition.id))) assignments = list( session.exec(select(Assignment).where(Assignment.edition_id == edition.id)) ) shifts_by_id = {s.id: s for s in shifts} assigned_count: dict = defaultdict(int) shifts_by_volunteer: dict = defaultdict(list) for a in assignments: assigned_count[a.shift_id] += 1 shift = shifts_by_id.get(a.shift_id) if shift is not None: shifts_by_volunteer[a.volunteer_id].append(shift) solver_shifts = tuple( SolverShift( id=str(s.id), position_id=str(s.position_id), starts_at=s.starts_at, ends_at=s.ends_at, min_staff=s.min_staff, ideal_staff=s.ideal_staff, already_assigned=assigned_count.get(s.id, 0), ) for s in shifts if assigned_count.get(s.id, 0) < s.ideal_staff ) availabilities: dict = defaultdict(list) for a in session.exec( select(Availability).where(Availability.edition_id == edition.id) ): availabilities[a.volunteer_id].append( AvailabilityWindow(date=a.date, start_time=a.start_time, end_time=a.end_time) ) wishes: dict = defaultdict(set) for w in session.exec( select(VolunteerPositionWish).join( Volunteer, Volunteer.id == VolunteerPositionWish.volunteer_id ).where(Volunteer.edition_id == edition.id) ): wishes[w.volunteer_id].add(str(w.position_id)) volunteers = list( session.exec(select(Volunteer).where(Volunteer.edition_id == edition.id)) ) solver_volunteers = tuple( SolverVolunteer( id=str(v.id), availability=tuple(availabilities.get(v.id, ())), wished_position_ids=frozenset(wishes.get(v.id, ())), existing_shifts=tuple( ShiftInfo(id=str(s.id), starts_at=s.starts_at, ends_at=s.ends_at) for s in shifts_by_volunteer.get(v.id, ()) ), existing_minutes=sum( int((s.ends_at - s.starts_at).total_seconds() // 60) for s in shifts_by_volunteer.get(v.id, ()) ), ) for v in volunteers ) return SolverInput( shifts=solver_shifts, volunteers=solver_volunteers, day_parts=tuple( DayPartWindow(dp.code, dp.start_time, dp.end_time, dp.order) for dp in day_parts ), )