diff --git a/app/main.py b/app/main.py index 54d7e5c..212aaf1 100644 --- a/app/main.py +++ b/app/main.py @@ -7,7 +7,7 @@ from fastapi.middleware.cors import CORSMiddleware from app.core.config import settings from app.db.init_db import init_schema_and_seed -from app.routers import auth, bookings, health, packages, payments, services +from app.routers import auth, availability, bookings, health, packages, payments, rosters, services @contextlib.asynccontextmanager @@ -40,6 +40,8 @@ app.add_middleware( app.include_router(health.router) app.include_router(auth.router) app.include_router(services.router) +app.include_router(availability.router) +app.include_router(rosters.router) app.include_router(bookings.router) app.include_router(packages.router) app.include_router(payments.router) diff --git a/app/models/admin.py b/app/models/admin.py index 7a054a5..3f4e4fd 100644 --- a/app/models/admin.py +++ b/app/models/admin.py @@ -3,6 +3,7 @@ from enum import StrEnum from typing import Annotated from pydantic import BeforeValidator, EmailStr +from sqlalchemy import Enum as SAEnum from sqlmodel import Field, SQLModel from sqlmodel._compat import SQLModelConfig @@ -42,6 +43,8 @@ class ActionTypeEnum(StrEnum): UPDATE_BOOKING_STATUS = "UPDATE_BOOKING_STATUS" RELEASE_BOOKING = "RELEASE_BOOKING" RETRY_CALENDAR_SYNC = "RETRY_CALENDAR_SYNC" + ROSTER_CHECKIN = "ROSTER_CHECKIN" + ROSTER_WALK_IN = "ROSTER_WALK_IN" ActionType = Annotated[ @@ -66,7 +69,9 @@ class AdminAuditLog(SQLModel, table=True): id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True) admin_email: EmailStr = Field(foreign_key="admin_allowlist.email") action_type: ActionType - entity_type: EntityType + entity_type: EntityType = Field( + sa_type=SAEnum(EntityTypeEnum, values_callable=lambda x: [e.value for e in x]) + ) entity_id: str details_json: str | None = None created_at: str = Field(default_factory=utc_now_iso) diff --git a/app/routers/availability.py b/app/routers/availability.py new file mode 100644 index 0000000..b18373d --- /dev/null +++ b/app/routers/availability.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +from collections import defaultdict +from datetime import date, time +from zoneinfo import ZoneInfo + +from fastapi import APIRouter, HTTPException, Query, status + +from app.core.config import settings +from app.db.database import get_db, result_to_dicts, row_to_dict +from app.routers.bookings import parse_iso_datetime +from app.schemas.availability import AvailabilityResponse, DayAvailabilityRead, SlotRead +from app.services.availability import ( + BlockedInterval, + BusinessHours, + blocked_interval, + compute_available_slots, +) + +router = APIRouter(prefix="/availability", tags=["Availability"]) + + +def _parse_time(time_str: str) -> time: + parts = [int(p) for p in time_str.split(":")] + return time(hour=parts[0], minute=parts[1]) + + +@router.get("", response_model=AvailabilityResponse) +async def get_availability( + service_id: str = Query(..., description="ID of the service to check availability for"), + date_from: date = Query(..., description="Start date (YYYY-MM-DD) inclusive"), + date_to: date = Query(..., description="End date (YYYY-MM-DD) inclusive"), +): + """ + Public-facing endpoint to query available appointment slots for INDIVIDUAL services. + Enforces service duration and mandatory 15-minute post-session buffer collision rules. + """ + if date_to < date_from: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail="date_to cannot be earlier than date_from.", + ) + + range_days = (date_to - date_from).days + 1 + if range_days > settings.availability_max_range_days: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail=f"Requested range ({range_days} days) exceeds maximum allowed limit ({settings.availability_max_range_days} days).", + ) + + async with get_db() as client: + # 1. Fetch service details + svc_res = await client.execute( + "SELECT * FROM services WHERE id = ? AND is_active = 1 LIMIT 1;", + [service_id], + ) + if not svc_res.rows: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Service '{service_id}' not found or inactive.", + ) + + service = row_to_dict(svc_res, svc_res.rows[0]) + if service["service_type"] != "INDIVIDUAL": + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Availability query is only applicable to INDIVIDUAL appointment services.", + ) + + duration_minutes = int(service.get("duration_minutes", 60)) + buffer_minutes = int(service.get("buffer_minutes", 15)) + service_name = str(service["name"]) + + # 2. Fetch all existing active reservations that could cause collisions + # (bookings where booking_status = 'RESERVED') + b_res = await client.execute( + """ + SELECT scheduled_at, duration_minutes, buffer_minutes + FROM bookings + WHERE booking_status = 'RESERVED'; + """ + ) + existing_rows = result_to_dicts(b_res) + + existing_intervals: list[BlockedInterval] = [] + for r in existing_rows: + dt = parse_iso_datetime(str(r["scheduled_at"])) + dur = int(r.get("duration_minutes", 60)) + buf = int(r.get("buffer_minutes", 0)) + existing_intervals.append(blocked_interval(dt, dur, buf)) + + tz = ZoneInfo(settings.business_timezone) + hours = BusinessHours( + timezone=tz, + open_time=_parse_time(settings.availability_open_time), + close_time=_parse_time(settings.availability_close_time), + working_weekdays=frozenset(settings.availability_working_weekdays), + slot_step_minutes=settings.availability_slot_step_minutes, + ) + + available_slots = compute_available_slots( + date_from=date_from, + date_to=date_to, + duration_minutes=duration_minutes, + buffer_minutes=buffer_minutes, + existing=existing_intervals, + hours=hours, + ) + + # Group available slots by date + days_dict: dict[date, list[SlotRead]] = defaultdict(list) + for slot in available_slots: + slot_date = slot.start.date() + days_dict[slot_date].append( + SlotRead(start=slot.start.isoformat(), end=slot.end.isoformat()) + ) + + # Maintain sorted dates representation + days_list: list[DayAvailabilityRead] = [ + DayAvailabilityRead(date=d.isoformat(), slots=slots) + for d, slots in sorted(days_dict.items(), key=lambda x: x[0]) + ] + + return AvailabilityResponse( + service_id=service_id, + service_name=service_name, + duration_minutes=duration_minutes, + buffer_minutes=buffer_minutes, + timezone=settings.business_timezone, + days=days_list, + ) diff --git a/app/routers/rosters.py b/app/routers/rosters.py new file mode 100644 index 0000000..25fdf5c --- /dev/null +++ b/app/routers/rosters.py @@ -0,0 +1,449 @@ +from __future__ import annotations + +import uuid +from datetime import UTC, date, datetime +from zoneinfo import ZoneInfo + +from fastapi import APIRouter, Depends, HTTPException, Query, status + +from app.core.auth import record_admin_audit, require_admin +from app.core.config import settings +from app.db.database import get_db, result_to_dicts, row_to_dict +from app.models.payment import PaymentMethodEnum +from app.routers.bookings import ( + BOOKING_SELECT_QUERY, + generate_booking_code, + parse_iso_datetime, +) +from app.schemas.auth import AdminPrincipal +from app.schemas.roster import ( + QuickCheckinRequest, + QuickCheckinResponse, + RosterAttendeeRead, + RosterSessionRead, +) +from app.services.calendar import calendar_service + +router = APIRouter(prefix="/rosters", tags=["Group Workshop Rosters"]) + + +def _to_utc_instant_key(dt_str: str) -> str: + """Normalize ISO datetime string to an ISO UTC string so different representations group together.""" + dt = parse_iso_datetime(dt_str) + return dt.astimezone(UTC).isoformat() + + +@router.get("", response_model=list[RosterSessionRead]) +async def get_rosters( + date_from: date = Query(..., description="Start date (YYYY-MM-DD)"), + date_to: date = Query(..., description="End date (YYYY-MM-DD)"), + service_id: str | None = Query(None, description="Optional service ID filter"), + _admin: AdminPrincipal = Depends(require_admin), +): + """ + Query workshop roster sessions for GROUP services within [date_from, date_to]. + Groups bookings by session instant across different ISO timezone representations. + Excludes RELEASED and CANCELLED bookings. + """ + if date_to < date_from: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail="date_to cannot be earlier than date_from.", + ) + + # Convert date range to Mexico City timezone boundaries + tz = ZoneInfo(settings.business_timezone) + start_dt = datetime( + date_from.year, date_from.month, date_from.day, 0, 0, 0, tzinfo=tz + ).astimezone(UTC) + end_dt = datetime( + date_to.year, date_to.month, date_to.day, 23, 59, 59, 999999, tzinfo=tz + ).astimezone(UTC) + + query = ( + BOOKING_SELECT_QUERY + + """ + WHERE s.service_type = 'GROUP' + AND b.booking_status IN ('RESERVED', 'COMPLETED', 'NO_SHOW') + AND s.is_active = 1 + """ + ) + params = [] + if service_id: + query += " AND s.id = ?" + params.append(service_id) + + query += " ORDER BY b.scheduled_at ASC;" + + async with get_db() as client: + # Also fetch group service details + svc_query = "SELECT id, name, max_capacity FROM services WHERE service_type = 'GROUP';" + svc_res = await client.execute(svc_query) + services_by_id = { + str(r[0]): {"name": str(r[1]), "max_capacity": int(str(r[2] or 1))} + for r in svc_res.rows + } + + res = await client.execute(query, params) + rows = result_to_dicts(res) + + # Group by (service_id, normalized_instant_key) + sessions_map: dict[tuple[str, str], dict] = {} + + for r in rows: + sched_dt_utc = parse_iso_datetime(str(r["scheduled_at"])).astimezone(UTC) + if not (start_dt <= sched_dt_utc <= end_dt): + continue + + svc_id = str(r["service_id"]) + instant_key = sched_dt_utc.isoformat() + group_key = (svc_id, instant_key) + + if group_key not in sessions_map: + svc_info = services_by_id.get( + svc_id, {"name": str(r.get("service_name", "")), "max_capacity": 20} + ) + sessions_map[group_key] = { + "service_id": svc_id, + "service_name": svc_info["name"], + "scheduled_at": str(r["scheduled_at"]), # preserve representative representation + "max_capacity": svc_info["max_capacity"], + "attendees": [], + } + + booking_status = str(r["booking_status"]) + attended = booking_status == "COMPLETED" + + sessions_map[group_key]["attendees"].append( + RosterAttendeeRead( + booking_id=str(r["id"]), + booking_code=str(r["booking_code"]), + client_id=str(r["client_id"]), + client_name=str(r.get("client_name") or ""), + client_phone=str(r.get("client_phone") or ""), + client_email=r.get("client_email"), + booking_status=booking_status, + payment_arrangement=str(r["payment_arrangement"]), + payment_status=str(r["payment_status"]), + amount_mxn=int(r["amount_mxn"]), + attended=attended, + ) + ) + + roster_sessions: list[RosterSessionRead] = [] + for s_data in sessions_map.values(): + attendees = s_data["attendees"] + occupied_count = len(attendees) + attended_count = sum(1 for a in attendees if a.attended) + roster_sessions.append( + RosterSessionRead( + service_id=s_data["service_id"], + service_name=s_data["service_name"], + scheduled_at=s_data["scheduled_at"], + max_capacity=s_data["max_capacity"], + occupied_count=occupied_count, + attended_count=attended_count, + attendees=attendees, + ) + ) + + return roster_sessions + + +@router.post("/quick-checkin", response_model=QuickCheckinResponse) +async def quick_checkin( + payload: QuickCheckinRequest, + admin: AdminPrincipal = Depends(require_admin), +): + """ + Perform a quick check-in for group workshops: + - Mode 1: Check in an existing booking (marking COMPLETED, optionally recording CASH payment). + - Mode 2: Register a walk-in attendee directly into COMPLETED status. + """ + now = datetime.now(UTC).isoformat() + + async with get_db() as client: + # MODE 1: Existing booking check-in + if payload.booking_id: + b_res = await client.execute( + BOOKING_SELECT_QUERY + " WHERE b.id = ? LIMIT 1;", + [payload.booking_id], + ) + if not b_res.rows: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Booking not found." + ) + + booking = row_to_dict(b_res, b_res.rows[0]) + svc_res = await client.execute( + "SELECT service_type FROM services WHERE id = ?;", [booking["service_id"]] + ) + if not svc_res.rows or str(svc_res.rows[0][0]) != "GROUP": + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Quick check-in is only available for GROUP workshops.", + ) + + current_status = str(booking["booking_status"]) + if current_status in ("RELEASED", "CANCELLED"): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Cannot check in a {current_status.lower()} booking.", + ) + if current_status == "COMPLETED": + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="This attendee has already checked in.", + ) + + new_booking_status = "COMPLETED" + payment_id: str | None = None + current_p_status = str(booking["payment_status"]) + current_p_arr = str(booking["payment_arrangement"]) + + if payload.paid_cash: + new_p_status = "ACKNOWLEDGED" + new_p_arr = current_p_arr + payment_id = str(uuid.uuid4()) + await client.execute( + """ + INSERT INTO payments ( + id, booking_id, amount_mxn, payment_method, status, + acknowledged_by, acknowledged_at, notes, created_at + ) + VALUES (?, ?, ?, ?, 'ACKNOWLEDGED', ?, ?, ?, ?); + """, + [ + payment_id, + booking["id"], + booking["amount_mxn"], + PaymentMethodEnum.CASH.value, + admin.email, + now, + payload.notes or "Quick check-in cash payment", + now, + ], + ) + else: + if current_p_status == "ACKNOWLEDGED": + new_p_status = "ACKNOWLEDGED" + new_p_arr = current_p_arr + else: + new_p_status = "AWAITING_ACKNOWLEDGMENT" + new_p_arr = "DELAYED_ALLOWED" + + cal_res = await calendar_service.sync_booking_event( + booking_id=str(booking["id"]), + booking_code=str(booking["booking_code"]), + service_name=str(booking["service_name"]), + client_name=str(booking["client_name"]), + scheduled_at=str(booking["scheduled_at"]), + duration_minutes=int(booking["duration_minutes"]), + booking_status=new_booking_status, + payment_arrangement=new_p_arr, + payment_status=new_p_status, + existing_event_id=booking.get("gcal_event_id"), + ) + + await client.execute( + """ + UPDATE bookings + SET booking_status = ?, + payment_arrangement = ?, + payment_status = ?, + gcal_event_id = ?, + gcal_sync_status = ?, + gcal_sync_error = ?, + gcal_synced_at = ? + WHERE id = ?; + """, + [ + new_booking_status, + new_p_arr, + new_p_status, + cal_res.event_id, + cal_res.sync_status, + cal_res.sync_error, + cal_res.synced_at, + booking["id"], + ], + ) + + await record_admin_audit( + client, + admin_email=admin.email, + action_type="ROSTER_CHECKIN", + entity_type="booking", + entity_id=str(booking["id"]), + details={"paid_cash": payload.paid_cash, "payment_id": payment_id}, + ) + + attendee = RosterAttendeeRead( + booking_id=str(booking["id"]), + booking_code=str(booking["booking_code"]), + client_id=str(booking["client_id"]), + client_name=str(booking["client_name"]), + client_phone=str(booking["client_phone"]), + client_email=booking.get("client_email"), + booking_status=new_booking_status, + payment_arrangement=new_p_arr, + payment_status=new_p_status, + amount_mxn=int(booking["amount_mxn"]), + attended=True, + ) + return QuickCheckinResponse(walk_in=False, attendee=attendee, payment_id=payment_id) + + # MODE 2: Walk-in registration and check-in + service_id = str(payload.service_id) + scheduled_at = str(payload.scheduled_at) + client_name = str(payload.client_name) + client_phone = str(payload.client_phone) + + svc_res = await client.execute( + "SELECT * FROM services WHERE id = ? AND is_active = 1 LIMIT 1;", + [service_id], + ) + if not svc_res.rows: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, detail="Service not found or inactive." + ) + + service = row_to_dict(svc_res, svc_res.rows[0]) + if service["service_type"] != "GROUP": + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Walk-in check-in is only applicable to GROUP workshops.", + ) + + # Capacity check for this group workshop session + cap_res = await client.execute( + """ + SELECT COUNT(*) AS count + FROM bookings + WHERE service_id = ? AND scheduled_at = ? AND booking_status IN ('RESERVED', 'COMPLETED'); + """, + [service_id, scheduled_at], + ) + current_count = int(str(cap_res.rows[0][0] or 0)) + max_cap = int(service.get("max_capacity", 1)) + if current_count >= max_cap: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail=f"El taller ha alcanzado su cupo máximo ({max_cap}) para esta sesión.", + ) + + # Upsert client by phone + c_res = await client.execute( + "SELECT id FROM clients WHERE phone_whatsapp = ? LIMIT 1;", + [client_phone], + ) + if c_res.rows: + client_id = str(c_res.rows[0][0]) + else: + client_id = str(uuid.uuid4()) + await client.execute( + "INSERT INTO clients (id, full_name, phone_whatsapp, email, notes) VALUES (?, ?, ?, ?, ?);", + [client_id, client_name, client_phone, payload.client_email, "Walk-in attendee"], + ) + + booking_id = str(uuid.uuid4()) + booking_code = generate_booking_code() + duration_minutes = int(service.get("duration_minutes", 60)) + buffer_minutes = int(service.get("buffer_minutes", 0)) + amount_mxn = int(service["price_mxn"]) + + booking_status = "COMPLETED" + if payload.paid_cash: + payment_status = "ACKNOWLEDGED" + payment_arrangement = "PREPAID_DEFAULT" + else: + payment_status = "AWAITING_ACKNOWLEDGMENT" + payment_arrangement = "DELAYED_ALLOWED" + + cal_res = await calendar_service.sync_booking_event( + booking_id=booking_id, + booking_code=booking_code, + service_name=str(service["name"]), + client_name=client_name, + scheduled_at=scheduled_at, + duration_minutes=duration_minutes, + booking_status=booking_status, + payment_arrangement=payment_arrangement, + payment_status=payment_status, + ) + + await client.execute( + """ + INSERT INTO bookings ( + id, booking_code, service_id, client_id, scheduled_at, + duration_minutes, buffer_minutes, booking_status, payment_arrangement, + payment_status, amount_mxn, gcal_event_id, gcal_sync_status, + gcal_sync_error, gcal_synced_at, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); + """, + [ + booking_id, + booking_code, + service["id"], + client_id, + scheduled_at, + duration_minutes, + buffer_minutes, + booking_status, + payment_arrangement, + payment_status, + amount_mxn, + cal_res.event_id, + cal_res.sync_status, + cal_res.sync_error, + cal_res.synced_at, + now, + ], + ) + + payment_id = None + if payload.paid_cash: + payment_id = str(uuid.uuid4()) + await client.execute( + """ + INSERT INTO payments ( + id, booking_id, amount_mxn, payment_method, status, + acknowledged_by, acknowledged_at, notes, created_at + ) VALUES (?, ?, ?, ?, 'ACKNOWLEDGED', ?, ?, ?, ?); + """, + [ + payment_id, + booking_id, + amount_mxn, + PaymentMethodEnum.CASH.value, + admin.email, + now, + payload.notes or "Walk-in cash payment", + now, + ], + ) + + await record_admin_audit( + client, + admin_email=admin.email, + action_type="ROSTER_WALK_IN", + entity_type="booking", + entity_id=booking_id, + details={"paid_cash": payload.paid_cash, "payment_id": payment_id}, + ) + + attendee = RosterAttendeeRead( + booking_id=booking_id, + booking_code=booking_code, + client_id=client_id, + client_name=client_name, + client_phone=client_phone, + client_email=payload.client_email, + booking_status=booking_status, + payment_arrangement=payment_arrangement, + payment_status=payment_status, + amount_mxn=amount_mxn, + attended=True, + ) + + return QuickCheckinResponse(walk_in=True, attendee=attendee, payment_id=payment_id) diff --git a/app/schemas/availability.py b/app/schemas/availability.py new file mode 100644 index 0000000..d86a37f --- /dev/null +++ b/app/schemas/availability.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from pydantic import BaseModel + + +class SlotRead(BaseModel): + start: str + end: str + + +class DayAvailabilityRead(BaseModel): + date: str + slots: list[SlotRead] + + +class AvailabilityResponse(BaseModel): + service_id: str + service_name: str + duration_minutes: int + buffer_minutes: int + timezone: str + days: list[DayAvailabilityRead] diff --git a/app/schemas/roster.py b/app/schemas/roster.py new file mode 100644 index 0000000..87b43b2 --- /dev/null +++ b/app/schemas/roster.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from pydantic import BaseModel, model_validator + + +class RosterAttendeeRead(BaseModel): + booking_id: str + booking_code: str + client_id: str + client_name: str + client_phone: str + client_email: str | None = None + booking_status: str + payment_arrangement: str + payment_status: str + amount_mxn: int + attended: bool + + +class RosterSessionRead(BaseModel): + service_id: str + service_name: str + scheduled_at: str + max_capacity: int + occupied_count: int + attended_count: int + attendees: list[RosterAttendeeRead] + + +class QuickCheckinRequest(BaseModel): + # Mode 1: existing booking check-in + booking_id: str | None = None + + # Mode 2: walk-in check-in + service_id: str | None = None + scheduled_at: str | None = None + client_name: str | None = None + client_phone: str | None = None + client_email: str | None = None + + paid_cash: bool = False + notes: str | None = None + + @model_validator(mode="after") + def validate_exactly_one_mode(self) -> QuickCheckinRequest: + has_booking_id = bool(self.booking_id) + has_any_walk_in = any( + [self.service_id, self.scheduled_at, self.client_name, self.client_phone] + ) + is_complete_walk_in = bool( + self.service_id and self.scheduled_at and self.client_name and self.client_phone + ) + + if has_booking_id: + if has_any_walk_in: + raise ValueError("Cannot combine 'booking_id' with walk-in fields.") + return self + + if is_complete_walk_in: + return self + + raise ValueError( + "Must provide either 'booking_id' for an existing booking, " + "or ('service_id', 'scheduled_at', 'client_name', 'client_phone') for a walk-in." + ) + + +class QuickCheckinResponse(BaseModel): + walk_in: bool + attendee: RosterAttendeeRead + payment_id: str | None = None diff --git a/app/services/availability.py b/app/services/availability.py new file mode 100644 index 0000000..e18bd7e --- /dev/null +++ b/app/services/availability.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +from dataclasses import dataclass +from datetime import UTC, date, datetime, time, timedelta +from zoneinfo import ZoneInfo + + +@dataclass(frozen=True) +class BlockedInterval: + start: datetime + end: datetime + + +@dataclass(frozen=True) +class AvailableSlot: + start: datetime + end: datetime + + +@dataclass(frozen=True) +class BusinessHours: + timezone: ZoneInfo + open_time: time + close_time: time + working_weekdays: frozenset[int] # 0=Monday .. 6=Sunday + slot_step_minutes: int + + +def blocked_interval( + start: datetime, duration_minutes: int, buffer_minutes: int +) -> BlockedInterval: + """Build a blocked interval including mandatory post-session buffer.""" + return BlockedInterval(start, start + timedelta(minutes=duration_minutes + buffer_minutes)) + + +def intervals_overlap(a: BlockedInterval, b: BlockedInterval) -> bool: + """ + Two half-open intervals [a.start, a.end) and [b.start, b.end) overlap + if max(a.start, b.start) < min(a.end, b.end). + Touching at the exact boundary (a.end == b.start) is NOT an overlap. + """ + return max(a.start, b.start) < min(a.end, b.end) + + +def compute_available_slots( + *, + date_from: date, + date_to: date, + duration_minutes: int, + buffer_minutes: int, + existing: list[BlockedInterval], + hours: BusinessHours, + now: datetime | None = None, +) -> list[AvailableSlot]: + """ + Compute collision-free individual appointment slots across [date_from, date_to] (inclusive). + Candidate slots are generated in the business timezone from open_time to close_time. + A candidate slot is rejected if: + 1. Its actual session end (start + duration) exceeds close_time. + 2. Its start is at or before `now` (UTC). + 3. Its blocked interval (start + duration + buffer) overlaps with any existing blocked interval. + """ + if date_to < date_from: + raise ValueError("date_to cannot precede date_from") + + ref_now = now or datetime.now(UTC) + slots: list[AvailableSlot] = [] + step = timedelta(minutes=hours.slot_step_minutes) + session_delta = timedelta(minutes=duration_minutes) + + current_date = date_from + while current_date <= date_to: + if current_date.weekday() in hours.working_weekdays: + day_open = datetime.combine(current_date, hours.open_time, tzinfo=hours.timezone) + day_close = datetime.combine(current_date, hours.close_time, tzinfo=hours.timezone) + + candidate_start = day_open + while candidate_start < day_close: + session_end = candidate_start + session_delta + if session_end > day_close: + break + + # Verify candidate is strictly in the future compared to ref_now + candidate_start_utc = candidate_start.astimezone(UTC) + if candidate_start_utc > ref_now: + candidate_blocked = blocked_interval( + candidate_start, duration_minutes, buffer_minutes + ) + # Check collision against existing blocked intervals + has_collision = False + for b in existing: + # Normalize timezones for safety when comparing + b_start_norm = b.start.astimezone(hours.timezone) + b_end_norm = b.end.astimezone(hours.timezone) + if intervals_overlap( + candidate_blocked, BlockedInterval(b_start_norm, b_end_norm) + ): + has_collision = True + break + + if not has_collision: + slots.append(AvailableSlot(start=candidate_start, end=session_end)) + + candidate_start += step + + current_date += timedelta(days=1) + + return slots diff --git a/pyproject.toml b/pyproject.toml index 1bd11d9..a9697e6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,7 @@ dependencies = [ "time-machine>=3.5.1", "uvicorn[standard]>=0.30.0", "httpx2>=2.14.0", + "tzdata>=2026.5", ] [dependency-groups] diff --git a/tests/test_availability.py b/tests/test_availability.py new file mode 100644 index 0000000..9982e0c --- /dev/null +++ b/tests/test_availability.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import pytest + +from app.core.auth import create_session_token +from app.core.config import settings + +DAY = "2027-03-01" # Monday, America/Mexico_City (UTC-6) + + +@pytest.fixture +def short_business_day(monkeypatch): + monkeypatch.setattr(settings, "business_timezone", "America/Mexico_City") + monkeypatch.setattr(settings, "availability_open_time", "09:00") + monkeypatch.setattr(settings, "availability_close_time", "13:00") + monkeypatch.setattr(settings, "availability_slot_step_minutes", 30) + monkeypatch.setattr(settings, "availability_working_weekdays", [0, 1, 2, 3, 4]) + + +def _individual_service(client) -> dict: + return client.get("/services/atencion-psicologica-individual").json() + + +def _book(client, service_id: str, scheduled_at: str, phone: str): + return client.post( + "/bookings", + json={ + "service_id": service_id, + "client_name": "Cliente Disponibilidad", + "client_phone": phone, + "scheduled_at": scheduled_at, + }, + ) + + +def _slot_starts(body: dict) -> list[str]: + return [slot["start"] for day in body["days"] for slot in day["slots"]] + + +def test_availability_excludes_slots_colliding_with_reserved_buffer(client, short_business_day): + svc = _individual_service(client) + assert _book(client, svc["id"], f"{DAY}T10:00:00-06:00", "7750001001").status_code == 201 + + res = client.get( + "/availability", params={"service_id": svc["id"], "date_from": DAY, "date_to": DAY} + ) + assert res.status_code == 200 + body = res.json() + assert body["service_id"] == svc["id"] + assert body["duration_minutes"] == 60 + assert body["buffer_minutes"] == 15 + assert body["timezone"] == "America/Mexico_City" + assert _slot_starts(body) == [f"{DAY}T11:30:00-06:00", f"{DAY}T12:00:00-06:00"] + assert body["days"][0]["slots"][0]["end"] == f"{DAY}T12:30:00-06:00" + + +def test_released_bookings_free_their_slots(client, short_business_day): + day = "2027-03-02" + svc = _individual_service(client) + booking = _book(client, svc["id"], f"{day}T09:00:00-06:00", "7750001002").json() + params = {"service_id": svc["id"], "date_from": day, "date_to": day} + assert f"{day}T09:00:00-06:00" not in _slot_starts( + client.get("/availability", params=params).json() + ) + + headers = {"Authorization": f"Bearer {create_session_token('jasmin@armoniadelser.mx')}"} + rel = client.post(f"/bookings/{booking['id']}/release", headers=headers, json={}) + assert rel.status_code == 200 + assert f"{day}T09:00:00-06:00" in _slot_starts( + client.get("/availability", params=params).json() + ) + + +def test_every_offered_slot_is_accepted_by_booking_engine(client, short_business_day): + day = "2027-03-03" + svc = _individual_service(client) + params = {"service_id": svc["id"], "date_from": day, "date_to": day} + first = _slot_starts(client.get("/availability", params=params).json())[0] + assert _book(client, svc["id"], first, "7750001003").status_code == 201 + + # Next 30-minute step now collides (60 + 15 buffer) and must disappear + after = _slot_starts(client.get("/availability", params=params).json()) + assert first not in after + assert f"{day}T09:30:00-06:00" not in after + assert f"{day}T10:00:00-06:00" not in after + assert after[0] == f"{day}T10:30:00-06:00" + + +def test_availability_groups_slots_by_local_day(client, short_business_day): + svc = _individual_service(client) + res = client.get( + "/availability", + params={"service_id": svc["id"], "date_from": "2027-03-05", "date_to": "2027-03-08"}, + ) + assert res.status_code == 200 + # Fri 5 and Mon 8 are working days; the weekend is omitted + assert [d["date"] for d in res.json()["days"]] == ["2027-03-05", "2027-03-08"] + + +def test_availability_rejects_group_services(client): + svc = client.get("/services/circulo-cacao-presencial").json() + res = client.get( + "/availability", params={"service_id": svc["id"], "date_from": DAY, "date_to": DAY} + ) + assert res.status_code == 400 + + +def test_availability_unknown_service_is_404(client): + res = client.get( + "/availability", params={"service_id": "nope", "date_from": DAY, "date_to": DAY} + ) + assert res.status_code == 404 + + +def test_availability_rejects_inverted_range(client): + svc = _individual_service(client) + res = client.get( + "/availability", + params={"service_id": svc["id"], "date_from": "2027-03-02", "date_to": "2027-03-01"}, + ) + assert res.status_code == 422 + + +def test_availability_rejects_range_over_limit(client, monkeypatch): + monkeypatch.setattr(settings, "availability_max_range_days", 7) + svc = _individual_service(client) + res = client.get( + "/availability", + params={"service_id": svc["id"], "date_from": "2027-03-01", "date_to": "2027-03-08"}, + ) + assert res.status_code == 422 diff --git a/tests/test_rosters.py b/tests/test_rosters.py new file mode 100644 index 0000000..b6d9f10 --- /dev/null +++ b/tests/test_rosters.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +import uuid + +import pytest +from sqlmodel import Session, select + +from app.core.auth import create_session_token +from app.core.config import AuthProvider, settings +from app.db.database import get_engine +from app.models.admin import AdminAuditLog +from app.models.payment import Payment +from app.models.service import Service, ServiceModalityEnum, ServiceTypeEnum + + +def _admin(email: str = "asistente@armoniadelser.mx") -> dict[str, str]: + return {"Authorization": f"Bearer {create_session_token(email)}"} + + +def _book(client, service_id: str, scheduled_at: str, phone: str, name: str = "Asistente Cacao"): + res = client.post( + "/bookings", + json={ + "service_id": service_id, + "client_name": name, + "client_phone": phone, + "scheduled_at": scheduled_at, + }, + ) + assert res.status_code == 201, res.text + return res.json() + + +def _roster(client, day: str, service_id: str | None = None) -> list[dict]: + params = {"date_from": day, "date_to": day} + if service_id: + params["service_id"] = service_id + res = client.get("/rosters", params=params, headers=_admin()) + assert res.status_code == 200, res.text + return res.json() + + +def _queue_ids(client) -> list[str]: + return [b["id"] for b in client.get("/bookings/follow-up-queue", headers=_admin()).json()] + + +@pytest.fixture +def cacao(client) -> dict: + return client.get("/services/circulo-cacao-presencial").json() + + +@pytest.fixture +def tiny_workshop() -> dict: + """A GROUP service with capacity 1, inserted through the real SQLModel engine.""" + service_id = str(uuid.uuid4()) + with Session(get_engine()) as session: + session.add( + Service( + id=service_id, + slug=f"taller-mini-{service_id[:8]}", + name="Taller Mini", + service_type=ServiceTypeEnum.GROUP, + modality=ServiceModalityEnum.PRESENCIAL, + price_mxn=50, + max_capacity=1, + duration_minutes=60, + buffer_minutes=0, + ) + ) + session.commit() + return {"id": service_id, "price_mxn": 50} + + +# --- GET /rosters --------------------------------------------------------------------- + + +def test_rosters_require_admin(client): + assert client.get("/rosters").status_code == 401 + + +def test_roster_groups_attendees_by_session_instant_across_iso_formats(client, cacao): + # Same instant written two ways must land in ONE session + a = _book(client, cacao["id"], "2027-04-06T18:00:00Z", "5510000001", "Ana") + b = _book(client, cacao["id"], "2027-04-06T12:00:00-06:00", "5510000002", "Beto") + released = _book(client, cacao["id"], "2027-04-06T18:00:00+00:00", "5510000003", "Ceci") + client.post(f"/bookings/{released['id']}/release", headers=_admin(), json={}) + + sessions = _roster(client, "2027-04-06", cacao["id"]) + assert len(sessions) == 1 + session = sessions[0] + assert session["service_name"] == cacao["name"] + assert session["max_capacity"] == cacao["max_capacity"] + assert session["occupied_count"] == 2 + assert session["attended_count"] == 0 + ids = {att["booking_id"] for att in session["attendees"]} + assert ids == {a["id"], b["id"]} # released booking is not on the roster + assert all(att["attended"] is False for att in session["attendees"]) + + +def test_roster_excludes_individual_services(client): + svc = client.get("/services/atencion-psicologica-individual").json() + _book(client, svc["id"], "2027-04-07T16:00:00Z", "5510000004") + assert _roster(client, "2027-04-07") == [] + + +# --- POST /rosters/quick-checkin: existing bookings ------------------------------------ + + +def test_checkin_with_cash_marks_attended_and_acknowledges_payment(client, cacao): + booking = _book(client, cacao["id"], "2027-04-13T18:00:00Z", "5510000010") + res = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json={"booking_id": booking["id"], "paid_cash": True}, + ) + assert res.status_code == 200, res.text + body = res.json() + assert body["walk_in"] is False + assert body["attendee"]["attended"] is True + assert body["attendee"]["booking_status"] == "COMPLETED" + assert body["attendee"]["payment_status"] == "ACKNOWLEDGED" + assert body["payment_id"] is not None + + with Session(get_engine()) as s: + payment = s.get(Payment, body["payment_id"]) + assert payment is not None + assert payment.payment_method == "CASH" + assert payment.amount_mxn == cacao["price_mxn"] + assert payment.acknowledged_by == "asistente@armoniadelser.mx" + audit = s.exec(select(AdminAuditLog).where(AdminAuditLog.entity_id == booking["id"])).all() + assert [a.action_type for a in audit] == ["ROSTER_CHECKIN"] + + assert booking["id"] not in _queue_ids(client) + assert _roster(client, "2027-04-13", cacao["id"])[0]["attended_count"] == 1 + + +def test_checkin_twice_is_conflict(client, cacao): + booking = _book(client, cacao["id"], "2027-04-14T18:00:00Z", "5510000011") + payload = {"booking_id": booking["id"]} + assert client.post("/rosters/quick-checkin", headers=_admin(), json=payload).status_code == 200 + assert client.post("/rosters/quick-checkin", headers=_admin(), json=payload).status_code == 409 + + +def test_unpaid_checkin_becomes_traceable_delayed_payment(client, cacao): + booking = _book(client, cacao["id"], "2027-04-15T18:00:00Z", "5510000012") + res = client.post( + "/rosters/quick-checkin", headers=_admin(), json={"booking_id": booking["id"]} + ) + assert res.status_code == 200 + attendee = res.json()["attendee"] + assert attendee["booking_status"] == "COMPLETED" + assert attendee["payment_arrangement"] == "DELAYED_ALLOWED" + assert attendee["payment_status"] == "AWAITING_ACKNOWLEDGMENT" + assert res.json()["payment_id"] is None + # Attending without paying must never silently disappear from the receivables queue + assert booking["id"] in _queue_ids(client) + + +def test_checkin_corrects_a_mistaken_no_show(client, cacao): + booking = _book(client, cacao["id"], "2027-04-16T18:00:00Z", "5510000013") + client.post( + f"/bookings/{booking['id']}/status", + headers=_admin(), + json={"booking_status": "NO_SHOW"}, + ) + res = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json={"booking_id": booking["id"], "paid_cash": True}, + ) + assert res.status_code == 200 + assert res.json()["attendee"]["attended"] is True + + +@pytest.mark.parametrize("status_path", ["release", "status"]) +def test_checkin_rejects_released_or_cancelled_bookings(client, cacao, status_path): + booking = _book(client, cacao["id"], "2027-04-17T18:00:00Z", f"55100000{20 + len(status_path)}") + if status_path == "release": + client.post(f"/bookings/{booking['id']}/release", headers=_admin(), json={}) + else: + client.post( + f"/bookings/{booking['id']}/status", + headers=_admin(), + json={"booking_status": "CANCELLED"}, + ) + res = client.post( + "/rosters/quick-checkin", headers=_admin(), json={"booking_id": booking["id"]} + ) + assert res.status_code == 400 + + +def test_checkin_rejects_individual_bookings(client): + svc = client.get("/services/atencion-psicologica-individual").json() + booking = _book(client, svc["id"], "2027-04-19T16:00:00Z", "5510000030") + res = client.post( + "/rosters/quick-checkin", headers=_admin(), json={"booking_id": booking["id"]} + ) + assert res.status_code == 400 + + +def test_checkin_unknown_booking_is_404(client): + res = client.post("/rosters/quick-checkin", headers=_admin(), json={"booking_id": "nope"}) + assert res.status_code == 404 + + +# --- POST /rosters/quick-checkin: walk-ins --------------------------------------------- + + +def _walk_in(service_id: str, scheduled_at: str, phone: str, **extra) -> dict: + return { + "service_id": service_id, + "scheduled_at": scheduled_at, + "client_name": "Llegó sin reservar", + "client_phone": phone, + **extra, + } + + +def test_paid_walk_in_creates_attended_acknowledged_booking(client, cacao): + res = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json=_walk_in(cacao["id"], "2027-04-20T18:00:00Z", "5510000040", paid_cash=True), + ) + assert res.status_code == 200, res.text + body = res.json() + assert body["walk_in"] is True + assert body["attendee"]["booking_status"] == "COMPLETED" + assert body["attendee"]["payment_status"] == "ACKNOWLEDGED" + assert body["attendee"]["booking_code"].startswith("ADS-") + assert body["payment_id"] is not None + + session = _roster(client, "2027-04-20", cacao["id"])[0] + assert [a["booking_id"] for a in session["attendees"]] == [body["attendee"]["booking_id"]] + assert session["attended_count"] == 1 + + +def test_unpaid_walk_in_is_visible_in_followup_queue(client, cacao): + res = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json=_walk_in(cacao["id"], "2027-04-21T18:00:00Z", "5510000041"), + ) + assert res.status_code == 200 + attendee = res.json()["attendee"] + assert attendee["payment_arrangement"] == "DELAYED_ALLOWED" + assert attendee["booking_id"] in _queue_ids(client) + + +def test_walk_in_reuses_existing_client_by_phone(client, cacao): + existing = _book(client, cacao["id"], "2027-04-22T18:00:00Z", "5510000042") + res = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json=_walk_in(cacao["id"], "2027-04-29T18:00:00Z", "5510000042"), + ) + assert res.json()["attendee"]["client_id"] == existing["client_id"] + + +def test_walk_in_respects_capacity(client, tiny_workshop): + when = "2027-04-23T18:00:00Z" + first = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json=_walk_in(tiny_workshop["id"], when, "5510000050"), + ) + assert first.status_code == 200 + second = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json=_walk_in(tiny_workshop["id"], when, "5510000051"), + ) + assert second.status_code == 409 + + +def test_walk_in_rejects_individual_service(client): + svc = client.get("/services/atencion-psicologica-individual").json() + res = client.post( + "/rosters/quick-checkin", + headers=_admin(), + json=_walk_in(svc["id"], "2027-04-26T16:00:00Z", "5510000060"), + ) + assert res.status_code == 400 + + +@pytest.mark.parametrize( + "payload", + [ + {}, + {"paid_cash": True}, + {"booking_id": "x", "service_id": "y", "scheduled_at": "2027-04-26T16:00:00Z"}, + {"service_id": "y", "scheduled_at": "2027-04-26T16:00:00Z"}, # walk-in without client + ], +) +def test_checkin_requires_exactly_one_mode(client, payload): + assert client.post("/rosters/quick-checkin", headers=_admin(), json=payload).status_code == 422 + + +# --- ADR-0006: proxy users keep FK integrity on roster writes -------------------------- + + +def test_proxy_user_walk_in_checkin_preserves_foreign_keys(client, cacao, monkeypatch): + monkeypatch.setattr(settings, "auth_provider", AuthProvider.PROXY_HEADERS) + proxy = { + "Remote-Email": "puerta@homelab.lan", + "Remote-Name": "Recepcion", + "Remote-Groups": "armonia-assistant", + } + res = client.post( + "/rosters/quick-checkin", + headers=proxy, + json=_walk_in(cacao["id"], "2027-04-27T18:00:00Z", "5510000070", paid_cash=True), + ) + assert res.status_code == 200, res.text + with Session(get_engine()) as s: + payment = s.get(Payment, res.json()["payment_id"]) + assert payment is not None + assert payment.acknowledged_by == "puerta@homelab.lan" diff --git a/tests/unit/services/test_availability_engine.py b/tests/unit/services/test_availability_engine.py new file mode 100644 index 0000000..b50c19b --- /dev/null +++ b/tests/unit/services/test_availability_engine.py @@ -0,0 +1,181 @@ +from __future__ import annotations + +from datetime import UTC, date, datetime, time, timedelta +from zoneinfo import ZoneInfo + +import pytest + +from app.services.availability import ( + BlockedInterval, + BusinessHours, + blocked_interval, + compute_available_slots, + intervals_overlap, +) + +MX = ZoneInfo("America/Mexico_City") # UTC-6, no DST since 2022 +MONDAY = date(2027, 3, 1) +LONG_AGO = datetime(2020, 1, 1, tzinfo=UTC) + +HOURS = BusinessHours( + timezone=MX, + open_time=time(9, 0), + close_time=time(13, 0), + working_weekdays=frozenset({0, 1, 2, 3, 4}), + slot_step_minutes=30, +) + + +def _local(day: date, hh: int, mm: int = 0) -> datetime: + return datetime(day.year, day.month, day.day, hh, mm, tzinfo=MX) + + +def _starts(slots) -> list[str]: + return [s.start.strftime("%H:%M") for s in slots] + + +# --- blocked_interval / intervals_overlap ------------------------------------------- + + +def test_blocked_interval_adds_duration_and_post_session_buffer(): + start = _local(MONDAY, 10) + interval = blocked_interval(start, duration_minutes=60, buffer_minutes=15) + assert interval.start == start + assert interval.end == start + timedelta(minutes=75) + + +def test_intervals_touching_at_boundary_do_not_overlap(): + a = BlockedInterval(_local(MONDAY, 9), _local(MONDAY, 10)) + b = BlockedInterval(_local(MONDAY, 10), _local(MONDAY, 11)) + assert intervals_overlap(a, b) is False + assert intervals_overlap(b, a) is False + + +def test_intervals_sharing_one_minute_overlap(): + a = BlockedInterval(_local(MONDAY, 9), _local(MONDAY, 10, 1)) + b = BlockedInterval(_local(MONDAY, 10), _local(MONDAY, 11)) + assert intervals_overlap(a, b) is True + assert intervals_overlap(b, a) is True + + +def test_contained_interval_overlaps(): + outer = BlockedInterval(_local(MONDAY, 9), _local(MONDAY, 12)) + inner = BlockedInterval(_local(MONDAY, 10), _local(MONDAY, 11)) + assert intervals_overlap(outer, inner) is True + assert intervals_overlap(inner, outer) is True + + +# --- compute_available_slots -------------------------------------------------------- + + +def _compute(existing=(), *, duration=60, buffer=15, now=LONG_AGO, day_to=None, hours=HOURS): + return compute_available_slots( + date_from=MONDAY, + date_to=day_to or MONDAY, + duration_minutes=duration, + buffer_minutes=buffer, + existing=list(existing), + hours=hours, + now=now, + ) + + +def test_empty_day_offers_every_step_whose_session_ends_by_close(): + # 60-minute session must END by 13:00 -> last start 12:00 + assert _starts(_compute()) == ["09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00"] + + +def test_buffer_may_spill_past_closing_time(): + # 12:00 + 60 = 13:00 session end (allowed) even though buffer runs to 13:15 + assert "12:00" in _starts(_compute()) + + +def test_slot_end_is_session_end_without_buffer(): + first = _compute()[0] + assert first.end - first.start == timedelta(minutes=60) + + +def test_slots_are_returned_in_business_timezone(): + first = _compute()[0] + assert first.start.utcoffset() == timedelta(hours=-6) + assert first.start.astimezone(UTC).hour == 15 + + +def test_existing_booking_blocks_its_buffer_and_new_sessions_buffer(): + # Existing 10:00 session blocks [10:00, 11:15) + existing = [blocked_interval(_local(MONDAY, 10), 60, 15)] + # 09:00 slot would block [09:00, 10:15) -> overlaps because of the NEW buffer + # 11:00 slot starts before 11:15 -> overlaps because of the EXISTING buffer + assert _starts(_compute(existing)) == ["11:30", "12:00"] + + +def test_slot_whose_buffer_ends_exactly_at_existing_start_is_available(): + # 15-min step so 08:45-style edges are representable; 09:45 + 60 + 15 = 11:00 + hours = BusinessHours(MX, time(9, 0), time(13, 0), frozenset({0}), 15) + existing = [blocked_interval(_local(MONDAY, 11), 60, 15)] + starts = _starts(_compute(existing, hours=hours)) + assert "09:45" in starts + assert "10:00" not in starts # 10:00 + 75 = 11:15 > 11:00 + + +def test_slot_starting_exactly_at_existing_buffer_end_is_available(): + hours = BusinessHours(MX, time(9, 0), time(13, 0), frozenset({0}), 15) + existing = [blocked_interval(_local(MONDAY, 9), 60, 15)] # blocks until 10:15 + starts = _starts(_compute(existing, hours=hours)) + assert starts[0] == "10:15" + assert "10:00" not in starts + + +def test_zero_buffer_service_still_respects_existing_buffer(): + existing = [blocked_interval(_local(MONDAY, 9), 60, 15)] # blocks until 10:15 + starts = _starts(_compute(existing, buffer=0)) + assert "10:00" not in starts + assert starts[0] == "10:30" + + +def test_bookings_on_other_days_do_not_block(): + existing = [blocked_interval(_local(MONDAY + timedelta(days=1), 10), 60, 15)] + assert len(_compute(existing)) == 7 + + +def test_past_and_current_slots_are_excluded(): + now = _local(MONDAY, 10).astimezone(UTC) + starts = _starts(_compute(now=now)) + assert "10:00" not in starts + assert starts[0] == "10:30" + + +def test_non_working_days_offer_no_slots(): + saturday, sunday = MONDAY + timedelta(days=5), MONDAY + timedelta(days=6) + slots = compute_available_slots( + date_from=saturday, + date_to=sunday, + duration_minutes=60, + buffer_minutes=15, + existing=[], + hours=HOURS, + now=LONG_AGO, + ) + assert slots == [] + + +def test_range_is_inclusive_of_both_endpoints(): + slots = _compute(day_to=MONDAY + timedelta(days=1)) + assert {s.start.date() for s in slots} == {MONDAY, MONDAY + timedelta(days=1)} + + +def test_session_longer_than_opening_hours_yields_nothing(): + assert _compute(duration=300) == [] + + +def test_invalid_range_is_rejected(): + with pytest.raises(ValueError): + compute_available_slots( + date_from=MONDAY, + date_to=MONDAY - timedelta(days=1), + duration_minutes=60, + buffer_minutes=15, + existing=[], + hours=HOURS, + now=LONG_AGO, + ) diff --git a/uv.lock b/uv.lock index 9101bba..c6c4037 100644 --- a/uv.lock +++ b/uv.lock @@ -206,6 +206,7 @@ dependencies = [ { name = "sqlalchemy-libsql" }, { name = "sqlmodel" }, { name = "time-machine" }, + { name = "tzdata" }, { name = "uvicorn", extra = ["standard"] }, ] @@ -232,6 +233,7 @@ requires-dist = [ { name = "sqlalchemy-libsql", specifier = ">=0.2.0" }, { name = "sqlmodel", specifier = ">=0.0.48" }, { name = "time-machine", specifier = ">=3.5.1" }, + { name = "tzdata", specifier = ">=2026.5" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" }, ] @@ -2044,6 +2046,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, ] +[[package]] +name = "tzdata" +version = "2026.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/68/f1b440335057bfce71b6e50a9d09445aa2ecbd08359a337976627b8409e7/tzdata-2026.5.tar.gz", hash = "sha256:8cc73c0a0bfca7dbfa59235d60b2eff82231dee33f53d206db1acd9173cfc0a7", size = 200404, upload-time = "2026-10-03T09:23:14.143Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/21/1e5995a1c920cce14e4bffae20c665ec10e7ed03ab25e006cd741092b718/tzdata-2026.5-py2.py3-none-any.whl", hash = "sha256:b683bd1b6659ddcd810ff02ad09ba821d4bf1065072805063eb35c49617905ac", size = 347996, upload-time = "2026-10-03T09:23:12.535Z" }, +] + [[package]] name = "urllib3" version = "2.8.0"