import type { Payload, PayloadRequest } from "payload"; import { WEEKDAYS } from "@/collections/Availability"; import { berlinParts, berlinWallTimeToUTC, type CalendarDate } from "@/lib/calendar/timezone"; export type TimeSlot = { start: Date; end: Date }; const WEEKDAY_BY_INDEX = [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", ] as const; // Availability/AvailabilityOverrides times are entered by the admin in their // browser (Europe/Berlin) and stored as UTC instants. All wall-clock reads // and writes here go through Intl's Berlin timezone data (not local Date // accessors, and not manual UTC+1/+2 arithmetic), so the server process's // own timezone (this app runs in UTC in production) never leaks into the // computed availability - see lib/calendar/timezone.ts for the same pattern. function dateKey(date: Date): string { const { year, month, day } = berlinParts(date); return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`; } function calendarDate(date: Date): CalendarDate { const { year, month, day } = berlinParts(date); return { year, month, day }; } function addCalendarDays({ year, month, day }: CalendarDate, delta: number): CalendarDate { // Pure calendar-rollover arithmetic (month/year boundaries) - no timezone // conversion happens here, so using the UTC constructor is safe and simple. const utc = new Date(Date.UTC(year, month - 1, day + delta)); return { year: utc.getUTCFullYear(), month: utc.getUTCMonth() + 1, day: utc.getUTCDate() }; } function weekdayOf({ year, month, day }: CalendarDate): (typeof WEEKDAY_BY_INDEX)[number] { return WEEKDAY_BY_INDEX[new Date(Date.UTC(year, month - 1, day)).getUTCDay()]; } function timeOfDayMinutes(date: Date): number { const { hour, minute } = berlinParts(date); return hour * 60 + minute; } function atMinutesOfDay(day: CalendarDate, minutes: number): Date { const rounded = Math.round(minutes); return berlinWallTimeToUTC(day, Math.floor(rounded / 60), rounded % 60); } function overlaps(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean { return aStart < bEnd && bStart < aEnd; } /** * Computes bookable slots for one offer across a date range, from the * configured weekly Availability (plus per-date AvailabilityOverrides), * minus anything already pending/confirmed on Anna's schedule - she can * only do one thing at a time, regardless of which offer it's for. */ export async function getAvailableSlots( payload: Payload, args: { durationMinutes: number; from: Date; to: Date; req?: PayloadRequest }, ): Promise> { const { durationMinutes, from, to, req } = args; const result = new Map(); if (!Number.isInteger(durationMinutes) || durationMinutes <= 0 || durationMinutes > 1440 || !Number.isFinite(from.getTime()) || !Number.isFinite(to.getTime()) || to < from || to.getTime() - from.getTime() > 63 * 86400000) return result; const [{ docs: weekly }, { docs: overrides }, { docs: busyBookings }] = await Promise.all([ payload.find({ collection: "availability", where: { active: { equals: true } }, pagination: false, req }), payload.find({ collection: "availability-overrides", where: { and: [{ date: { greater_than_equal: from.toISOString() } }, { date: { less_than_equal: to.toISOString() } }] }, pagination: false, req, }), payload.find({ collection: "booking-requests", where: { and: [ { status: { in: ["pending", "confirmed"] } }, { date: { greater_than_equal: from.toISOString() } }, { date: { less_than_equal: to.toISOString() } }, ], }, pagination: false, req, }), ]); const overridesByDate = new Map(overrides.map((o) => [dateKey(new Date(o.date)), o])); const now = new Date(); for ( let day = calendarDate(from); atMinutesOfDay(day, 0) <= to; day = addCalendarDays(day, 1) ) { const key = `${day.year}-${String(day.month).padStart(2, "0")}-${String(day.day).padStart(2, "0")}`; const override = overridesByDate.get(key); let windows: { startMinutes: number; endMinutes: number }[] = []; if (override?.type === "unavailable") { windows = []; } else if (override?.type === "custom-hours" && override.startTime && override.endTime) { windows = [ { startMinutes: timeOfDayMinutes(new Date(override.startTime)), endMinutes: timeOfDayMinutes(new Date(override.endTime)), }, ]; } else { const weekdayName = weekdayOf(day); windows = weekly .filter((w) => w.weekday === weekdayName) .map((w) => ({ startMinutes: timeOfDayMinutes(new Date(w.startTime)), endMinutes: timeOfDayMinutes(new Date(w.endTime)), })); } const dayBusy = busyBookings .filter((b) => dateKey(new Date(b.date)) === key) .map((b) => ({ start: new Date(b.startTime), end: new Date(b.endTime) })); const slots: TimeSlot[] = []; for (const window of windows) { for (let start = window.startMinutes; start + durationMinutes <= window.endMinutes; start += durationMinutes) { const slotStart = atMinutesOfDay(day, start); const slotEnd = atMinutesOfDay(day, start + durationMinutes); if (slotStart < now) continue; if (dayBusy.some((b) => overlaps(slotStart, slotEnd, b.start, b.end))) continue; if (!slots.some((slot) => slot.start.getTime() === slotStart.getTime())) slots.push({ start: slotStart, end: slotEnd }); } } if (slots.length > 0) result.set(key, slots.sort((a, b) => a.start.getTime() - b.start.getTime())); } return result; } export { WEEKDAYS };