Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/modules/booking/services/SlotQueryService.server.ts
T
2026-07-08 16:15:37 +02:00

88 lines
3.8 KiB
TypeScript

// AK-P16b · slot query service (loader-side). Loads availability rules, exceptions,
// existing appointments and Google busy intervals (AK-P16a) for a booking page's
// providers, then delegates the timezone-aware arithmetic to the pure slotEngine.
//
// Busy intervals fed to the engine combine, per provider:
// - existing appointments (status scheduled/held) → [startAt, endAt)
// - external/internal calendar events flagged busy → via availability.ts (leak-safe)
// The engine buffers the candidate slot, so raw occupied intervals are enough.
import { db } from "~/utils/db.server";
import { extractBusyIntervals, type BusyInterval } from "~/modules/calendar/services/availability";
import {
computeSlots,
type BookingWeekday,
type ComputedSlot,
type ProviderAvailabilityInput,
type SlotEngineConfig,
type SlotExceptionInput,
type SlotRuleInput,
} from "./slotEngine";
const DAY_MS = 86_400_000;
const OCCUPYING_STATUSES = ["scheduled", "held"] as const;
export interface SlotQueryInput {
readonly tenantId: string;
readonly providerUserIds: readonly string[];
/** Provider-local calendar date `YYYY-MM-DD`. */
readonly date: string;
readonly config: SlotEngineConfig;
readonly now: Date;
}
/** Broad UTC window around the requested local day (covers any provider timezone). */
function dayWindow(date: string): { from: Date; to: Date } {
const midnightUtc = new Date(`${date}T00:00:00Z`).getTime();
return { from: new Date(midnightUtc - DAY_MS), to: new Date(midnightUtc + 2 * DAY_MS) };
}
/** Load one provider's rules, exceptions and busy intervals for the day. */
async function loadProviderInput(tenantId: string, providerUserId: string, date: string): Promise<ProviderAvailabilityInput> {
const window = dayWindow(date);
const [rules, exceptions, appointments, events] = await Promise.all([
db.availabilityRule.findMany({
where: { tenantId, providerUserId },
select: { dayOfWeek: true, startTime: true, endTime: true, timezone: true },
}),
db.availabilityException.findMany({
where: { tenantId, providerUserId, date: new Date(`${date}T00:00:00Z`) },
select: { date: true, kind: true, startTime: true, endTime: true, timezone: true },
}),
db.appointment.findMany({
where: { tenantId, providerUserId, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
select: { startAt: true, endAt: true },
}),
db.calendarEvent.findMany({
where: { tenantId, userId: providerUserId, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
select: { startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
}),
]);
const appointmentBusy: BusyInterval[] = appointments.map((a) => ({ from: a.startAt, to: a.endAt }));
const calendarBusy = extractBusyIntervals(events);
return {
providerUserId,
rules: rules.map((r) => ({ dayOfWeek: r.dayOfWeek as BookingWeekday, startTime: r.startTime, endTime: r.endTime, timezone: r.timezone })) satisfies SlotRuleInput[],
exceptions: exceptions.map((e) => ({
date,
kind: e.kind as SlotExceptionInput["kind"],
startTime: e.startTime,
endTime: e.endTime,
timezone: e.timezone,
})) satisfies SlotExceptionInput[],
busyIntervals: [...appointmentBusy, ...calendarBusy],
};
}
/** Compute the bookable slots for a booking page's providers on a given local day. */
export async function loadSlotsForDate(input: SlotQueryInput): Promise<ComputedSlot[]> {
if (input.providerUserIds.length === 0) {
return [];
}
const providers = await Promise.all(input.providerUserIds.map((id) => loadProviderInput(input.tenantId, id, input.date)));
return computeSlots({ date: input.date, now: input.now, providers, config: input.config });
}