import type { Payload } from "payload"; import { WEEKDAYS } from "@/collections/Availability"; export type TimeSlot = { start: Date; end: Date }; const BERLIN_TZ = "Europe/Berlin"; const WEEKDAY_BY_INDEX = [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", ] as const; type CalendarDate = { year: number; month: number; day: number }; // 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 berlinParts(date: Date): CalendarDate & { hour: number; minute: number } { const parts = new Intl.DateTimeFormat("en-US", { timeZone: BERLIN_TZ, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23", }).formatToParts(date); const get = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? "0"); return { year: get("year"), month: get("month"), day: get("day"), hour: get("hour"), minute: get("minute") }; } function berlinOffsetMinutes(date: Date): number { const tzName = new Intl.DateTimeFormat("en-US", { timeZone: BERLIN_TZ, timeZoneName: "shortOffset" }) .formatToParts(date) .find((p) => p.type === "timeZoneName")?.value ?? "GMT+1"; const match = tzName.match(/GMT([+-]\d+)(?::(\d+))?/); const hours = match ? Number(match[1]) : 1; const minutes = match?.[2] ? Number(match[2]) : 0; return hours * 60 + (hours < 0 ? -minutes : minutes); } /** Converts a Europe/Berlin wall-clock date+time into the UTC instant it represents. */ function berlinWallTimeToUTC(date: CalendarDate, hour: number, minute: number): Date { const guess = Date.UTC(date.year, date.month - 1, date.day, hour, minute); return new Date(guess - berlinOffsetMinutes(new Date(guess)) * 60_000); } 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 }, ): Promise> { const { durationMinutes, from, to } = args; const result = new Map(); const [{ docs: weekly }, { docs: overrides }, { docs: busyBookings }] = await Promise.all([ payload.find({ collection: "availability", where: { active: { equals: true } }, limit: 100 }), payload.find({ collection: "availability-overrides", where: { and: [{ date: { greater_than_equal: from.toISOString() } }, { date: { less_than_equal: to.toISOString() } }] }, limit: 200, }), payload.find({ collection: "booking-requests", where: { and: [ { status: { in: ["pending", "confirmed"] } }, { date: { greater_than_equal: from.toISOString() } }, { date: { less_than_equal: to.toISOString() } }, ], }, limit: 500, }), ]); 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; slots.push({ start: slotStart, end: slotEnd }); } } if (slots.length > 0) result.set(key, slots); } return result; } export { WEEKDAYS };