Email for professionals and teams
Added bookings
Hieu Nguyen (Jack)0912416ec4ba
diff --git a/drizzle/migrations/0049_add_booking_events.sql b/drizzle/migrations/0049_add_booking_events.sqlnew file mode 100644index 0000000..4f02ff7--- /dev/null+++ b/drizzle/migrations/0049_add_booking_events.sql@@ -0,0 +1,23 @@+CREATE TABLE `booking_events` (+ `id` text PRIMARY KEY NOT NULL,+ `user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,+ `name` text NOT NULL,+ `slug` text NOT NULL DEFAULT '',+ `description` text NOT NULL DEFAULT '',+ `color` text NOT NULL DEFAULT '#2563eb',+ `host_ids` text NOT NULL DEFAULT '[]',+ `duration_minutes` integer NOT NULL,+ `location` text NOT NULL DEFAULT '',+ `weekdays` text NOT NULL DEFAULT '[1,2,3,4,5]',+ `start_time` text NOT NULL DEFAULT '09:00',+ `end_time` text NOT NULL DEFAULT '17:00',+ `time_ranges` text NOT NULL DEFAULT '[{"startTime":"09:00","endTime":"17:00"}]',+ `time_zone` text NOT NULL DEFAULT 'UTC',+ `enabled` integer NOT NULL DEFAULT 1,+ `created_at` integer NOT NULL,+ `updated_at` integer NOT NULL+);+CREATE INDEX `booking_events_user_idx` ON `booking_events` (`user_id`);+CREATE UNIQUE INDEX `booking_events_user_slug_idx` ON `booking_events` (`user_id`, `slug`);+ALTER TABLE `users` ADD COLUMN `booking_username` text;+CREATE UNIQUE INDEX `users_booking_username_idx` ON `users` (`booking_username`);diff --git a/src/app/(calendar)/booking/booking-editor.tsx b/src/app/(calendar)/booking/booking-editor.tsxnew file mode 100644index 0000000..ae44359--- /dev/null+++ b/src/app/(calendar)/booking/booking-editor.tsx@@ -0,0 +1,59 @@+"use client";++import { useEffect, useState } from "react";+import { CalendarDays, ChevronDown, Clock3, MapPin, MoreHorizontal, Plus, Trash2, UserRound } from "lucide-react";+import clsx from "clsx";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { FOLDER_COLOR_OPTIONS } from "@/lib/folders/colors";+import { slugifyBookingName } from "@/lib/booking/utils";+import type { BookingEditorProps } from "./editor-types";+import type { BookingEditorSection } from "./types";+import { bookingFormWithName, durationLabel, formAvailabilityLabel, matchBookingHost, nextBookingTimeRange, WEEKDAYS } from "./utils";+import { BookingHostAvatar } from "./booking-host-avatar";++export function BookingEditor({ form, open, editingId, username, hosts, canManageHosts, currentUserId, saving, onChange, onClose, onSave, onDelete, onToggleEnabled, onClosed }: BookingEditorProps) {+ const [activeSection, setActiveSection] = useState<BookingEditorSection>(null);+ const [nameEditing, setNameEditing] = useState(false);+ const [moreOpen, setMoreOpen] = useState(false);+ const [hostQuery, setHostQuery] = useState("");+ const [hostError, setHostError] = useState("");+ useEffect(() => { if (open) { setActiveSection(null); setNameEditing(false); setMoreOpen(false); setHostQuery(""); setHostError(""); } }, [editingId, open]);+ const sectionClass = "border-b border-neutral-200 px-5 py-5";+ const headingClass = "flex w-full items-center justify-between gap-3 text-left text-base font-semibold text-neutral-900";+ const fieldClass = "h-10 w-full rounded-xl border border-neutral-200 bg-white px-3 text-sm";+ const toggle = (section: BookingEditorSection) => setActiveSection((current) => current === section ? null : section);++ return <aside aria-label="Event details" aria-hidden={!open} inert={!open} onTransitionEnd={(event) => { if (event.target === event.currentTarget && event.propertyName === "width" && !open) onClosed(); }} className={clsx("relative z-10 h-full shrink-0 overflow-hidden transition-[width] duration-300 ease-in-out motion-reduce:transition-none", open ? "w-full sm:w-[392px]" : "w-0")}>+ <div className={clsx("flex h-full w-[min(392px,100vw)] flex-col overflow-hidden rounded-t-2xl bg-white shadow-2xl shadow-neutral-100 transition-transform duration-300 ease-in-out motion-reduce:transition-none", open ? "translate-x-0" : "translate-x-full")}>+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain scrollbar-gutter-stable">+ <section className={sectionClass}>+ <div className="flex items-center gap-3">+ <button type="button" onClick={() => setActiveSection("event")} aria-label="Edit event color" className="h-6 w-6 shrink-0 rounded-full" style={{ backgroundColor: form.color }} />+ {nameEditing ? <Input autoFocus aria-label="Meeting name" value={form.name} onChange={(event) => onChange(bookingFormWithName(form, event.target.value))} onBlur={() => setNameEditing(false)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === "Escape") setNameEditing(false); }} placeholder="New meeting" maxLength={120} className="min-w-0 flex-1 cursor-text bg-neutral-100 text-xl font-semibold" /> : <button type="button" onClick={() => { setActiveSection("event"); setNameEditing(true); }} className={clsx("min-w-0 flex-1 break-words text-left text-xl font-semibold text-neutral-900", activeSection === "event" ? "cursor-text rounded-lg bg-neutral-100 px-2 py-1" : "hover:text-blue-700")}>{form.name || "New meeting"}</button>}+ <button type="button" onClick={() => toggle("event")} aria-label="Toggle event details" aria-expanded={activeSection === "event"} className="rounded-full p-1 text-neutral-500 hover:bg-neutral-100"><ChevronDown className={clsx("h-5 w-5 transition-transform", activeSection === "event" && "rotate-180")} /></button>+ </div>+ {activeSection === "event" && <div className="mt-5 space-y-4"><label className="block text-sm font-medium text-neutral-700">Link slug<Input value={form.slug} onChange={(event) => onChange({ ...form, slug: slugifyBookingName(event.target.value) })} placeholder="new-meeting" maxLength={80} className="mt-2" /><span className="mt-1 block break-all text-xs font-normal text-neutral-500">/c/{username || "your-name"}/{form.slug || "event-slug"}</span></label><label className="block text-sm font-medium text-neutral-700">Description<Textarea value={form.description} onChange={(event) => onChange({ ...form, description: event.target.value })} placeholder="Tell guests what this meeting is about" maxLength={2000} rows={4} className="mt-2 resize-y" /></label><fieldset><legend className="text-sm font-medium text-neutral-700">Color</legend><div className="mt-2 flex flex-wrap gap-2" role="radiogroup" aria-label="Event color">{FOLDER_COLOR_OPTIONS.map((option) => <button key={option.value} type="button" role="radio" aria-label={option.label} aria-checked={form.color === option.value} onClick={() => onChange({ ...form, color: option.value })} className={clsx("flex h-8 w-8 items-center justify-center rounded-full border-2 border-white ring-2", form.color === option.value ? "ring-neutral-800" : "ring-transparent hover:ring-neutral-300")} style={{ backgroundColor: option.value }}>{form.color === option.value && <span className="h-2 w-2 rounded-full bg-white" />}</button>)}</div></fieldset></div>}+ </section>+ <section className={sectionClass}><button type="button" onClick={() => toggle("duration")} aria-expanded={activeSection === "duration"} className={headingClass}><span>Duration</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "duration" && "rotate-180")} /></button>{activeSection === "duration" ? <div className="mt-4"><select aria-label="Meeting length" value={[15, 30, 45, 60].includes(form.durationMinutes) ? form.durationMinutes : "custom"} onChange={(event) => onChange({ ...form, durationMinutes: event.target.value === "custom" ? 90 : Number(event.target.value) })} className={fieldClass}><option value={15}>15 minutes</option><option value={30}>30 minutes</option><option value={45}>45 minutes</option><option value={60}>1 hour</option><option value="custom">Custom</option></select>{![15, 30, 45, 60].includes(form.durationMinutes) && <Input aria-label="Custom minutes" type="number" min={5} max={480} step={5} value={form.durationMinutes} onChange={(event) => onChange({ ...form, durationMinutes: Number(event.target.value) })} className="mt-3" />}</div> : <button type="button" onClick={() => toggle("duration")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><Clock3 className="h-4 w-4" />{durationLabel(form.durationMinutes)}</button>}</section>+ <section className={sectionClass}><button type="button" onClick={() => toggle("location")} aria-expanded={activeSection === "location"} className={headingClass}><span>Location</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "location" && "rotate-180")} /></button>{activeSection === "location" ? <Input aria-label="Location" value={form.location} onChange={(event) => onChange({ ...form, location: event.target.value })} placeholder="Phone call, video link, or address" maxLength={240} className="mt-4" /> : <button type="button" onClick={() => toggle("location")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><MapPin className="h-4 w-4" />{form.location || "No location set"}</button>}</section>+ <section className={sectionClass}><button type="button" onClick={() => toggle("availability")} aria-expanded={activeSection === "availability"} className={headingClass}><span>Availability</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "availability" && "rotate-180")} /></button>{activeSection === "availability" ? <div className="mt-4 space-y-4"><fieldset aria-label="Available days"><div className="flex flex-wrap gap-1">{WEEKDAYS.map((day) => <button key={day.value} type="button" aria-label={day.label} aria-pressed={form.weekdays.includes(day.value)} onClick={() => onChange({ ...form, weekdays: form.weekdays.includes(day.value) ? form.weekdays.filter((value) => value !== day.value) : [...form.weekdays, day.value].sort() })} className={clsx("rounded-full px-3 py-1.5 text-xs font-medium", form.weekdays.includes(day.value) ? "bg-blue-600 text-white" : "bg-neutral-100 text-neutral-600 hover:bg-neutral-200")}>{day.short}</button>)}</div></fieldset><div className="flex flex-row gap-8 mt-2"><p className="text-sm font-medium text-neutral-700 mt-3">Times</p>++ <div className="space-y-2 flex flex-col items-start flex-1 min-w-0 w-fll">{form.timeRanges.map((range, index) => <div key={index} className="flex items-end gap-2 w-full"><label className="min-w-0 flex-1 text-xs text-neutral-500">From<Input type="time" step={900} value={range.startTime} onChange={(event) => onChange({ ...form, timeRanges: form.timeRanges.map((item, itemIndex) => itemIndex === index ? { ...item, startTime: event.target.value } : item) })} className="mt-1 flex-1 min-w-0" /></label><label className="min-w-0 flex-1 text-xs text-neutral-500">To<Input type="time" step={900} value={range.endTime} onChange={(event) => onChange({ ...form, timeRanges: form.timeRanges.map((item, itemIndex) => itemIndex === index ? { ...item, endTime: event.target.value } : item) })} className="mt-1 flex-1 min-w-0" /></label><button type="button" aria-label={`Remove time ${index + 1}`} disabled={form.timeRanges.length === 1} onClick={() => onChange({ ...form, timeRanges: form.timeRanges.filter((_, itemIndex) => itemIndex !== index) })} className="mb-1 rounded-full p-2 text-neutral-500 hover:bg-neutral-100 disabled:opacity-30"><Trash2 className="h-4 w-4" /></button></div>)}++ <button type="button" disabled={form.timeRanges.length >= 12} onClick={() => onChange({ ...form, timeRanges: [...form.timeRanges, nextBookingTimeRange(form.timeRanges, form.durationMinutes)] })} className="mt-3 inline-flex items-center gap-1 text-sm font-medium text-blue-700 hover:text-blue-600 disabled:opacity-50"><Plus className="h-4 w-4" />Add time</button>+ </div></div>+ <p className="text-xs text-neutral-500">Times use {form.timeZone}.</p></div> : <button type="button" onClick={() => toggle("availability")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><CalendarDays className="h-4 w-4 shrink-0" />{formAvailabilityLabel(form)}</button>}</section>+ <section className={sectionClass}>+ <button type="button" onClick={() => toggle("host")} aria-expanded={activeSection === "host"} className={headingClass}><span>Host</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "host" && "rotate-180")} /></button>+ {activeSection === "host" ? <div className="mt-4 space-y-4">+ <div className="space-y-2">{form.hostIds.map((id) => { const host = hosts.find((item) => item.id === id); const isCurrentUser = id === currentUserId; return <div key={id} className="flex items-center gap-3 rounded-xl bg-neutral-50 px-3 py-2">{host ? <BookingHostAvatar host={host} currentUserId={currentUserId} /> : <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-neutral-200 text-neutral-500"><UserRound className="h-4 w-4" /></span>}<span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-neutral-900">{host?.name || "Unavailable user"}{isCurrentUser ? " (you)" : ""}</span><span className="block truncate text-xs text-neutral-500">{host?.email}</span></span>{!isCurrentUser && <button type="button" onClick={() => onChange({ ...form, hostIds: form.hostIds.filter((hostId) => hostId !== id) })} className="text-xs font-medium text-neutral-500 hover:text-red-600">Remove</button>}</div>; })}</div>+ {canManageHosts && <form onSubmit={(event) => { event.preventDefault(); const match = matchBookingHost(hosts, hostQuery); if (!match.host) { setHostError(match.error); return; } if (form.hostIds.includes(match.host.id)) { setHostError("This user is already a host."); return; } if (form.hostIds.length >= 20) { setHostError("A booking can have up to 20 hosts."); return; } onChange({ ...form, hostIds: [...form.hostIds, match.host.id] }); setHostQuery(""); setHostError(""); }}><label htmlFor="booking-host-input" className="block text-sm font-medium text-neutral-700">Add a host</label><div className="mt-2 flex gap-2"><Input id="booking-host-input" value={hostQuery} onChange={(event) => { setHostQuery(event.target.value); setHostError(""); }} placeholder="Name or email" autoComplete="off" aria-invalid={!!hostError} aria-describedby={hostError ? "booking-host-error" : undefined} className="min-w-0 flex-1" /><Button type="submit" variant="outline" className="shrink-0 rounded-full">Add</Button></div>{hostError && <p id="booking-host-error" role="alert" className="mt-2 text-xs text-red-600">{hostError}</p>}</form>}+ </div> : <button type="button" onClick={() => toggle("host")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><span className="flex shrink-0 -space-x-1">{form.hostIds.slice(0, 3).map((id) => { const host = hosts.find((item) => item.id === id); return host ? <BookingHostAvatar key={id} host={host} currentUserId={currentUserId} size="small" /> : <span key={id} className="flex h-5 w-5 items-center justify-center rounded-full bg-neutral-200"><UserRound className="h-3 w-3" /></span>; })}</span><span className="truncate">{form.hostIds.map((id) => hosts.find((host) => host.id === id)?.name ?? "User").join(", ")}</span></button>}+ </section>+ </div>+ <div className="relative flex shrink-0 items-center justify-end gap-2 bg-white px-4 py-3">{editingId && <div className="relative"><Button type="button" variant="outline" onClick={() => setMoreOpen((value) => !value)} className="h-9 rounded-full px-3"><MoreHorizontal className="h-4 w-4" />More</Button>{moreOpen && <div className="absolute bottom-full right-0 z-20 mb-2 w-40 rounded-xl border border-neutral-200 bg-white p-1 shadow-lg"><button type="button" onClick={() => { setMoreOpen(false); onToggleEnabled(); }} className="block w-full rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100">Turn {form.enabled ? "off" : "on"}</button><button type="button" onClick={() => { setMoreOpen(false); onDelete(); }} className="block w-full rounded-lg px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50">Delete</button></div>}</div>}<Button type="button" variant="ghost" disabled={saving} onClick={onClose} className="h-9 rounded-full px-4">Cancel</Button><Button type="button" disabled={saving} onClick={onSave} className="h-9 rounded-full px-4">{saving ? "Saving…" : editingId ? "Save changes" : "Create"}</Button></div>+ </div>+ </aside>;+}diff --git a/src/app/(calendar)/booking/booking-host-avatar.tsx b/src/app/(calendar)/booking/booking-host-avatar.tsxnew file mode 100644index 0000000..d700861--- /dev/null+++ b/src/app/(calendar)/booking/booking-host-avatar.tsx@@ -0,0 +1,15 @@+"use client";++import { useEffect, useState } from "react";+import { ProgressiveAvatarImage } from "@/components/progressive-avatar-image";+import { getAvatarColorStyle } from "@/lib/avatar-colors";+import type { BookingHostAvatarProps } from "./types";++export function BookingHostAvatar({ host, currentUserId, size = "medium" }: BookingHostAvatarProps) {+ const [imageFailed, setImageFailed] = useState(false);+ const imageUrl = host.id === currentUserId ? "/api/profile/avatar" : `/api/accounts/${host.id}/avatar`;+ const sizeClass = size === "small" ? "h-5 w-5 text-[10px]" : "h-8 w-8 text-sm";+ useEffect(() => { setImageFailed(false); }, [host.id, host.hasAvatar]);+ if (host.hasAvatar && !imageFailed) return <ProgressiveAvatarImage src={imageUrl} alt={`${host.name || host.email} profile picture`} className={`${sizeClass} shrink-0 rounded-full border border-neutral-200 object-cover`} onError={() => setImageFailed(true)} />;+ return <span aria-hidden="true" className={`${sizeClass} flex shrink-0 items-center justify-center rounded-full font-semibold`} style={getAvatarColorStyle(host.email)}>{(host.name || host.email).slice(0, 1).toUpperCase()}</span>;+}diff --git a/src/app/(calendar)/booking/booking-list-skeleton.tsx b/src/app/(calendar)/booking/booking-list-skeleton.tsxnew file mode 100644index 0000000..ef70e70--- /dev/null+++ b/src/app/(calendar)/booking/booking-list-skeleton.tsx@@ -0,0 +1,10 @@+export function BookingListSkeleton() {+ return <div role="status" aria-label="Loading bookings" className="space-y-3">+ <span className="sr-only">Loading bookings…</span>+ {[0, 1, 2].map((item) => <div key={item} className="rounded-2xl border border-neutral-200 bg-white px-5 py-5 motion-safe:animate-pulse">+ <div className="h-5 w-1/2 rounded bg-neutral-200" />+ <div className="mt-4 h-3 w-3/4 rounded bg-neutral-100" />+ <div className="mt-3 h-3 w-2/5 rounded bg-neutral-100" />+ </div>)}+ </div>;+}diff --git a/src/app/(calendar)/booking/default-events.ts b/src/app/(calendar)/booking/default-events.tsnew file mode 100644index 0000000..875f286--- /dev/null+++ b/src/app/(calendar)/booking/default-events.ts@@ -0,0 +1,26 @@+import { DEFAULT_FOLDER_COLOR } from "@/lib/folders/colors";+import type { BookingEvent } from "./types";++const DEFAULT_EVENTS = [+ { id: "template:30-minute", name: "30 Minute Meeting", slug: "30-minute-meeting", durationMinutes: 30, startTime: "09:00", endTime: "11:00" },+ { id: "template:15-minute", name: "15 Minute Meeting", slug: "15-minute-meeting", durationMinutes: 15, startTime: "14:00", endTime: "16:00" },+] as const;++export function visibleBookingEvents(events: BookingEvent[], userId: string, timeZone: string): BookingEvent[] {+ if (!userId || events.some((event) => !DEFAULT_EVENTS.some((template) => template.slug === event.slug))) return events;+ const existingSlugs = new Set(events.map((event) => event.slug));+ const templates: BookingEvent[] = DEFAULT_EVENTS.filter((template) => !existingSlugs.has(template.slug)).map((template) => ({+ ...template,+ userId,+ description: "",+ color: DEFAULT_FOLDER_COLOR,+ hostIds: JSON.stringify([userId]),+ location: "",+ weekdays: "[1,2,3,4,5]",+ timeRanges: JSON.stringify([{ startTime: template.startTime, endTime: template.endTime }]),+ timeZone,+ enabled: false,+ isTemplate: true as const,+ }));+ return [...events, ...templates];+}diff --git a/src/app/(calendar)/booking/editor-types.d.ts b/src/app/(calendar)/booking/editor-types.d.tsnew file mode 100644index 0000000..041c845--- /dev/null+++ b/src/app/(calendar)/booking/editor-types.d.ts@@ -0,0 +1,18 @@+import type { BookingForm, BookingHost } from "./types";++export type BookingEditorProps = {+ form: BookingForm;+ open: boolean;+ editingId: string | null;+ username: string;+ hosts: BookingHost[];+ canManageHosts: boolean;+ currentUserId: string;+ saving: boolean;+ onChange: (form: BookingForm) => void;+ onClose: () => void;+ onSave: () => void;+ onDelete: () => void;+ onToggleEnabled: () => void;+ onClosed: () => void;+};diff --git a/src/app/(calendar)/booking/page.tsx b/src/app/(calendar)/booking/page.tsxnew file mode 100644index 0000000..f90699c--- /dev/null+++ b/src/app/(calendar)/booking/page.tsx@@ -0,0 +1,145 @@+"use client";++import { useEffect, useState } from "react";+import Link from "next/link";+import clsx from "clsx";+import { CalendarDays, Check, Clock3, Copy, ExternalLink, MapPin, MoreHorizontal, Plus } from "lucide-react";+import toast, { Toaster } from "react-hot-toast";+import { Button } from "@/components/ui/button";+import { RouteLoadingBar } from "@/components/route-loading-bar";+import { authFetch } from "@/lib/auth/client";+import { getUserTimeZone } from "@/lib/time/utils";+import { useSidebar } from "@/components/sidebar-state";+import { UpcomingSidebar } from "../upcoming-sidebar";+import { BookingEditor } from "./booking-editor";+import { BookingListSkeleton } from "./booking-list-skeleton";+import { visibleBookingEvents } from "./default-events";+import type { BookingEvent, BookingForm, BookingHost } from "./types";+import { availabilityLabel, durationLabel, emptyBookingForm, formFromEvent } from "./utils";++export default function BookingsPage() {+ const { minimal } = useSidebar();+ const [events, setEvents] = useState<BookingEvent[]>([]);+ const [username, setUsername] = useState("");+ const [hosts, setHosts] = useState<BookingHost[]>([]);+ const [canManageHosts, setCanManageHosts] = useState(false);+ const [currentUserId, setCurrentUserId] = useState("");+ const [loading, setLoading] = useState(true);+ const [editingId, setEditingId] = useState<string | null>(null);+ const [form, setForm] = useState<BookingForm | null>(null);+ const [panelOpen, setPanelOpen] = useState(false);+ const [saving, setSaving] = useState(false);+ const [menuId, setMenuId] = useState<string | null>(null);+ const [savingTemplateId, setSavingTemplateId] = useState<string | null>(null);+ const listEvents = visibleBookingEvents(events, currentUserId, getUserTimeZone());++ useEffect(() => {+ let active = true;+ void authFetch("/api/booking").then(async (response) => {+ if (!response.ok) throw new Error();+ return response.json() as Promise<{ events: BookingEvent[]; username: string | null; currentUser: BookingHost; canManageHosts: boolean }>;+ }).then(async (data) => {+ if (active) { setEvents(data.events); setUsername(data.username ?? ""); setHosts([data.currentUser]); setCurrentUserId(data.currentUser.id); }+ if (!data.canManageHosts) return;+ const response = await authFetch("/api/accounts");+ if (!response.ok) { if (active) toast.error("Could not load the user list."); return; }+ const accounts = await response.json() as { accounts: (BookingHost & { disabled: boolean })[] };+ if (active) { setHosts([data.currentUser, ...accounts.accounts.filter((account) => !account.disabled && account.id !== data.currentUser.id).map(({ id, name, email, hasAvatar }) => ({ id, name, email, hasAvatar }))]); setCanManageHosts(true); }+ })+ .catch(() => { if (active) toast.error("Could not load bookings."); })+ .finally(() => { if (active) setLoading(false); });+ return () => { active = false; };+ }, []);++ useEffect(() => {+ if (panelOpen || !form) return;+ const timeout = window.setTimeout(() => { setForm(null); setEditingId(null); }, 320);+ return () => window.clearTimeout(timeout);+ }, [panelOpen, form]);++ function revealPanel() { setPanelOpen(false); requestAnimationFrame(() => requestAnimationFrame(() => setPanelOpen(true))); }+ function startCreate() { if (!currentUserId) return; setEditingId(null); setForm(emptyBookingForm(getUserTimeZone(), currentUserId)); setMenuId(null); revealPanel(); }+ function startEdit(event: BookingEvent) { setEditingId(event.isTemplate ? null : event.id); setForm({ ...formFromEvent(event), enabled: event.isTemplate ? true : event.enabled }); setMenuId(null); if (!panelOpen) revealPanel(); }+ function closeEditor() { setPanelOpen(false); }++ async function save() {+ if (!form) return;+ setSaving(true);+ try {+ const response = await authFetch(editingId ? `/api/booking/${editingId}` : "/api/booking", { method: editingId ? "PATCH" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form) });+ const data = await response.json() as { event?: BookingEvent; error?: string };+ if (!response.ok || !data.event) { toast.error(data.error ?? "Could not save booking event."); return; }+ setEvents((current) => editingId ? current.map((item) => item.id === editingId ? data.event! : item) : [...current, data.event!]);+ closeEditor();+ toast.success(editingId ? "Booking event saved." : "Booking event created.");+ } catch { toast.error("Could not save booking event."); }+ finally { setSaving(false); }+ }++ async function setEnabled(event: BookingEvent, enabled: boolean) {+ if (event.isTemplate && !enabled) return;+ if (event.isTemplate) setSavingTemplateId(event.id);+ try {+ const response = await authFetch(event.isTemplate ? "/api/booking" : `/api/booking/${event.id}`, { method: event.isTemplate ? "POST" : "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...formFromEvent(event), enabled }) });+ const data = await response.json() as { event?: BookingEvent; error?: string };+ if (!response.ok || !data.event) throw new Error(data.error);+ setEvents((current) => event.isTemplate ? [...current, data.event!] : current.map((item) => item.id === event.id ? data.event! : item));+ if (editingId === event.id && form) setForm({ ...form, enabled });+ setMenuId(null);+ } catch { toast.error(event.isTemplate ? "Could not enable booking event." : "Could not update booking event."); }+ finally { if (event.isTemplate) setSavingTemplateId(null); }+ }++ async function remove(event: BookingEvent) {+ if (!window.confirm(`Delete “${event.name}”?`)) return;+ try {+ const response = await authFetch(`/api/booking/${event.id}`, { method: "DELETE" });+ if (!response.ok) throw new Error();+ setEvents((current) => current.filter((item) => item.id !== event.id));+ if (editingId === event.id) closeEditor();+ setMenuId(null);+ } catch { toast.error("Could not delete booking event."); }+ }++ async function copyLink(event: BookingEvent) {+ if (!username) { toast.error("Booking username is unavailable."); return; }+ try { await navigator.clipboard.writeText(`${window.location.origin}/c/${username}/${event.slug}`); toast.success("Booking link copied."); }+ catch { toast.error("Could not copy booking link."); }+ }++ return <div className={clsx("flex h-full min-h-0 flex-col bg-[#f6f8fc] pl-3 transition-[gap] duration-200 ease-in-out motion-reduce:transition-none lg:flex-row", minimal ? "gap-0" : "gap-3")}>+ <Toaster position="bottom-right" />+ {loading && <RouteLoadingBar />}+ <UpcomingSidebar />+ <section className="min-h-0 min-w-0 flex-1 overflow-hidden overscroll-contain">+ <div className="flex h-full min-h-0 min-w-0">+ <div className="min-w-0 flex-1 overflow-y-auto overscroll-contain scrollbar-gutter-stable">+ <div className="mx-auto max-w-6xl px-5 md:px-8">+ <section aria-label="Booking events" className="space-y-1 pt-3">++ <div className="flex flex-wrap items-start justify-between gap-4 pb-6">+ <div><h1 className="text-3xl font-semibold text-neutral-900">Bookings</h1><p className="mt-1 text-sm text-neutral-500">Set the meetings people can book with you.</p></div>+ <div className="flex items-center gap-2">++ <Button variant="ghost" className="w-10">+ <Link href={`/c/${username}`} target="_blank" className="text-blue-700 underline underline-offset-2">+ <ExternalLink size={18} />+ </Link>+ </Button>++ <Button type="button" onClick={startCreate} disabled={!currentUserId} className="rounded-full"><Plus size={18} />New event</Button></div>+ </div>++ {loading ? <BookingListSkeleton /> : listEvents.length === 0 ? <div className="rounded-2xl border border-dashed border-neutral-300 bg-white px-6 py-12 text-center"><CalendarDays className="mx-auto mb-3 h-8 w-8 text-neutral-400" /><h2 className="font-medium text-neutral-900">No booking events yet</h2><p className="mt-1 text-sm text-neutral-500">Create an event to share your availability.</p></div> : listEvents.map((event, i) => <article key={event.id} className={clsx(!event.enabled && "opacity-65", `relative flex flex-wrap items-center gap-4 rounded-md bg-white px-5 py-5`, i === 0 && "rounded-t-3xl")}>+ <div className="flex min-w-0 flex-1 items-start gap-4"><span className={`mt-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border ${event.enabled ? "border-blue-600 bg-blue-600 text-white" : "border-neutral-300"}`}>{event.enabled && <Check className="h-3.5 w-3.5" />}</span><div className="min-w-0"><button type="button" onClick={() => startEdit(event)} className="text-left text-lg font-semibold text-neutral-900 hover:text-blue-700">{event.name}</button>{event.description && <p className="mt-1 line-clamp-2 whitespace-pre-wrap text-sm text-neutral-600">{event.description}</p>}<p className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-neutral-500"><span className="inline-flex items-center gap-1"><Clock3 className="h-3.5 w-3.5" />{durationLabel(event.durationMinutes)}</span><span>·</span><span className="inline-flex items-center gap-1"><MapPin className="h-3.5 w-3.5" />{event.location || "No location set"}</span></p><p className="mt-2 text-sm text-neutral-500">{availabilityLabel(event)}</p></div></div>+ <div className="ml-auto flex items-center gap-2">{event.enabled ? <><Button type="button" variant="outline" onClick={() => void copyLink(event)} className="h-9 rounded-full px-3"><Copy className="h-4 w-4" />Copy link</Button>{username && <Link href={`/c/${username}/${event.slug}`} target="_blank" aria-label={`Open booking page for ${event.name}`} className="rounded-full p-2 text-neutral-600 hover:bg-neutral-100"><ExternalLink className="h-4 w-4" /></Link>}</> : <Button type="button" variant="outline" disabled={event.isTemplate && savingTemplateId !== null} onClick={() => void setEnabled(event, true)} className="h-9 rounded-full px-3">{savingTemplateId === event.id ? "Turning on…" : "Turn on"}</Button>}+ {!event.isTemplate && <div className="relative"><button type="button" aria-label={`More options for ${event.name}`} aria-expanded={menuId === event.id} onClick={() => setMenuId(menuId === event.id ? null : event.id)} className="rounded-full p-2 text-neutral-600 hover:bg-neutral-100"><MoreHorizontal className="h-5 w-5" /></button>{menuId === event.id && <div className="absolute right-0 top-10 z-10 w-36 rounded-xl border border-neutral-200 bg-white p-1 shadow-lg"><button type="button" onClick={() => startEdit(event)} className="block w-full rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100">Edit</button><button type="button" onClick={() => void setEnabled(event, !event.enabled)} className="block w-full rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100">Turn {event.enabled ? "off" : "on"}</button><button type="button" onClick={() => void remove(event)} className="block w-full rounded-lg px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50">Delete</button></div>}</div>}</div>+ </article>)}+ </section>+ </div>+ </div>+ {form && <BookingEditor form={form} open={panelOpen} editingId={editingId} username={username} hosts={hosts} canManageHosts={canManageHosts} currentUserId={currentUserId} saving={saving} onChange={setForm} onClose={closeEditor} onSave={() => void save()} onDelete={() => { const event = events.find((item) => item.id === editingId); if (event) void remove(event); }} onToggleEnabled={() => { const event = events.find((item) => item.id === editingId); if (event) void setEnabled(event, !event.enabled); }} onClosed={() => { if (!panelOpen) { setForm(null); setEditingId(null); } }} />}+ </div>+ </section>+ </div>;+}diff --git a/src/app/(calendar)/booking/types.d.ts b/src/app/(calendar)/booking/types.d.tsnew file mode 100644index 0000000..cae39a8--- /dev/null+++ b/src/app/(calendar)/booking/types.d.ts@@ -0,0 +1,44 @@+import type { BookingTimeRange } from "@/lib/booking/types";++export type BookingEvent = {+ id: string;+ userId: string;+ name: string;+ slug: string;+ description: string;+ color: string;+ hostIds: string;+ durationMinutes: number;+ location: string;+ weekdays: string;+ startTime: string;+ endTime: string;+ timeRanges: string;+ timeZone: string;+ enabled: boolean;+ isTemplate?: true;+};++export type BookingForm = {+ name: string;+ slug: string;+ description: string;+ color: string;+ hostIds: string[];+ durationMinutes: number;+ location: string;+ weekdays: number[];+ startTime: string;+ endTime: string;+ timeRanges: BookingTimeRange[];+ timeZone: string;+ enabled: boolean;+};++export type BookingHost = { id: string; name: string; email: string; hasAvatar?: boolean };++export type BookingHostAvatarProps = { host: BookingHost; currentUserId: string; size?: "small" | "medium" };++export type BookingHostMatch = { host: BookingHost | null; error: string };++export type BookingEditorSection = "event" | "duration" | "location" | "availability" | "host" | null;diff --git a/src/app/(calendar)/booking/utils.ts b/src/app/(calendar)/booking/utils.tsnew file mode 100644index 0000000..0ed6603--- /dev/null+++ b/src/app/(calendar)/booking/utils.ts@@ -0,0 +1,78 @@+import type { BookingEvent, BookingForm, BookingHost, BookingHostMatch } from "./types";+import { parseBookingTimeRanges } from "@/lib/booking/utils";+import { timeToMinutes } from "@/lib/booking/utils";+import type { BookingTimeRange } from "@/lib/booking/types";+import { DEFAULT_FOLDER_COLOR } from "@/lib/folders/colors";+import { normalizeCalendarColor } from "@/lib/calendar/colors";+import { slugifyBookingName } from "@/lib/booking/utils";+import { parseBookingHostIds } from "@/lib/booking/hosts";++export const WEEKDAYS = [+ { value: 0, short: "Sun", label: "Sunday" },+ { value: 1, short: "Mon", label: "Monday" },+ { value: 2, short: "Tue", label: "Tuesday" },+ { value: 3, short: "Wed", label: "Wednesday" },+ { value: 4, short: "Thu", label: "Thursday" },+ { value: 5, short: "Fri", label: "Friday" },+ { value: 6, short: "Sat", label: "Saturday" },+];++export function emptyBookingForm(timeZone: string, currentUserId: string): BookingForm {+ return { name: "", slug: "", description: "", color: DEFAULT_FOLDER_COLOR, hostIds: [currentUserId], durationMinutes: 30, location: "", weekdays: [1, 2, 3, 4, 5], startTime: "09:00", endTime: "17:00", timeRanges: [{ startTime: "09:00", endTime: "17:00" }], timeZone, enabled: true };+}++export function formFromEvent(event: BookingEvent): BookingForm {+ let weekdays: number[] = [];+ try { weekdays = JSON.parse(event.weekdays) as number[]; } catch { /* An invalid saved schedule remains editable. */ }+ return { name: event.name, slug: event.slug, description: event.description ?? "", color: normalizeCalendarColor(event.color), hostIds: parseBookingHostIds(event.hostIds, event.userId), durationMinutes: event.durationMinutes, location: event.location, weekdays, startTime: event.startTime, endTime: event.endTime, timeRanges: parseBookingTimeRanges(event.timeRanges, { startTime: event.startTime, endTime: event.endTime }), timeZone: event.timeZone, enabled: event.enabled };+}++export function bookingFormWithName(form: BookingForm, name: string): BookingForm {+ return { ...form, name, slug: !form.slug || form.slug === slugifyBookingName(form.name) ? slugifyBookingName(name) : form.slug };+}++export function matchBookingHost(hosts: BookingHost[], value: string): BookingHostMatch {+ const query = value.trim().toLowerCase();+ if (!query) return { host: null, error: "Enter a name or email." };+ if (query.includes("@")) {+ const host = hosts.find((item) => item.email.toLowerCase() === query);+ return host ? { host, error: "" } : { host: null, error: "Invalid email" };+ }+ const matches = hosts.filter((item) => item.name.toLowerCase() === query || item.name.toLowerCase().startsWith(query));+ if (matches.length === 1) return { host: matches[0], error: "" };+ return { host: null, error: matches.length ? "More than one user matches. Enter their email address." : "No user with that name is in your user list." };+}++export function durationLabel(minutes: number): string {+ return minutes === 60 ? "1 hour" : minutes > 60 && minutes % 60 === 0 ? `${minutes / 60} hours` : `${minutes} min`;+}++export function availabilityLabel(event: BookingEvent): string {+ const { weekdays } = formFromEvent(event);+ if (!weekdays.length) return "No days selected";+ const days = weekdays.map((day) => WEEKDAYS.find((item) => item.value === day)?.short).filter(Boolean).join(", ");+ const ranges = parseBookingTimeRanges(event.timeRanges, { startTime: event.startTime, endTime: event.endTime });+ return `${days} · ${ranges.map((range) => `${range.startTime}–${range.endTime}`).join(", ")}`;+}++export function formAvailabilityLabel(form: BookingForm): string {+ if (!form.weekdays.length) return "No days selected";+ const days = form.weekdays.map((day) => WEEKDAYS.find((item) => item.value === day)?.short).filter(Boolean).join(", ");+ return `${days} · ${form.timeRanges.length === 1 ? `${form.timeRanges[0].startTime}–${form.timeRanges[0].endTime}` : `${form.timeRanges.length} time windows`}`;+}++export function nextBookingTimeRange(ranges: BookingTimeRange[], durationMinutes: number): BookingTimeRange {+ const length = Math.ceil(Math.max(durationMinutes, 60) / 15) * 15;+ const occupied = ranges.map((range) => ({ start: timeToMinutes(range.startTime), end: timeToMinutes(range.endTime) })).sort((a, b) => a.start - b.start);+ let start = occupied.length ? occupied[occupied.length - 1].end : 9 * 60;+ if (start + length > 23 * 60 + 45) {+ start = 0;+ for (const range of occupied) {+ if (start + length <= range.start) break;+ start = Math.max(start, range.end);+ }+ }+ const end = Math.min(start + length, 23 * 60 + 45);+ const format = (minutes: number) => `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;+ return { startTime: format(start), endTime: format(end) };+}diff --git a/src/app/(dashboard)/calendar/page.tsx b/src/app/(calendar)/calendar/page.tsxsimilarity index 90%rename from src/app/(dashboard)/calendar/page.tsxrename to src/app/(calendar)/calendar/page.tsxindex 5bae5a6..ac00a47 100644--- a/src/app/(dashboard)/calendar/page.tsx+++ b/src/app/(calendar)/calendar/page.tsx@@ -1,13 +1,15 @@"use client";import { Fragment, useEffect, useMemo, useRef, useState } from "react";+import Link from "next/link";import type { PointerEvent as ReactPointerEvent } from "react";import { createPortal } from "react-dom";import toast, { Toaster } from "react-hot-toast";-import { AlignLeft, ChevronDown, ChevronLeft, ChevronRight, Clock3, MapPin, Palette, Plus, Repeat2, Trash2, UsersRound, X } from "lucide-react";+import { AlignLeft, CalendarPlus2, ChevronDown, ChevronLeft, ChevronRight, Clock3, MapPin, Palette, Plus, Repeat2, Trash2, UsersRound, X } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Textarea } from "@/components/ui/textarea";+import { RouteLoadingBar } from "@/components/route-loading-bar";import { authFetch } from "@/lib/auth/client";import { formatUserDate, getUserTimeZone, parseUserDateTimeLocal } from "@/lib/time/utils";import { normalizeCalendarColor } from "@/lib/calendar/colors";@@ -16,13 +18,13 @@ import { DEFAULT_FOLDER_COLOR, FOLDER_COLOR_OPTIONS } from "@/lib/folders/colorsimport type { CalendarRepeat } from "@/lib/calendar/types";import { useSelectedMailbox } from "@/components/mailbox-provider";import { useSidebar } from "@/components/sidebar-state";-import { SidebarResizeBoundary } from "@/components/sidebar-resize-boundary";+import { UpcomingSidebar } from "../upcoming-sidebar";import type { CalendarEvent, CalendarView, EventDragPreview, EventResizeEdge, EventResizeSession } from "./types";import {addDays, addMonths, calendarAnchorDay, CALENDAR_END_HOUR, CALENDAR_HOUR_HEIGHT, CALENDAR_START_HOUR,currentTimePosition, dateKey, defaultCalendarStart, dropStartForPosition, EVENT_COLOR_CLASSES, eventEndAfterMinutes, eventPosition, expandCalendarEvents,- formatEventRange, formatHour, formatLocalDateTime, groupUpcomingEvents,- monthGridDates, PAST_EVENT_COLOR_CLASSES, rescheduleCalendarOccurrence, resizeEventTimes, startOfDay, startOfMonth, startOfWeek, takeUpcomingGroups, UPCOMING_BATCH_SIZE, WEEKDAY_OPTIONS,+ formatEventRange, formatHour, formatLocalDateTime,+ monthGridDates, PAST_EVENT_COLOR_CLASSES, rescheduleCalendarOccurrence, resizeEventTimes, startOfDay, startOfMonth, startOfWeek, WEEKDAY_OPTIONS,} from "./utils";import clsx from "clsx";@@ -30,6 +32,7 @@ const eventFieldClass = "h-9 border-transparent bg-transparent px-2 shadow-noneexport default function CalendarPage() {const [events, setEvents] = useState<CalendarEvent[]>([]);+ const [loading, setLoading] = useState(true);const [eventsVersion, setEventsVersion] = useState(0);const [currentTime, setCurrentTime] = useState(() => Date.now());const [visibleDate, setVisibleDate] = useState(() => new Date());@@ -37,8 +40,7 @@ export default function CalendarPage() {const [monthPickerOpen, setMonthPickerOpen] = useState(false);const [pickerMonth, setPickerMonth] = useState(() => new Date());const monthPickerRef = useRef<HTMLDivElement | null>(null);- const upcomingScrollRef = useRef<HTMLDivElement | null>(null);- const upcomingSentinelRef = useRef<HTMLDivElement | null>(null);+ const openedEventFromUrl = useRef<string | null>(null);const [headerTarget, setHeaderTarget] = useState<HTMLElement | null>(null);const [draggedEvent, setDraggedEvent] = useState<CalendarEvent | null>(null);const [resizingEvent, setResizingEvent] = useState<CalendarEvent | null>(null);@@ -59,7 +61,6 @@ export default function CalendarPage() {const [description, setDescription] = useState("");const [editing, setEditing] = useState<CalendarEvent | null>(null);const [pendingAction, setPendingAction] = useState<"save" | string | null>(null);- const [visibleUpcomingCount, setVisibleUpcomingCount] = useState(UPCOMING_BATCH_SIZE);const { selectedMailbox } = useSelectedMailbox();const { minimal } = useSidebar();@@ -71,9 +72,6 @@ export default function CalendarPage() {() => view === "day" ? [startOfDay(visibleDate)] : Array.from({ length: 7 }, (_, index) => addDays(weekStart, index)),[view, visibleDate, weekStart],);- const upcomingGroups = useMemo(() => groupUpcomingEvents(events, today), [events, today]);- const upcomingTotal = useMemo(() => upcomingGroups.reduce((count, group) => count + group.events.length, 0), [upcomingGroups]);- const visibleUpcomingGroups = useMemo(() => takeUpcomingGroups(upcomingGroups, visibleUpcomingCount), [upcomingGroups, visibleUpcomingCount]);const pickerDates = useMemo(() => monthGridDates(pickerMonth), [pickerMonth]);const previewEvent = useMemo(() => dragPreview && (draggedEvent || resizingEvent)? {@@ -95,21 +93,6 @@ export default function CalendarPage() {return () => window.clearInterval(interval);}, []);- useEffect(() => {- setVisibleUpcomingCount(UPCOMING_BATCH_SIZE);- }, [events]);-- useEffect(() => {- if (minimal || visibleUpcomingCount >= upcomingTotal || !upcomingScrollRef.current || !upcomingSentinelRef.current) return;- const observer = new IntersectionObserver(([entry]) => {- if (!entry?.isIntersecting) return;- observer.disconnect();- setVisibleUpcomingCount((count) => Math.min(count + UPCOMING_BATCH_SIZE, upcomingTotal));- }, { root: upcomingScrollRef.current, rootMargin: "0px 0px 100px 0px" });- observer.observe(upcomingSentinelRef.current);- return () => observer.disconnect();- }, [minimal, upcomingTotal, visibleUpcomingCount]);-useEffect(() => {if (!monthPickerOpen) return;const closeOnOutsidePointer = (event: PointerEvent) => {@@ -127,6 +110,8 @@ export default function CalendarPage() {}, [monthPickerOpen]);useEffect(() => {+ let active = true;+ setLoading(true);const start = new Date(Math.min(today.getTime(), weekStart.getTime(), startOfDay(visibleDate).getTime()));const end = new Date(Math.max(addDays(today, 90).getTime(), addDays(weekStart, 7).getTime(), addDays(visibleDate, 1).getTime()));void authFetch(`/api/calendar/events?start=${start.toISOString()}&end=${end.toISOString()}`)@@ -134,10 +119,21 @@ export default function CalendarPage() {if (!response.ok) throw new Error("Could not load calendar events.");return response.json();})- .then((data) => setEvents(expandCalendarEvents(data.events ?? [], start, end)))- .catch(() => toast.error("Could not load calendar events."));+ .then((data) => { if (active) setEvents(expandCalendarEvents(data.events ?? [], start, end)); })+ .catch(() => { if (active) toast.error("Could not load calendar events."); })+ .finally(() => { if (active) setLoading(false); });+ return () => { active = false; };}, [today, visibleDate, weekStart, eventsVersion]);+ useEffect(() => {+ const eventFromUrl = new URLSearchParams(window.location.search).get("event");+ if (!eventFromUrl || openedEventFromUrl.current === eventFromUrl) return;+ const event = events.find((item) => item.id === eventFromUrl);+ if (!event) return;+ openedEventFromUrl.current = eventFromUrl;+ editEvent(event);+ }, [events]);+function openNewEvent(day = visibleDate, startAt?: Date) {const start = startAt ? new Date(startAt) : defaultCalendarStart(day);setEditing(null);@@ -351,8 +347,10 @@ export default function CalendarPage() {return (<div className={clsx("flex h-full min-h-0 flex-col bg-[#f6f8fc] pl-3 lg:flex-row transition-[gap] duration-200 ease-in-out motion-reduce:transition-none", minimal ? "gap-0" : "gap-3")}><Toaster position="bottom-right" />+ {loading && <RouteLoadingBar />}{headerTarget && createPortal(<div className="flex min-w-0 flex-1 items-center justify-between gap-3">+ <div className="flex shrink-0 items-center gap-2"><div ref={monthPickerRef} className="relative shrink-0"><button type="button" onClick={() => {setPickerMonth(startOfMonth(visibleDate));@@ -397,6 +395,7 @@ export default function CalendarPage() {</div>)}</div>+ </div><div className="flex shrink-0 items-center gap-1.5"><button type="button" aria-label={`Previous ${view}`} onClick={() => setVisibleDate(addDays(visibleDate, view === "week" ? -7 : -1))} className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-white"><ChevronLeft className="h-6 w-6" /></button><button type="button" aria-label={`Next ${view}`} onClick={() => setVisibleDate(addDays(visibleDate, view === "week" ? 7 : 1))} className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-white"><ChevronRight className="h-6 w-6" /></button>@@ -413,37 +412,9 @@ export default function CalendarPage() {</div>,headerTarget,)}- <aside className={clsx("relative shrink-0 rounded-t-3xl bg-white transition-[width,max-height] duration-200 ease-in-out motion-reduce:transition-none lg:h-full lg:max-h-none", minimal ? "w-0 max-h-0" : "w-full max-h-[36vh] lg:w-[var(--sidebar-width)]")} aria-hidden={minimal}>- {!minimal && (- <div ref={upcomingScrollRef} className="h-full overflow-y-auto overscroll-contain rounded-t-3xl px-5 py-5">- {upcomingGroups.length === 0 ? (- <div>- <h2 className="text-lg font-semibold text-neutral-900">Upcoming</h2>- <p className="mt-4 text-sm text-neutral-400">No upcoming events.</p>- </div>- ) : visibleUpcomingGroups.map((group) => (- <section key={group.key} className="mb-6 last:mb-0">- <h2 className="sticky -top-5 z-10 -mx-5 mb-2 bg-white px-5 py-2 text-base font-semibold text-neutral-900">{group.label}</h2>- <div className="space-y-2">- {group.events.map((event) => (- <button key={event.id} type="button" onClick={() => editEvent(event)} className="group flex w-full items-start gap-3 text-left">- <span className="mt-0.5 h-4 w-4 shrink-0 rounded-full border-2 border-white ring-1 ring-neutral-200" style={{ backgroundColor: normalizeCalendarColor(event.color) }} />- <span className="min-w-0">- <span className="block truncate text-sm text-neutral-700 group-hover:text-neutral-950">{event.title}</span>- <span className="block text-xs text-neutral-400">{formatEventRange(event)}</span>- </span>- </button>- ))}- </div>- </section>- ))}- {visibleUpcomingCount < upcomingTotal && <div ref={upcomingSentinelRef} aria-hidden="true" className="h-1" />}- </div>- )}- {!minimal && <div className="hidden lg:block"><SidebarResizeBoundary /></div>}- </aside>+ <UpcomingSidebar events={events} onSelect={editEvent} />- <section className="min-h-0 min-w-0 flex-1 rounded-t-3xl bg-white flex flex-col overflow-hidden">+ <section aria-busy={loading} className="min-h-0 min-w-0 flex-1 rounded-t-3xl bg-white flex flex-col overflow-hidden"><div className="min-h-0 min-w-0 flex-1 overflow-auto overscroll-contain"><div className={clsx("w-full", view === "week" ? "min-w-190" : "min-w-90")}><div className="sticky top-0 z-30 grid h-14 border-b border-neutral-200 bg-white" style={{ gridTemplateColumns: `64px repeat(${days.length}, minmax(0, 1fr))` }}>diff --git a/src/app/(dashboard)/calendar/types.d.ts b/src/app/(calendar)/calendar/types.d.tssimilarity index 100%rename from src/app/(dashboard)/calendar/types.d.tsrename to src/app/(calendar)/calendar/types.d.tsdiff --git a/src/app/(dashboard)/calendar/utils.ts b/src/app/(calendar)/calendar/utils.tssimilarity index 100%rename from src/app/(dashboard)/calendar/utils.tsrename to src/app/(calendar)/calendar/utils.tsdiff --git a/src/app/(calendar)/layout.tsx b/src/app/(calendar)/layout.tsxnew file mode 100644index 0000000..4e7872f--- /dev/null+++ b/src/app/(calendar)/layout.tsx@@ -0,0 +1,77 @@+"use client";++import { useEffect } from "react";+import Link from "next/link";+import { usePathname } from "next/navigation";+import { Sparkles } from "lucide-react";+import { AgentPanel } from "@/components/agent/agent-panel";+import { AssistantOpenContext } from "@/components/agent/assistant-open-state";+import { AuthGuard } from "@/components/auth/auth-guard";+import { ComposeProvider } from "@/components/compose/compose-context";+import { FloatingComposer } from "@/components/compose/floating-composer";+import { LicenseIndicator } from "@/components/license-indicator";+import { MailSearchProvider } from "@/components/mail-search/mail-search-context";+import { MailboxProvider } from "@/components/mailbox-provider";+import { MailboxSelector } from "@/components/mailbox-selector";+import { SidebarHeader } from "@/components/sidebar-header";+import { SidebarProvider } from "@/components/sidebar-state";+import { ShortcutsProvider } from "@/components/shortcuts";+import { Button } from "@/components/ui/button";+import clsx from "clsx";+import { useDashboardState } from "../(dashboard)/dashboard-state";+import { useAssistantAvailability } from "../(dashboard)/use-assistant-availability";++export default function CalendarLayout({ children }: { children: React.ReactNode }) {+ const pathname = usePathname();+ const { assistantOpen, setAssistantOpen, assistantFullSize, setAssistantFullSize } = useDashboardState();+ const assistantEnabled = useAssistantAvailability();+ const assistantVisible = assistantEnabled === true && assistantOpen;++ useEffect(() => {+ if (assistantEnabled === false && (assistantOpen || assistantFullSize)) {+ setAssistantOpen(false);+ setAssistantFullSize(false);+ }+ }, [assistantEnabled, assistantOpen, assistantFullSize, setAssistantOpen, setAssistantFullSize]);++ return (+ <AuthGuard>+ <SidebarProvider>+ <MailboxProvider>+ <ComposeProvider>+ <MailSearchProvider>+ <ShortcutsProvider>+ <div className="grid h-dvh grid-cols-[minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]">+ <div className="flex min-h-0 min-w-0 flex-col">+ <header className="flex h-16 w-full shrink-0 items-center gap-3 pr-4 text-sm">+ <div className="shrink-0 px-3 [&>div]:mb-0" style={{ width: "calc(var(--sidebar-width) + 1.5rem)" }}><SidebarHeader href="/inbox" /></div>+ <nav aria-label="Calendar sections" className="flex shrink-0 items-center rounded-full bg-white p-1">+ <Link href="/booking" aria-current={pathname === "/booking" ? "page" : undefined} className={clsx("rounded-full px-4 py-2 text-sm font-medium transition-colors", pathname === "/booking" ? "bg-blue-600 text-white" : "text-neutral-600 hover:bg-neutral-100")}>Bookings</Link>+ <Link href="/calendar" aria-current={pathname === "/calendar" ? "page" : undefined} className={clsx("rounded-full px-4 py-2 text-sm font-medium transition-colors", pathname === "/calendar" ? "bg-blue-600 text-white" : "text-neutral-600 hover:bg-neutral-100")}>Calendar</Link>+ </nav>+ <div id="calendar-header-slot" className="flex min-w-0 flex-1 items-center" />+ <LicenseIndicator />+ {assistantEnabled && <Button type="button" variant="ghost" size="sm" className={assistantOpen ? "bg-blue-50 text-blue-700" : "text-neutral-600"} onClick={() => { setAssistantOpen((current) => !current); setAssistantFullSize(false); }} aria-label={assistantOpen ? "Close email assistant" : "Open email assistant"} aria-expanded={assistantOpen} aria-controls="email-assistant-panel"><Sparkles className="h-5 w-5" /></Button>}+ <MailboxSelector />+ </header>+ <div className="flex min-h-0 min-w-0 flex-1 overflow-hidden">+ <AssistantOpenContext.Provider value={assistantVisible}>+ <main className="min-h-0 min-w-0 flex-1 overflow-hidden bg-[#f6f8fc] overscroll-contain scrollbar-gutter-stable" aria-hidden={assistantVisible && assistantFullSize} inert={assistantVisible && assistantFullSize}>+ <div key={pathname} className="page-transition-enter h-full min-h-0">{children}</div>+ </main>+ </AssistantOpenContext.Provider>+ <aside className={clsx(assistantFullSize ? "pl-0" : "pl-4", "min-h-0 min-w-0 shrink-0 overflow-hidden pb-2 pr-2 transition-[width] duration-300 ease-in-out motion-reduce:transition-none", assistantVisible ? "" : "opacity-0")} style={{ width: assistantVisible ? assistantFullSize ? "100%" : "min(390px, 100%)" : "0px" }} aria-hidden={!assistantVisible} inert={!assistantVisible}>+ {assistantEnabled && <AgentPanel open={assistantVisible} fullSize={assistantFullSize} onToggleFullSize={() => setAssistantFullSize((current) => !current)} onClose={() => { setAssistantOpen(false); setAssistantFullSize(false); }} />}+ </aside>+ </div>+ </div>+ <FloatingComposer />+ </div>+ </ShortcutsProvider>+ </MailSearchProvider>+ </ComposeProvider>+ </MailboxProvider>+ </SidebarProvider>+ </AuthGuard>+ );+}diff --git a/src/app/(calendar)/upcoming-sidebar-types.d.ts b/src/app/(calendar)/upcoming-sidebar-types.d.tsnew file mode 100644index 0000000..0fbf6e2--- /dev/null+++ b/src/app/(calendar)/upcoming-sidebar-types.d.ts@@ -0,0 +1,6 @@+import type { CalendarEvent } from "./calendar/types";++export type UpcomingSidebarProps = {+ events?: CalendarEvent[];+ onSelect?: (event: CalendarEvent) => void;+};diff --git a/src/app/(calendar)/upcoming-sidebar.tsx b/src/app/(calendar)/upcoming-sidebar.tsxnew file mode 100644index 0000000..edae60e--- /dev/null+++ b/src/app/(calendar)/upcoming-sidebar.tsx@@ -0,0 +1,62 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { useRouter } from "next/navigation";+import clsx from "clsx";+import { SidebarResizeBoundary } from "@/components/sidebar-resize-boundary";+import { useSidebar } from "@/components/sidebar-state";+import { authFetch } from "@/lib/auth/client";+import { normalizeCalendarColor } from "@/lib/calendar/colors";+import type { CalendarEvent } from "./calendar/types";+import { addDays, expandCalendarEvents, formatEventRange, groupUpcomingEvents, startOfDay, takeUpcomingGroups, UPCOMING_BATCH_SIZE } from "./calendar/utils";+import type { UpcomingSidebarProps } from "./upcoming-sidebar-types";++export function UpcomingSidebar({ events, onSelect }: UpcomingSidebarProps) {+ const { minimal } = useSidebar();+ const router = useRouter();+ const [loadedEvents, setLoadedEvents] = useState<CalendarEvent[]>([]);+ const [loadError, setLoadError] = useState(false);+ const [visibleCount, setVisibleCount] = useState(UPCOMING_BATCH_SIZE);+ const scrollRef = useRef<HTMLDivElement | null>(null);+ const sentinelRef = useRef<HTMLDivElement | null>(null);+ const today = useMemo(() => startOfDay(new Date()), []);+ const shownEvents = events ?? loadedEvents;+ const groups = useMemo(() => groupUpcomingEvents(shownEvents, today), [shownEvents, today]);+ const total = useMemo(() => groups.reduce((count, group) => count + group.events.length, 0), [groups]);+ const visibleGroups = useMemo(() => takeUpcomingGroups(groups, visibleCount), [groups, visibleCount]);++ useEffect(() => {+ if (events !== undefined) return;+ let active = true;+ const end = addDays(today, 90);+ void authFetch(`/api/calendar/events?start=${today.toISOString()}&end=${end.toISOString()}`)+ .then(async (response) => {+ if (!response.ok) throw new Error();+ return response.json() as Promise<{ events?: CalendarEvent[] }>;+ })+ .then((data) => { if (active) setLoadedEvents(expandCalendarEvents(data.events ?? [], today, end)); })+ .catch(() => { if (active) setLoadError(true); });+ return () => { active = false; };+ }, [events, today]);++ useEffect(() => { setVisibleCount(UPCOMING_BATCH_SIZE); }, [shownEvents]);++ useEffect(() => {+ if (minimal || visibleCount >= total || !scrollRef.current || !sentinelRef.current) return;+ const observer = new IntersectionObserver(([entry]) => {+ if (!entry?.isIntersecting) return;+ observer.disconnect();+ setVisibleCount((count) => Math.min(count + UPCOMING_BATCH_SIZE, total));+ }, { root: scrollRef.current, rootMargin: "0px 0px 100px 0px" });+ observer.observe(sentinelRef.current);+ return () => observer.disconnect();+ }, [minimal, total, visibleCount]);++ return <aside className={clsx("relative shrink-0 rounded-t-3xl bg-white transition-[width,max-height] duration-200 ease-in-out motion-reduce:transition-none lg:h-full lg:max-h-none", minimal ? "w-0 max-h-0" : "w-full max-h-[36vh] lg:w-[var(--sidebar-width)]")} aria-hidden={minimal}>+ {!minimal && <div ref={scrollRef} className="h-full overflow-y-auto overscroll-contain rounded-t-3xl px-5 py-5">+ {groups.length === 0 ? <div><h2 className="text-lg font-semibold text-neutral-900">Upcoming</h2><p className="mt-4 text-sm text-neutral-400">{loadError ? "Could not load upcoming events." : "No upcoming events."}</p></div> : visibleGroups.map((group) => <section key={group.key} className="mb-6 last:mb-0"><h2 className="sticky -top-5 z-10 -mx-5 mb-2 bg-white px-5 py-2 text-base font-semibold text-neutral-900">{group.label}</h2><div className="space-y-2">{group.events.map((event) => <button key={event.id} type="button" onClick={() => onSelect ? onSelect(event) : router.push(`/calendar?event=${encodeURIComponent(event.id)}`)} className="group flex w-full items-start gap-3 text-left"><span className="mt-0.5 h-4 w-4 shrink-0 rounded-full border-2 border-white ring-1 ring-neutral-200" style={{ backgroundColor: normalizeCalendarColor(event.color) }} /><span className="min-w-0"><span className="block truncate text-sm text-neutral-700 group-hover:text-neutral-950">{event.title}</span><span className="block text-xs text-neutral-400">{formatEventRange(event)}</span></span></button>)}</div></section>)}+ {visibleCount < total && <div ref={sentinelRef} aria-hidden="true" className="h-1" />}+ </div>}+ {!minimal && <div className="hidden lg:block"><SidebarResizeBoundary /></div>}+ </aside>;+}diff --git a/src/app/(dashboard)/layout.tsx b/src/app/(dashboard)/layout.tsxindex 9f96c11..e3a87ad 100644--- a/src/app/(dashboard)/layout.tsx+++ b/src/app/(dashboard)/layout.tsx@@ -1,9 +1,7 @@"use client";import { useEffect } from "react";-import Link from "next/link";-import { usePathname } from "next/navigation";-import { HelpCircle, Sparkles } from "lucide-react";+import { Sparkles } from "lucide-react";import { AuthGuard } from "@/components/auth/auth-guard";import { ComposeProvider } from "@/components/compose/compose-context";import { FloatingComposer } from "@/components/compose/floating-composer";@@ -16,7 +14,6 @@ import { AssistantOpenContext } from "@/components/agent/assistant-open-state";import { Button } from "@/components/ui/button";import { LicenseIndicator } from "@/components/license-indicator";import { DashboardNav } from "@/components/dashboard-nav";-import { SidebarHeader } from "@/components/sidebar-header";import { SidebarProvider } from "@/components/sidebar-state";import { SidebarResizeBoundary } from "@/components/sidebar-resize-boundary";import { ShortcutsProvider } from "@/components/shortcuts";@@ -32,8 +29,6 @@ export default function DashboardLayout({const { assistantOpen, setAssistantOpen, assistantFullSize, setAssistantFullSize } = useDashboardState();const assistantEnabled = useAssistantAvailability();const assistantVisible = assistantEnabled === true && assistantOpen;- const pathname = usePathname();- const isCalendarPage = pathname === "/calendar" || pathname.startsWith("/calendar/");useEffect(() => {if (assistantEnabled === false && (assistantOpen || assistantFullSize)) {@@ -49,17 +44,16 @@ export default function DashboardLayout({<ComposeProvider><MailSearchProvider><ShortcutsProvider>- <div className={clsx("grid h-dvh overflow-hidden bg-[#f6f8fc] transition-[grid-template-columns]", isCalendarPage ? "grid-cols-[minmax(0,1fr)]" : "grid-cols-[72px_minmax(0,1fr)] md:grid-cols-[var(--sidebar-width)_minmax(0,1fr)]")} style={{ transitionDuration: "var(--sidebar-transition-duration)" }}>- {!isCalendarPage && <aside className="relative z-30 w-[var(--sidebar-width)] min-h-0 min-w-0 bg-[#f6f8fc]">+ <div className="grid h-dvh grid-cols-[72px_minmax(0,1fr)] overflow-hidden bg-[#f6f8fc] transition-[grid-template-columns] md:grid-cols-[var(--sidebar-width)_minmax(0,1fr)]" style={{ transitionDuration: "var(--sidebar-transition-duration)" }}>+ <aside className="relative z-30 w-[var(--sidebar-width)] min-h-0 min-w-0 bg-[#f6f8fc]"><div className="h-full overflow-y-auto overscroll-contain px-3 py-4 scrollbar-gutter-stable"><DashboardNav /></div><SidebarResizeBoundary />- </aside>}+ </aside><div className="flex min-h-0 min-w-0 flex-col"><header className="flex h-16 w-full shrink-0 items-center gap-3 pr-4 text-sm">- {isCalendarPage && <div className="shrink-0 px-3 transition-[width] duration-200 ease-in-out motion-reduce:transition-none [&>div]:mb-0" style={{ width: "calc(var(--sidebar-width) + 1.5rem)" }}><SidebarHeader href="/inbox" /></div>}- {isCalendarPage ? <div id="calendar-header-slot" className="flex min-w-0 flex-1 items-center" /> : <MailSearchInput />}+ <MailSearchInput />{/* <Linkhref="/settings/account"className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"@@ -73,7 +67,7 @@ export default function DashboardLayout({</header><div className="flex min-h-0 min-w-0 flex-1 overflow-hidden"><AssistantOpenContext.Provider value={assistantVisible}>- <main className={clsx("min-h-0 min-w-0 flex-1 overscroll-contain scrollbar-gutter-stable", isCalendarPage ? "overflow-hidden bg-[#f6f8fc]" : "rounded-t-3xl overflow-y-auto bg-white")} aria-hidden={assistantVisible && assistantFullSize} inert={assistantVisible && assistantFullSize}>+ <main className="min-h-0 min-w-0 flex-1 overflow-y-auto rounded-t-3xl bg-white overscroll-contain scrollbar-gutter-stable" aria-hidden={assistantVisible && assistantFullSize} inert={assistantVisible && assistantFullSize}>{children}</main></AssistantOpenContext.Provider>diff --git a/src/app/api/accounts/[id]/avatar/route.ts b/src/app/api/accounts/[id]/avatar/route.tsindex f6fda78..840099b 100644--- a/src/app/api/accounts/[id]/avatar/route.ts+++ b/src/app/api/accounts/[id]/avatar/route.ts@@ -6,11 +6,14 @@ import { getAvatarImageResponse, getOptimizedAvatarFiles, storeAvatarImages } frimport { avatarKeyFor } from "@/app/api/profile/avatar/utils";import type { AccountRouteParams } from "../types";import { getManagedAccount } from "./utils";+import { requireTeamAdmin } from "../../utils";+import { selectAccountById } from "../utils";export async function GET(request: Request, { params }: AccountRouteParams) {const { id } = await params;- const { access, account } = await getManagedAccount(request, id);+ const access = await requireTeamAdmin(request);if (access.error) return access.error;+ const account = await selectAccountById(getDb(access.env), id);if (!account?.avatarKey) return new Response("Not found", { status: 404 });return getAvatarImageResponse(request, access.env.BUCKET, account.avatarKey);}diff --git a/src/app/api/accounts/route.ts b/src/app/api/accounts/route.tsindex aa98029..db7b939 100644--- a/src/app/api/accounts/route.ts+++ b/src/app/api/accounts/route.ts@@ -7,6 +7,7 @@ import { newId } from "@/lib/ids";import { createUserAccountSchema } from "@/lib/validators";import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";+import { ensureBookingUsername } from "@/lib/booking/username";import type { CreateUserAccountInput } from "./types";import {accountListItemFromUser,@@ -67,6 +68,7 @@ export async function POST(request: Request) {disabled: users.disabled,createdAt: users.createdAt,});+ await ensureBookingUsername(access.env, userId, email);const mailboxId = newId("mbx");await db.insert(mailboxes).values({id: mailboxId,diff --git a/src/app/api/api-keys/route.ts b/src/app/api/api-keys/route.tsindex 931556c..3b08788 100644--- a/src/app/api/api-keys/route.ts+++ b/src/app/api/api-keys/route.ts@@ -14,7 +14,7 @@ import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";const createKeySchema = z.object({name: z.string().trim().min(1).max(100),scopes: z.array(z.enum([...API_KEY_SCOPES])).min(1),- mailboxIds: z.array(z.string().min(1)).min(1).max(30),+ mailboxIds: z.array(z.string().min(1)).max(30),});export async function GET(request: Request) {@@ -51,6 +51,7 @@ export async function POST(request: Request) {const { fullKey, prefix, hash } = generateApiKey();const db = getDb(env);const mailboxIds = [...new Set(parsed.data.mailboxIds)];+ if (!mailboxIds.length && parsed.data.scopes.some((scope) => !scope.startsWith("calendar:"))) return NextResponse.json({ error: "Choose a mailbox for mail permissions" }, { status: 400 });for (const mailboxId of mailboxIds) if (!(await getMailboxAccessLevel(db, user, mailboxId))?.canRead) return NextResponse.json({ error: "Mailbox not found" }, { status: 403 });const id = newId("key");await db.insert(apiKeys).values({@@ -62,7 +63,7 @@ export async function POST(request: Request) {scopes: scopesToJson([...new Set(parsed.data.scopes)]),mailboxScopeEnabled: true,});- await db.insert(mcpKeyMailboxes).values(mailboxIds.map((mailboxId) => ({ keyId: id, mailboxId })));+ if (mailboxIds.length) await db.insert(mcpKeyMailboxes).values(mailboxIds.map((mailboxId) => ({ keyId: id, mailboxId })));return NextResponse.json({ id, name: parsed.data.name, prefix, key: fullKey, mailboxIds });}diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.tsindex cf2925d..f2e7e34 100644--- a/src/app/api/auth/register/route.ts+++ b/src/app/api/auth/register/route.ts@@ -17,6 +17,7 @@ import { readJsonBody } from "@/lib/http/request";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { verifyTurnstileToken } from "@/lib/auth/turnstile";import { getDomainProvisioningError } from "@/lib/domains/errors";+import { ensureBookingUsername } from "@/lib/booking/username";export async function POST(request: Request) {const env = getEnv();@@ -68,6 +69,7 @@ export async function POST(request: Request) {// config would go unnoticed.let changes: DomainProvisioningChanges | null = null;try {+ await ensureBookingUsername(env, userId, email);const added = await addDomainForUser(env, userId, domainName, {enableRouting: true,enableSending: firstRunParsed.data.enableSending ?? true,diff --git a/src/app/api/booking/[eventId]/route.ts b/src/app/api/booking/[eventId]/route.tsnew file mode 100644index 0000000..71843cf--- /dev/null+++ b/src/app/api/booking/[eventId]/route.ts@@ -0,0 +1,44 @@+import { and, eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { bookingEvents } from "@/db/schema";+import { getCurrentUser } from "@/lib/auth/cookies";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";+import { parseBookingEventInput } from "@/lib/booking/utils";+import { getEnv } from "@/lib/cloudflare";+import type { BookingEventRouteContext } from "./types";+import { validBookingHostIds } from "@/lib/booking/hosts";+import { getLicenseEntitlements } from "@/lib/licenses/service";++export async function PATCH(request: Request, { params }: BookingEventRouteContext) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });+ const input = parseBookingEventInput(await request.json().catch(() => null));+ if (!input) return NextResponse.json({ error: "Enter valid booking details and availability." }, { status: 400 });+ const { eventId } = await params;+ const db = getDb(env);+ const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canManageAccounts;+ const hostIds = await validBookingHostIds(db, user.id, input.hostIds, canManageHosts);+ if (!hostIds) return NextResponse.json({ error: "Choose users from the host list." }, { status: 400 });+ const [taken] = await db.select({ id: bookingEvents.id }).from(bookingEvents).where(and(eq(bookingEvents.userId, user.id), eq(bookingEvents.slug, input.slug))).limit(1);+ if (taken && taken.id !== eventId) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });+ try {+ const [event] = await db.update(bookingEvents).set({ ...input, hostIds: JSON.stringify(hostIds), weekdays: JSON.stringify(input.weekdays), timeRanges: JSON.stringify(input.timeRanges), updatedAt: new Date() }).where(and(eq(bookingEvents.id, eventId), eq(bookingEvents.userId, user.id))).returning();+ return event ? NextResponse.json({ event }) : NextResponse.json({ error: "Booking event not found" }, { status: 404 });+ } catch (error) {+ if (error instanceof Error && /UNIQUE constraint failed|booking_events_user_slug_idx/i.test(error.message)) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });+ throw error;+ }+}++export async function DELETE(request: Request, { params }: BookingEventRouteContext) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });+ const { eventId } = await params;+ const [event] = await getDb(env).delete(bookingEvents).where(and(eq(bookingEvents.id, eventId), eq(bookingEvents.userId, user.id))).returning();+ return event ? NextResponse.json({ ok: true }) : NextResponse.json({ error: "Booking event not found" }, { status: 404 });+}diff --git a/src/app/api/booking/[eventId]/types.d.ts b/src/app/api/booking/[eventId]/types.d.tsnew file mode 100644index 0000000..11ba808--- /dev/null+++ b/src/app/api/booking/[eventId]/types.d.ts@@ -0,0 +1 @@+export type BookingEventRouteContext = { params: Promise<{ eventId: string }> };diff --git a/src/app/api/booking/route.ts b/src/app/api/booking/route.tsnew file mode 100644index 0000000..a10f7f0--- /dev/null+++ b/src/app/api/booking/route.ts@@ -0,0 +1,46 @@+import { and, eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { bookingEvents, users } from "@/db/schema";+import { getCurrentUser } from "@/lib/auth/cookies";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";+import { parseBookingEventInput } from "@/lib/booking/utils";+import { getEnv } from "@/lib/cloudflare";+import { newId } from "@/lib/ids";+import { ensureBookingUsername } from "@/lib/booking/username";+import { validBookingHostIds } from "@/lib/booking/hosts";+import { getLicenseEntitlements } from "@/lib/licenses/service";++export async function GET(request: Request) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ const username = await ensureBookingUsername(env, user.id, user.email);+ const db = getDb(env);+ const events = await db.select().from(bookingEvents).where(eq(bookingEvents.userId, user.id)).orderBy(bookingEvents.createdAt);+ const [currentUser] = await db.select({ avatarKey: users.avatarKey }).from(users).where(eq(users.id, user.id)).limit(1);+ const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canManageAccounts;+ return NextResponse.json({ events, username, currentUser: { id: user.id, name: user.name, email: user.email, hasAvatar: !!currentUser?.avatarKey }, canManageHosts });+}++export async function POST(request: Request) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });+ const input = parseBookingEventInput(await request.json().catch(() => null));+ if (!input) return NextResponse.json({ error: "Enter valid booking details and availability." }, { status: 400 });+ const db = getDb(env);+ const canManageHosts = user.role === "admin" && (await getLicenseEntitlements(env)).canManageAccounts;+ const hostIds = await validBookingHostIds(db, user.id, input.hostIds, canManageHosts);+ if (!hostIds) return NextResponse.json({ error: "Choose users from the host list." }, { status: 400 });+ const [taken] = await db.select({ id: bookingEvents.id }).from(bookingEvents).where(and(eq(bookingEvents.userId, user.id), eq(bookingEvents.slug, input.slug))).limit(1);+ if (taken) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });+ try {+ const [event] = await db.insert(bookingEvents).values({ ...input, id: newId("book"), userId: user.id, hostIds: JSON.stringify(hostIds), weekdays: JSON.stringify(input.weekdays), timeRanges: JSON.stringify(input.timeRanges) }).returning();+ return NextResponse.json({ event });+ } catch (error) {+ if (error instanceof Error && /UNIQUE constraint failed|booking_events_user_slug_idx/i.test(error.message)) return NextResponse.json({ error: "This event link is already in use." }, { status: 409 });+ throw error;+ }+}diff --git a/src/app/api/booking/settings/route.ts b/src/app/api/booking/settings/route.tsnew file mode 100644index 0000000..acbdb46--- /dev/null+++ b/src/app/api/booking/settings/route.ts@@ -0,0 +1,30 @@+import { eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { users } from "@/db/schema";+import { getCurrentUser } from "@/lib/auth/cookies";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";+import { normalizeBookingUsername } from "@/lib/booking/utils";+import { getEnv } from "@/lib/cloudflare";+import type { BookingSettingsInput } from "./types";++export async function PATCH(request: Request) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ if (user.role !== "admin") return NextResponse.json({ error: "Only administrators can change booking usernames." }, { status: 403 });+ if (!hasValidSessionMutationOrigin(request)) return NextResponse.json({ error: "Invalid origin" }, { status: 403 });+ const body = await request.json().catch(() => null) as BookingSettingsInput | null;+ const username = normalizeBookingUsername(body?.username);+ if (!username) return NextResponse.json({ error: "Use up to 64 lowercase letters, numbers, dots, underscores, plus signs, or hyphens." }, { status: 400 });+ const db = getDb(env);+ const [taken] = await db.select({ id: users.id }).from(users).where(eq(users.bookingUsername, username)).limit(1);+ if (taken && taken.id !== user.id) return NextResponse.json({ error: "This username is already taken." }, { status: 409 });+ try {+ await db.update(users).set({ bookingUsername: username }).where(eq(users.id, user.id));+ return NextResponse.json({ username });+ } catch (error) {+ if (error instanceof Error && /UNIQUE constraint failed|users_booking_username_idx/i.test(error.message)) return NextResponse.json({ error: "This username is already taken." }, { status: 409 });+ throw error;+ }+}diff --git a/src/app/api/booking/settings/types.d.ts b/src/app/api/booking/settings/types.d.tsnew file mode 100644index 0000000..33bb05b--- /dev/null+++ b/src/app/api/booking/settings/types.d.ts@@ -0,0 +1 @@+export type BookingSettingsInput = { username?: unknown };diff --git a/src/app/api/calendar/events/[eventId]/route.ts b/src/app/api/calendar/events/[eventId]/route.tsindex cff2c94..93cd87a 100644--- a/src/app/api/calendar/events/[eventId]/route.ts+++ b/src/app/api/calendar/events/[eventId]/route.ts@@ -2,7 +2,6 @@ import { and, eq } from "drizzle-orm";import { NextResponse } from "next/server";import { getDb } from "@/db";import { calendarEvents } from "@/db/schema";-import { requireUser } from "@/lib/auth/cookies";import { getEnv } from "@/lib/cloudflare";import { createCalendarInvitation } from "@/lib/calendar/utils";import { sendEmail } from "@/lib/email/send";@@ -12,10 +11,12 @@ import { normalizeCalendarColor } from "@/lib/calendar/colors";import { DEFAULT_REPEAT_DAYS, normalizeCalendarRepeat, normalizeCalendarRepeatDays, parseCalendarOccurrenceId, parseCalendarRepeatDays, parseExcludedOccurrences } from "@/lib/calendar/recurrence";import { newId } from "@/lib/ids";import { getRequestTimeZone, normalizeTimeZone } from "@/lib/time/utils";+import { authorizeCalendarRequest, calendarKeyCanSendInvitations } from "@/lib/calendar/api-auth";export async function PATCH(request: Request, { params }: CalendarEventRouteParams) {const env = getEnv();- const user = await requireUser(env, request);+ const { user, key, error } = await authorizeCalendarRequest(env, request, "calendar:write");+ if (error) return error;const { eventId } = await params;const occurrence = parseCalendarOccurrenceId(eventId);const input = await request.json() as CalendarEventInput;@@ -31,6 +32,7 @@ export async function PATCH(request: Request, { params }: CalendarEventRouteParaif (occurrence && (existing.repeat === "none" || occurrence.startsAt < existing.startsAt || (existing.repeatUntil && occurrence.startsAt >= existing.repeatUntil))) return NextResponse.json({ error: "Occurrence not found" }, { status: 404 });if (existing.repeat !== "none" && effectiveFrom && existing.repeatUntil && effectiveFrom >= existing.repeatUntil) return NextResponse.json({ error: "No future occurrences remain" }, { status: 404 });const attendees = (input.attendees ?? []).map((email) => email.trim()).filter((email) => /^\S+@\S+\.\S+$/.test(email));+ if (attendees.length && existing.mailboxId && input.from && !calendarKeyCanSendInvitations(key, existing.mailboxId)) return NextResponse.json({ error: "Sending invitations requires mail send permission for this mailbox" }, { status: 403 });if (input.moveOccurrenceToPast) {if (!occurrence || existing.repeat === "none" || startsAt >= new Date()) return NextResponse.json({ error: "Choose a past time for this occurrence" }, { status: 400 });const excluded = parseExcludedOccurrences(existing.excludedOccurrences);@@ -59,12 +61,13 @@ export async function PATCH(request: Request, { params }: CalendarEventRouteParareturn NextResponse.json({ ok: true });}-export async function DELETE(_request: Request, { params }: CalendarEventRouteParams) {+export async function DELETE(request: Request, { params }: CalendarEventRouteParams) {const env = getEnv();- const user = await requireUser(env, _request);+ const { user, error } = await authorizeCalendarRequest(env, request, "calendar:write");+ if (error) return error;const { eventId } = await params;const occurrence = parseCalendarOccurrenceId(eventId);- const input = await _request.json().catch(() => ({})) as CalendarEventInput;+ const input = await request.json().catch(() => ({})) as CalendarEventInput;const effectiveFrom = input.effectiveFrom ? new Date(input.effectiveFrom) : occurrence?.startsAt;if (effectiveFrom && Number.isNaN(effectiveFrom.getTime())) return NextResponse.json({ error: "Invalid repeat start" }, { status: 400 });const db = getDb(env);diff --git a/src/app/api/calendar/events/route.ts b/src/app/api/calendar/events/route.tsindex a32ad1b..f435643 100644--- a/src/app/api/calendar/events/route.ts+++ b/src/app/api/calendar/events/route.ts@@ -2,7 +2,6 @@ import { and, eq, gte, lt, ne, or } from "drizzle-orm";import { NextResponse } from "next/server";import { getDb } from "@/db";import { calendarEvents } from "@/db/schema";-import { requireUser } from "@/lib/auth/cookies";import { getEnv } from "@/lib/cloudflare";import { newId } from "@/lib/ids";import { sendEmail } from "@/lib/email/send";@@ -11,10 +10,12 @@ import { normalizeCalendarColor } from "@/lib/calendar/colors";import { DEFAULT_REPEAT_DAYS, normalizeCalendarRepeat, normalizeCalendarRepeatDays } from "@/lib/calendar/recurrence";import type { CalendarEventInput } from "./types";import { getRequestTimeZone, normalizeTimeZone } from "@/lib/time/utils";+import { authorizeCalendarRequest, calendarKeyCanSendInvitations } from "@/lib/calendar/api-auth";export async function GET(request: Request) {const env = getEnv();- const user = await requireUser(env, request);+ const { user, error } = await authorizeCalendarRequest(env, request, "calendar:read");+ if (error) return error;const url = new URL(request.url);const start = new Date(url.searchParams.get("start") ?? Date.now());const end = new Date(url.searchParams.get("end") ?? start.getTime() + 31 * 86_400_000);@@ -24,7 +25,8 @@ export async function GET(request: Request) {export async function POST(request: Request) {const env = getEnv();- const user = await requireUser(env, request);+ const { user, key, error } = await authorizeCalendarRequest(env, request, "calendar:write");+ if (error) return error;const input = await request.json() as CalendarEventInput;const startsAt = new Date(input.startsAt);const endsAt = new Date(input.endsAt);@@ -33,6 +35,7 @@ export async function POST(request: Request) {const repeatDays = repeat === "weekdays" ? normalizeCalendarRepeatDays(input.repeatDays ?? DEFAULT_REPEAT_DAYS) : [];if (repeat === "weekdays" && repeatDays.length === 0) return NextResponse.json({ error: "Choose at least one weekday" }, { status: 400 });const attendees = (input.attendees ?? []).map((email) => email.trim()).filter((email) => /^\S+@\S+\.\S+$/.test(email));+ if (attendees.length && input.mailboxId && !calendarKeyCanSendInvitations(key, input.mailboxId)) return NextResponse.json({ error: "Sending invitations requires mail send permission for this mailbox" }, { status: 403 });const event = { id: newId("evt"), userId: user.id, mailboxId: input.mailboxId ?? null, title: input.title.trim(), description: input.description?.trim() ?? "", location: input.location?.trim() ?? "", attendees: JSON.stringify(attendees), color: normalizeCalendarColor(input.color), repeat, repeatDays: JSON.stringify(repeatDays), repeatAnchorDay: repeat === "monthly" && Number.isInteger(input.repeatAnchorDay) && input.repeatAnchorDay! >= 1 && input.repeatAnchorDay! <= 31 ? input.repeatAnchorDay : null, startsAt, endsAt };const savedEvent = { ...event, timeZone: input.timeZone ? normalizeTimeZone(input.timeZone) : getRequestTimeZone(request, user.timeZone) };await getDb(env).insert(calendarEvents).values(savedEvent);diff --git a/src/app/api/public/booking/[eventId]/route.ts b/src/app/api/public/booking/[eventId]/route.tsnew file mode 100644index 0000000..49b74cb--- /dev/null+++ b/src/app/api/public/booking/[eventId]/route.ts@@ -0,0 +1,32 @@+import { NextResponse } from "next/server";+import { availableBookingSlots } from "@/lib/booking/availability";+import { getEnv } from "@/lib/cloudflare";+import { createBookedCalendarEvents } from "@/lib/booking/create";+import type { PublicBookingRouteContext, PublicBookingSubmission } from "./types";+import { loadPublicBookingEvent, parseBookingGuestEmails } from "./utils";++export async function GET(request: Request, { params }: PublicBookingRouteContext) {+ const { eventId } = await params;+ const found = await loadPublicBookingEvent(eventId, new URL(request.url).searchParams.get("username"));+ if (!found) return NextResponse.json({ error: "Booking event not found" }, { status: 404 });+ const slots = await availableBookingSlots(getEnv(), found.event, 60);+ return NextResponse.json({ event: found.event, hostName: found.hostName, slots });+}++export async function POST(request: Request, { params }: PublicBookingRouteContext) {+ const { eventId } = await params;+ const found = await loadPublicBookingEvent(eventId, new URL(request.url).searchParams.get("username"));+ if (!found) return NextResponse.json({ error: "Booking event not found" }, { status: 404 });+ const body = await request.json().catch(() => null) as PublicBookingSubmission | null;+ const name = typeof body?.name === "string" ? body.name.trim() : "";+ const email = typeof body?.email === "string" ? body.email.trim().toLowerCase() : "";+ if (!name || name.length > 120 || !/^\S+@\S+\.\S+$/.test(email) || email.length > 254 || typeof body?.startsAt !== "string") return NextResponse.json({ error: "Enter your name, email, and a time." }, { status: 400 });+ const guestEmails = parseBookingGuestEmails(body?.guestEmails, email);+ const notes = typeof body?.notes === "string" ? body.notes.trim() : "";+ if (!guestEmails || notes.length > 2000 || (body?.notes !== undefined && typeof body.notes !== "string")) return NextResponse.json({ error: "Check the guest emails and meeting notes." }, { status: 400 });+ const slots = await availableBookingSlots(getEnv(), found.event, 60);+ const slot = slots.find((item) => item.startsAt === body.startsAt);+ if (!slot) return NextResponse.json({ error: "That time is no longer available." }, { status: 409 });+ if (!(await createBookedCalendarEvents(getEnv(), found.event, name, email, slot.startsAt, slot.endsAt, guestEmails, notes))) return NextResponse.json({ error: "That time is no longer available." }, { status: 409 });+ return NextResponse.json({ booked: true, startsAt: slot.startsAt, endsAt: slot.endsAt });+}diff --git a/src/app/api/public/booking/[eventId]/types.d.ts b/src/app/api/public/booking/[eventId]/types.d.tsnew file mode 100644index 0000000..5a805d6--- /dev/null+++ b/src/app/api/public/booking/[eventId]/types.d.ts@@ -0,0 +1,2 @@+export type PublicBookingRouteContext = { params: Promise<{ eventId: string }> };+export type PublicBookingSubmission = { startsAt?: unknown; name?: unknown; email?: unknown; guestEmails?: unknown; notes?: unknown };diff --git a/src/app/api/public/booking/[eventId]/utils.ts b/src/app/api/public/booking/[eventId]/utils.tsnew file mode 100644index 0000000..59ce94b--- /dev/null+++ b/src/app/api/public/booking/[eventId]/utils.ts@@ -0,0 +1,27 @@+import { and, eq, inArray } from "drizzle-orm";+import { getDb } from "@/db";+import { bookingEvents, users } from "@/db/schema";+import { parseBookingTimeRanges, parseBookingWeekdays } from "@/lib/booking/utils";+import type { BookingEventRecord } from "@/lib/booking/types";+import { getEnv } from "@/lib/cloudflare";+import { parseBookingHostIds } from "@/lib/booking/hosts";++export function parseBookingGuestEmails(value: unknown, bookerEmail: string): string[] | null {+ if (value === undefined || value === "") return [];+ if (typeof value !== "string" || value.length > 2000) return null;+ const emails = value.split(",").map((email) => email.trim().toLowerCase()).filter(Boolean);+ if (emails.length > 20 || emails.some((email) => email.length > 254 || !/^\S+@\S+\.\S+$/.test(email))) return null;+ return [...new Set(emails.filter((email) => email !== bookerEmail))];+}++export async function loadPublicBookingEvent(eventId: string, username?: string | null) {+ const db = getDb(getEnv());+ const [matchedUser] = username ? await db.select({ id: users.id }).from(users).where(and(eq(users.bookingUsername, username.toLowerCase()), eq(users.disabled, false))).limit(1) : [];+ if (username && !matchedUser) return null;+ const [event] = await db.select().from(bookingEvents).where(and(username ? eq(bookingEvents.slug, eventId) : eq(bookingEvents.id, eventId), username ? eq(bookingEvents.userId, matchedUser!.id) : undefined, eq(bookingEvents.enabled, true))).limit(1);+ if (!event) return null;+ const hostIds = parseBookingHostIds(event.hostIds, event.userId);+ const hosts = await db.select({ id: users.id, name: users.name }).from(users).where(and(inArray(users.id, hostIds), eq(users.disabled, false)));+ if (hosts.length !== hostIds.length) return null;+ return { event: { ...event, hostIds, weekdays: parseBookingWeekdays(event.weekdays), timeRanges: parseBookingTimeRanges(event.timeRanges, { startTime: event.startTime, endTime: event.endTime }) } as BookingEventRecord, hostName: hostIds.map((id) => hosts.find((host) => host.id === id)?.name).join(", ") };+}diff --git a/src/app/api/public/booking/route.ts b/src/app/api/public/booking/route.tsnew file mode 100644index 0000000..b775973--- /dev/null+++ b/src/app/api/public/booking/route.ts@@ -0,0 +1,17 @@+import { and, eq } from "drizzle-orm";+import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { bookingEvents, users } from "@/db/schema";+import { getEnv } from "@/lib/cloudflare";++export async function GET(request: Request) {+ const url = new URL(request.url);+ const username = url.searchParams.get("username");+ const userId = url.searchParams.get("userId");+ if (!username && !userId) return NextResponse.json({ error: "Missing booking page" }, { status: 400 });+ const db = getDb(getEnv());+ const [user] = await db.select({ id: users.id, name: users.name, username: users.bookingUsername }).from(users).where(and(username ? eq(users.bookingUsername, username.toLowerCase()) : eq(users.id, userId!), eq(users.disabled, false))).limit(1);+ if (!user) return NextResponse.json({ error: "Booking page not found" }, { status: 404 });+ const events = await db.select({ id: bookingEvents.id, slug: bookingEvents.slug, name: bookingEvents.name, description: bookingEvents.description, durationMinutes: bookingEvents.durationMinutes, location: bookingEvents.location, weekdays: bookingEvents.weekdays, timeZone: bookingEvents.timeZone }).from(bookingEvents).where(and(eq(bookingEvents.userId, user.id), eq(bookingEvents.enabled, true))).orderBy(bookingEvents.createdAt);+ return NextResponse.json({ name: user.name, username: user.username, events });+}diff --git a/src/app/api/v1/accounts/utils.ts b/src/app/api/v1/accounts/utils.tsindex 99db8c7..edb8eca 100644--- a/src/app/api/v1/accounts/utils.ts+++ b/src/app/api/v1/accounts/utils.ts@@ -9,6 +9,7 @@ import { newId } from "@/lib/ids";import { createUserAccountSchema } from "@/lib/validators";import { ensureEmailRoutingRuleToWorker } from "@/lib/cloudflare-api";import { ensureMailboxDomainRouting } from "@/lib/mailboxes/domain-addresses";+import { ensureBookingUsername } from "@/lib/booking/username";import { accountListItemFromUser, getDomainForAdmin, getExistingMailbox } from "@/app/api/accounts/utils";export async function GET(request: Request) {@@ -45,6 +46,7 @@ export async function POST(request: Request) {role: parsed.data.role,createdByUserId: auth.userId,}).returning();+ await ensureBookingUsername(env, userId, email);const mailboxId = newId("mbx");await db.insert(mailboxes).values({ id: mailboxId, userId, domainId: domain.id, localPart: username, displayName: username });await ensureMailboxDomainRouting(env, db, { id: mailboxId, domainId: domain.id, localPart: username, useAllDomains: true });diff --git a/src/app/book/[userId]/[eventId]/booking-detail-skeleton.tsx b/src/app/book/[userId]/[eventId]/booking-detail-skeleton.tsxnew file mode 100644index 0000000..1ebf51f--- /dev/null+++ b/src/app/book/[userId]/[eventId]/booking-detail-skeleton.tsx@@ -0,0 +1,21 @@+export function BookingDetailSkeleton() {+ return <div role="status" aria-label="Loading availability" className="grid overflow-hidden rounded-t-3xl bg-white shadow-xl shadow-neutral-200/50 motion-safe:animate-pulse lg:min-h-0 lg:flex-1 lg:grid-cols-[minmax(240px,.95fr)_minmax(380px,1.65fr)_minmax(240px,.95fr)]">+ <span className="sr-only">Loading availability…</span>+ <div className="space-y-6 border-b border-neutral-200 p-7 sm:p-9 lg:border-b-0 lg:border-r">+ <div className="h-6 w-2/3 rounded bg-neutral-200" />+ <div className="h-4 w-full rounded bg-neutral-100" />+ <div className="h-4 w-4/5 rounded bg-neutral-100" />+ <div className="mt-10 h-4 w-1/3 rounded bg-neutral-100" />+ </div>+ <div className="border-b border-neutral-200 p-7 sm:p-9 lg:border-b-0 lg:border-r">+ <div className="h-6 w-1/2 rounded bg-neutral-200" />+ <div className="mx-auto mt-10 grid max-w-[440px] grid-cols-7 gap-2">+ {Array.from({ length: 35 }, (_, index) => <div key={index} className="aspect-square rounded-lg bg-neutral-100" />)}+ </div>+ </div>+ <div className="space-y-3 p-7 sm:p-9">+ <div className="mb-6 h-6 w-3/4 rounded bg-neutral-200" />+ {[0, 1, 2, 3, 4].map((item) => <div key={item} className="h-11 rounded-md bg-neutral-100" />)}+ </div>+ </div>;+}diff --git a/src/app/book/[userId]/[eventId]/page.tsx b/src/app/book/[userId]/[eventId]/page.tsxnew file mode 100644index 0000000..74c23af--- /dev/null+++ b/src/app/book/[userId]/[eventId]/page.tsx@@ -0,0 +1,163 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import Link from "next/link";+import { useParams } from "next/navigation";+import { ArrowLeft, CalendarDays, Check, ChevronLeft, ChevronRight, Clock3, Globe2, MapPin, Users } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { useBranding } from "@/components/branding-provider";+import { RouteLoadingBar } from "@/components/route-loading-bar";+import { getUserTimeZone } from "@/lib/time/utils";+import type { BookingSlot, PublicBookingEvent } from "../types";+import { bookingTimeZones, calendarDays, formatCalendarDate, localDateForSlot, moveMonth, readBookingPageSelection, submitPublicBooking, writeBookingPageSelection } from "./utils";+import { BookingDetailSkeleton } from "./booking-detail-skeleton";++export default function PublicBookingEventPage() {+ const branding = useBranding();+ const params = useParams();+ const userId = typeof params.userId === "string" ? params.userId : undefined;+ const eventId = typeof params.eventId === "string" ? params.eventId : undefined;+ const username = typeof params.username === "string" ? params.username : undefined;+ const slug = typeof params.slug === "string" ? params.slug : undefined;+ const identifier = slug ?? eventId ?? "";+ const endpoint = `/api/public/booking/${encodeURIComponent(identifier)}${username ? `?username=${encodeURIComponent(username)}` : ""}`;+ const [event, setEvent] = useState<PublicBookingEvent | null>(null);+ const [hostName, setHostName] = useState("");+ const [slots, setSlots] = useState<BookingSlot[]>([]);+ const [timeZone, setTimeZone] = useState("UTC");+ const [month, setMonth] = useState("");+ const [selectedDate, setSelectedDate] = useState(() => new Date().toISOString().slice(0, 10));+ const [selectedSlot, setSelectedSlot] = useState<BookingSlot | null>(null);+ const [name, setName] = useState("");+ const [email, setEmail] = useState("");+ const [guestEmails, setGuestEmails] = useState("");+ const [showGuests, setShowGuests] = useState(false);+ const [notes, setNotes] = useState("");+ const [loading, setLoading] = useState(true);+ const [submitting, setSubmitting] = useState(false);+ const [done, setDone] = useState(false);+ const [error, setError] = useState("");+ const slotsByDate = useMemo(() => {+ const grouped = new Map<string, BookingSlot[]>();+ for (const slot of slots) {+ const date = localDateForSlot(slot, timeZone);+ grouped.set(date, [...(grouped.get(date) ?? []), slot]);+ }+ return grouped;+ }, [slots, timeZone]);+ const availableDates = [...slotsByDate.keys()].sort();+ const todayDate = localDateForSlot({ startsAt: new Date().toISOString(), endsAt: "", localDate: "", time: "" }, timeZone);+ const visibleMonth = month || localDateForSlot({ startsAt: new Date().toISOString(), endsAt: "", localDate: "", time: "" }, timeZone).slice(0, 7);+ const firstMonth = availableDates[0]?.slice(0, 7);+ const lastMonth = availableDates.at(-1)?.slice(0, 7);+ const timeZones = useMemo(() => event ? bookingTimeZones(event.timeZone, timeZone) : [], [event, timeZone]);++ useEffect(() => {+ function restoreSelection() {+ const selection = readBookingPageSelection(window.location.search);+ const zone = selection.timeZone ?? getUserTimeZone();+ const viewerToday = localDateForSlot({ startsAt: new Date().toISOString(), endsAt: "", localDate: "", time: "" }, zone);+ const slot = slots.find((item) => item.startsAt === selection.slotStartsAt) ?? null;+ const date = slot ? localDateForSlot(slot, zone) : selection.date ?? viewerToday;+ setTimeZone(zone);+ setSelectedDate(date);+ setSelectedSlot(slot);+ setMonth(date.slice(0, 7));+ if (!loading || !selection.slotStartsAt) {+ if (selection.date !== date || (new URLSearchParams(window.location.search).has("slot") && !slot) || !selection.timeZone) writeBookingPageSelection(date, slot?.startsAt ?? null, zone, true);+ }+ }+ restoreSelection();+ window.addEventListener("popstate", restoreSelection);+ return () => window.removeEventListener("popstate", restoreSelection);+ }, [slots, loading]);++ useEffect(() => {+ let active = true;+ void fetch(endpoint).then(async (response) => {+ if (!response.ok) throw new Error();+ return response.json() as Promise<{ event: PublicBookingEvent; hostName: string; slots: BookingSlot[] }>;+ }).then((data) => {+ if (!active) return;+ if (userId && data.event.userId !== userId) throw new Error();+ setEvent(data.event);+ setHostName(data.hostName);+ setSlots(data.slots);+ }).catch(() => { if (active) setError("This meeting is unavailable."); }).finally(() => { if (active) setLoading(false); });+ return () => { active = false; };+ }, [endpoint, userId]);++ async function book() {+ if (!selectedSlot) return;+ setSubmitting(true);+ setError("");+ try {+ await submitPublicBooking(endpoint, selectedSlot.startsAt, name, email, guestEmails, notes);+ setDone(true);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Could not book this time. Please try again.");+ } finally { setSubmitting(false); }+ }++ return <main className="page-transition-enter min-h-dvh bg-[#f6f8fc] p-4 text-neutral-900 sm:px-6 lg:h-dvh lg:overflow-hidden lg:pb-0">+ <div className="mx-auto max-w-[1500px] lg:flex lg:h-full lg:min-h-0 lg:flex-col">+ {loading && <RouteLoadingBar />}+ {selectedSlot && !done ? <button type="button" onClick={() => { setSelectedSlot(null); setError(""); writeBookingPageSelection(selectedDate, null, timeZone, true); }} className="mb-5 inline-flex items-center gap-2 self-start text-sm text-neutral-600 hover:text-blue-700"><ArrowLeft className="h-4 w-4" />Back to calendar</button> : <Link href={username ? `/c/${username}` : `/book/${userId}`} className="mb-5 inline-flex items-center gap-2 self-start text-sm text-neutral-600 hover:text-blue-700"><ArrowLeft className="h-4 w-4" />All meetings</Link>}+ {loading ? <BookingDetailSkeleton /> : !event ? <p className="rounded-2xl bg-white p-8 text-sm text-neutral-600 shadow-sm">{error}</p> :+ <div className={`page-transition-enter grid overflow-hidden rounded-t-3xl bg-white shadow-xl shadow-neutral-200/50 lg:min-h-0 lg:flex-1 ${selectedSlot || done ? "lg:grid-cols-[minmax(260px,1fr)_minmax(420px,2fr)]" : "lg:grid-cols-[minmax(240px,.95fr)_minmax(380px,1.65fr)_minmax(240px,.95fr)]"}`}>+ <aside className="min-w-0 border-b border-neutral-200 p-7 sm:p-9 lg:min-h-0 lg:overflow-y-auto lg:border-b-0 flex flex-col border-r">+ <h1 className="text-xl font-semibold tracking-tight">{event.name}</h1>++ {event.description && <p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-neutral-600">{event.description}</p>}++ <div className="mt-4 space-y-5 text-sm font-medium text-neutral-600 border-t border-neutral-100 pt-4">+ <p className="flex items-start gap-3"><Clock3 size={18} className="shrink-0 text-neutral-600" />{event.durationMinutes} min</p>+ {event.location && <p className="flex items-start gap-3"><MapPin size={18} className="shrink-0 text-neutral-600" />{event.location}</p>}+ {selectedSlot && <><p className="flex items-start gap-3"><CalendarDays size={18} className="shrink-0 text-neutral-600" /><span>{new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit", hourCycle: "h23", timeZone }).format(new Date(selectedSlot.startsAt))} – {new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit", hourCycle: "h23", timeZone }).format(new Date(selectedSlot.endsAt))}, {new Intl.DateTimeFormat(undefined, { weekday: "long", month: "long", day: "numeric", year: "numeric", timeZone }).format(new Date(selectedSlot.startsAt))}</span></p><p className="flex items-start gap-3"><Globe2 size={18} className="shrink-0 text-neutral-600" />{timeZone.replaceAll("_", " ")}</p></>}+ {hostName && <p className="flex items-start gap-3"><Users size={18} className="shrink-0 text-neutral-600" /><span>{hostName}</span></p>}++ </div>+++ <span className="flex-1" />+ <div className="flex min-w-0 items-center gap-3">++ <img src={branding.iconUrl} width={24} height={24} alt={branding.appName || "Mailflare"} />++ <span className="truncate font-semibold">{branding.appName}</span>+ </div>+ </aside>+ {done ? <section className="flex min-h-0 flex-col items-center justify-center px-8 py-20 text-center"><div className="mb-5 flex h-14 w-14 items-center justify-center rounded-full bg-green-100 text-green-700"><Check className="h-7 w-7" /></div><h2 className="text-2xl font-semibold">Meeting booked</h2><p className="mt-3 text-sm text-neutral-500">Your meeting is scheduled for {selectedSlot && new Intl.DateTimeFormat(undefined, { dateStyle: "full", timeStyle: "short", timeZone }).format(new Date(selectedSlot.startsAt))}.</p></section> : selectedSlot ?+ <form onSubmit={(formEvent) => { formEvent.preventDefault(); void book(); }} className="page-transition-enter min-h-0 space-y-6 overflow-y-auto p-7 sm:p-10">+ <h2 className="text-2xl font-medium">Enter Details</h2>+ <label className="block text-sm font-medium text-neutral-700">Name <span aria-hidden="true">*</span><Input required value={name} onChange={(input) => setName(input.target.value)} maxLength={120} autoComplete="name" className="mt-2" /></label>+ <label className="block text-sm font-medium text-neutral-700">Email <span aria-hidden="true">*</span><Input required type="email" value={email} onChange={(input) => setEmail(input.target.value)} maxLength={254} autoComplete="email" className="mt-2" /></label>+ {showGuests ? <label className="block text-sm font-medium text-neutral-700">Guest emails <span className="font-normal text-neutral-500">(comma separated)</span><Input type="text" value={guestEmails} onChange={(input) => setGuestEmails(input.target.value)} placeholder="[email protected]" className="mt-2" /></label> : <Button type="button" variant="outline" onClick={() => setShowGuests(true)} className="rounded-full text-blue-700">Add guests</Button>}+ <label className="block text-sm font-medium text-neutral-700">Please share anything that will help prepare for our meeting.<Textarea value={notes} onChange={(input) => setNotes(input.target.value)} maxLength={2000} rows={4} className="mt-2 resize-y" /></label>+ {error && <p role="alert" className="text-sm text-red-600">{error}</p>}+ <Button type="submit" disabled={submitting || !name.trim() || !email.trim()} className="h-11 rounded-full bg-blue-600 px-7 text-sm font-medium hover:bg-blue-700">{submitting ? "Booking…" : "Schedule Event"}</Button>+ </form> : <>+ <section className="page-transition-enter min-w-0 border-b border-neutral-200 lg:min-h-0 lg:overflow-y-auto">+ <div className="mx-auto mt-8 mb-2 flex max-w-[440px] items-center justify-between gap-3 px-5"><h3 className="text-lg font-semibold flex-1">{formatCalendarDate(`${visibleMonth}-01`, { month: "long", year: "numeric" })}</h3>+ <button type="button" aria-label="Previous month" disabled={!firstMonth || moveMonth(visibleMonth, -1) < firstMonth} onClick={() => setMonth(moveMonth(visibleMonth, -1))} className="flex h-9 w-9 items-center justify-center rounded-md border border-neutral-200 text-blue-600 hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-30"><ChevronLeft className="h-5 w-5" /></button>+ <button type="button" aria-label="Next month" disabled={!lastMonth || moveMonth(visibleMonth, 1) > lastMonth} onClick={() => setMonth(moveMonth(visibleMonth, 1))} className="flex h-9 w-9 items-center justify-center rounded-md border border-neutral-200 text-blue-600 hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-30"><ChevronRight className="h-5 w-5" /></button>+ </div>+ <div className="mx-auto mt-6 grid max-w-[440px] grid-cols-7 text-center text-sm text-neutral-400"><span>Mo</span><span>Tu</span><span>We</span><span>Th</span><span>Fr</span><span>Sa</span><span>Su</span></div>+ <div className="mx-auto mt-2 mb-6 grid max-w-[440px] grid-cols-7">{calendarDays(visibleMonth).map((date, index) => <div key={date || `blank-${index}`} className="aspect-square min-w-0">{date && <button type="button" disabled={!slotsByDate.has(date) && date !== todayDate} onClick={() => { setSelectedDate(date); setError(""); writeBookingPageSelection(date, null, timeZone); }} aria-label={`${formatCalendarDate(date, { weekday: "long", month: "long", day: "numeric", year: "numeric" })}${date === todayDate ? ", today" : ""}${slotsByDate.has(date) ? `, ${slotsByDate.get(date)?.length} available times` : ", no available times"}`} aria-current={date === todayDate ? "date" : undefined} aria-pressed={selectedDate === date} className={`flex h-full w-full items-center justify-center rounded-lg text-base ${selectedDate === date ? "bg-blue-600 text-white" : slotsByDate.has(date) || date === todayDate ? "text-blue-700 hover:bg-blue-50" : "cursor-not-allowed text-neutral-400"}`}><span className={`relative flex h-10 w-10 items-center justify-center rounded-full ${selectedDate === date ? "font-semibold" : slotsByDate.has(date) ? "bg-blue-50 font-medium" : ""} ${date === todayDate && selectedDate !== date ? "ring-2 ring-blue-300 ring-offset-2" : ""}`}>{Number(date.slice(-2))}{date === todayDate && selectedDate === date && <span aria-hidden="true" className="absolute bottom-1 h-1 w-1 rounded-full bg-white" />}</span></button>}</div>)}+ </div>++ <div className="flex min-w-0 items-center gap-2 w-full pl-3 pr-2 text-sm text-neutral-600 focus-within:border-blue-600 max-w-[440px] my-4 mx-auto">+ <Globe2 aria-hidden="true" className="h-4 w-4 shrink-0" />+ <label htmlFor="booking-time-zone" className="flex-1 min-w-0">Time zone</label>+ <select id="booking-time-zone" value={timeZone} onChange={(input) => { const nextToday = localDateForSlot({ startsAt: new Date().toISOString(), endsAt: "", localDate: "", time: "" }, input.target.value); setTimeZone(input.target.value); setSelectedDate(nextToday); setMonth(nextToday.slice(0, 7)); writeBookingPageSelection(nextToday, null, input.target.value); }} className="h-9 border-0 bg-transparent px-1 text-sm text-neutral-700 shadow-none outline-none text-right">{timeZones.map((zone) => <option key={zone} value={zone}>{zone.replaceAll("_", " ")}</option>)}</select>+ </div>+ {slots.length === 0 && <p className="mt-6 text-sm text-neutral-500">No times are available in the next 60 days.</p>}+ </section>+ {selectedDate && <section key={selectedDate} className="page-transition-enter flex min-h-0 flex-col p-7 sm:p-9 lg:overflow-hidden"><h3 className="mb-6 shrink-0 text-lg font-semibold">{formatCalendarDate(selectedDate, { weekday: "long", month: "short", day: "numeric" })}</h3><div className="min-h-0 max-h-[50dvh] flex-1 space-y-3 overflow-y-auto pr-1 lg:max-h-none">{(slotsByDate.get(selectedDate) ?? []).length === 0 ? <p className="text-sm text-neutral-500">No times are available on this date. Choose another highlighted date.</p> : (slotsByDate.get(selectedDate) ?? []).map((slot) => <button type="button" key={slot.startsAt} onClick={() => { setSelectedSlot(slot); setError(""); writeBookingPageSelection(selectedDate, slot.startsAt, timeZone); }} className="w-full rounded-md border border-neutral-300 bg-white px-4 py-3 text-center text-sm font-medium text-blue-700 hover:border-blue-500 hover:bg-blue-50">{new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit", hour12: true, timeZone }).format(new Date(slot.startsAt))}</button>)}</div></section>}+ </>}+ </div>}+ </div>+ </main>;+}diff --git a/src/app/book/[userId]/[eventId]/types.d.ts b/src/app/book/[userId]/[eventId]/types.d.tsnew file mode 100644index 0000000..7bfbb5e--- /dev/null+++ b/src/app/book/[userId]/[eventId]/types.d.ts@@ -0,0 +1,5 @@+export type BookingPageSelection = {+ date: string | null;+ slotStartsAt: string | null;+ timeZone: string | null;+};diff --git a/src/app/book/[userId]/[eventId]/utils.ts b/src/app/book/[userId]/[eventId]/utils.tsnew file mode 100644index 0000000..24a2c80--- /dev/null+++ b/src/app/book/[userId]/[eventId]/utils.ts@@ -0,0 +1,61 @@+import type { BookingSlot } from "../types";+import { isValidTimeZone } from "@/lib/time/utils";+import type { BookingPageSelection } from "./types";++export function readBookingPageSelection(search: string): BookingPageSelection {+ const params = new URLSearchParams(search);+ const rawDate = params.get("date");+ const parsedDate = rawDate ? new Date(`${rawDate}T12:00:00Z`) : null;+ const date = rawDate && /^\d{4}-\d{2}-\d{2}$/.test(rawDate) && parsedDate && !Number.isNaN(parsedDate.getTime()) && parsedDate.toISOString().slice(0, 10) === rawDate ? rawDate : null;+ const rawSlot = params.get("slot");+ const parsedSlot = rawSlot ? new Date(rawSlot) : null;+ const slotStartsAt = parsedSlot && !Number.isNaN(parsedSlot.getTime()) ? parsedSlot.toISOString() : null;+ const rawTimeZone = params.get("timeZone");+ return { date, slotStartsAt, timeZone: rawTimeZone && isValidTimeZone(rawTimeZone) ? rawTimeZone : null };+}++export function writeBookingPageSelection(date: string, slotStartsAt: string | null, timeZone: string, replace = false): void {+ const url = new URL(window.location.href);+ url.searchParams.set("date", date);+ url.searchParams.set("timeZone", timeZone);+ if (slotStartsAt) url.searchParams.set("slot", slotStartsAt);+ else url.searchParams.delete("slot");+ const nextUrl = `${url.pathname}${url.search}${url.hash}`;+ if (replace) window.history.replaceState(window.history.state, "", nextUrl);+ else window.history.pushState(window.history.state, "", nextUrl);+}++export function localDateForSlot(slot: BookingSlot, timeZone: string): string {+ const parts = new Intl.DateTimeFormat("en-US", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(new Date(slot.startsAt));+ const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));+ return `${values.year}-${values.month}-${values.day}`;+}++export function calendarDays(month: string): string[] {+ const [year, monthNumber] = month.split("-").map(Number);+ const first = new Date(Date.UTC(year, monthNumber - 1, 1));+ const count = new Date(Date.UTC(year, monthNumber, 0)).getUTCDate();+ const blanks = (first.getUTCDay() + 6) % 7;+ const trailing = (7 - (blanks + count) % 7) % 7;+ return [...Array(blanks).fill(""), ...Array.from({ length: count }, (_, index) => `${month}-${String(index + 1).padStart(2, "0")}`), ...Array(trailing).fill("")];+}++export function moveMonth(month: string, offset: number): string {+ const [year, monthNumber] = month.split("-").map(Number);+ return new Date(Date.UTC(year, monthNumber - 1 + offset, 1)).toISOString().slice(0, 7);+}++export function formatCalendarDate(date: string, options: Intl.DateTimeFormatOptions): string {+ return new Intl.DateTimeFormat(undefined, { ...options, timeZone: "UTC" }).format(new Date(`${date}T12:00:00Z`));+}++export function bookingTimeZones(eventTimeZone: string, selectedTimeZone: string): string[] {+ const supported = typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : [];+ return [...new Set([selectedTimeZone, eventTimeZone, "UTC", ...supported])].sort((a, b) => a.localeCompare(b));+}++export async function submitPublicBooking(endpoint: string, startsAt: string, name: string, email: string, guestEmails: string, notes: string): Promise<void> {+ const response = await fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ startsAt, name, email, guestEmails, notes }) });+ const data = await response.json() as { error?: string };+ if (!response.ok) throw new Error(data.error ?? "Could not book this time.");+}diff --git a/src/app/book/[userId]/booking-list-skeleton.tsx b/src/app/book/[userId]/booking-list-skeleton.tsxnew file mode 100644index 0000000..cdba172--- /dev/null+++ b/src/app/book/[userId]/booking-list-skeleton.tsx@@ -0,0 +1,10 @@+export function BookingListSkeleton() {+ return <div role="status" aria-label="Loading meetings" className="space-y-3">+ <span className="sr-only">Loading meetings…</span>+ {[0, 1, 2].map((item) => <div key={item} className="rounded-2xl bg-white p-5 motion-safe:animate-pulse">+ <div className="h-5 w-2/3 rounded bg-neutral-200" />+ <div className="mt-4 h-3 w-5/6 rounded bg-neutral-100" />+ <div className="mt-3 h-3 w-1/3 rounded bg-neutral-100" />+ </div>)}+ </div>;+}diff --git a/src/app/book/[userId]/page.tsx b/src/app/book/[userId]/page.tsxnew file mode 100644index 0000000..3e5fb59--- /dev/null+++ b/src/app/book/[userId]/page.tsx@@ -0,0 +1,41 @@+"use client";++import { useEffect, useState } from "react";+import Link from "next/link";+import { useParams } from "next/navigation";+import { ArrowRight, Clock3, MapPin } from "lucide-react";+import { useBranding } from "@/components/branding-provider";+import { RouteLoadingBar } from "@/components/route-loading-bar";+import type { PublicBookingEvent } from "./types";+import { BookingListSkeleton } from "./booking-list-skeleton";++export default function PublicBookingListPage() {+ const branding = useBranding();+ const params = useParams();+ const userId = typeof params.userId === "string" ? params.userId : undefined;+ const username = typeof params.username === "string" ? params.username : undefined;+ const query = username ? `username=${encodeURIComponent(username)}` : `userId=${encodeURIComponent(userId ?? "")}`;+ const [name, setName] = useState("");+ const [events, setEvents] = useState<PublicBookingEvent[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState("");+ useEffect(() => {+ let active = true;+ void fetch(`/api/public/booking?${query}`).then(async (response) => {+ if (!response.ok) throw new Error();+ return response.json() as Promise<{ name: string; events: PublicBookingEvent[] }>;+ }).then((data) => { if (active) { setName(data.name); setEvents(data.events); } }).catch(() => { if (active) setError("This booking page is unavailable."); }).finally(() => { if (active) setLoading(false); });+ return () => { active = false; };+ }, [query]);+ return <main className="page-transition-enter flex min-h-dvh flex-col bg-[#f6f8fc] p-4 lg:pt-12 text-neutral-900">+ {loading && <RouteLoadingBar />}+ <div className="mx-auto flex w-full max-w-2xl flex-1 flex-col">+ <div className="mb-7"><h1 className="text-3xl font-semibold">Book a meeting{name ? ` with ${name}` : ""}</h1><p className="mt-2 text-sm text-neutral-500">Choose a meeting to see available times.</p></div>+ {loading ? <BookingListSkeleton /> : error ? <p className="rounded-2xl border border-neutral-200 bg-white p-6 text-sm text-neutral-600 shadow-sm">{error}</p> : events.length === 0 ? <p className="rounded-2xl border border-neutral-200 bg-white p-6 text-sm text-neutral-600">No meetings are available to book right now.</p> : <div className="page-transition-enter space-y-3">{events.map((event) => <Link key={event.id} href={username ? `/c/${username}/${event.slug}` : `/book/${userId}/${event.id}`} className="group flex items-center gap-4 rounded-2xl bg-white p-5 transition-colors"><div className="min-w-0 flex-1"><h2 className="font-semibold group-hover:text-blue-700">{event.name}</h2>{event.description && <p className="mt-1 line-clamp-2 whitespace-pre-wrap text-sm text-neutral-600">{event.description}</p>}<p className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm text-neutral-500"><span className="inline-flex items-center gap-1"><Clock3 className="h-4 w-4" />{event.durationMinutes} minutes</span>{event.location && <span className="inline-flex items-center gap-1"><MapPin className="h-4 w-4" />{event.location}</span>}</p></div><ArrowRight className="h-5 w-5 text-neutral-400 group-hover:text-blue-700" /></Link>)}</div>}+ <div className="mt-auto flex min-w-0 items-center gap-3 pt-10 text-neutral-700">+ <img src={branding.iconUrl} width={24} height={24} alt={branding.appName || "Mailflare"} />+ <span className="truncate font-semibold">{branding.appName}</span>+ </div>+ </div>+ </main>;+}diff --git a/src/app/book/[userId]/types.d.ts b/src/app/book/[userId]/types.d.tsnew file mode 100644index 0000000..5c4dd33--- /dev/null+++ b/src/app/book/[userId]/types.d.ts@@ -0,0 +1,15 @@+export type PublicBookingEvent = {+ id: string;+ slug: string;+ userId: string;+ name: string;+ description: string;+ durationMinutes: number;+ location: string;+ weekdays: number[] | string;+ startTime?: string;+ endTime?: string;+ timeZone: string;+};++export type BookingSlot = { startsAt: string; endsAt: string; localDate: string; time: string };diff --git a/src/app/c/[username]/[slug]/page.tsx b/src/app/c/[username]/[slug]/page.tsxnew file mode 100644index 0000000..bd7bd63--- /dev/null+++ b/src/app/c/[username]/[slug]/page.tsx@@ -0,0 +1 @@+export { default } from "@/app/book/[userId]/[eventId]/page";diff --git a/src/app/c/[username]/page.tsx b/src/app/c/[username]/page.tsxnew file mode 100644index 0000000..ce8a6c0--- /dev/null+++ b/src/app/c/[username]/page.tsx@@ -0,0 +1 @@+export { default } from "@/app/book/[userId]/page";diff --git a/src/app/globals.css b/src/app/globals.cssindex 9684b8c..13156c1 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -89,6 +89,15 @@ pre {100% { transform: translateX(280%) scaleX(0.55); }}+@keyframes page-transition-enter {+ from { opacity: 0; transform: translateY(8px); }+ to { opacity: 1; transform: translateY(0); }+}++.page-transition-enter {+ animation: page-transition-enter 260ms ease-out both;+}+.route-loading-bar {transform-origin: left;animation: route-loading-bar 1.1s ease-in-out infinite;@@ -104,6 +113,10 @@ pre {width: 100%;animation: none;}++ .page-transition-enter {+ animation: none;+ }}/* Rendered email bodies (reader, conversation cards, composer). Tailwind'sdiff --git a/src/components/settings/api-keys-settings-utils.ts b/src/components/settings/api-keys-settings-utils.tsindex 8cd7098..0569e07 100644--- a/src/components/settings/api-keys-settings-utils.ts+++ b/src/components/settings/api-keys-settings-utils.ts@@ -14,6 +14,8 @@ export const MCP_KEY_SCOPES: { value: McpKeyScope; label: string; description: sexport const STANDARD_KEY_SCOPES: { value: ApiKeyScope; label: string; description: string }[] = [{ value: "read", label: "Read mail", description: "Read messages through the API." },{ value: "send", label: "Send mail", description: "Send messages directly through the API." },+ { value: "calendar:read", label: "Read calendar", description: "Read your calendar events through the API." },+ { value: "calendar:write", label: "Manage calendar", description: "Create, update, and delete your calendar events through the API." },];async function responseData(response: Response): Promise<{ error?: unknown; key?: string; apiKeys?: ManagedApiKey[] }> {diff --git a/src/components/settings/api-keys-settings.tsx b/src/components/settings/api-keys-settings.tsxindex 6c9b5dd..2b8b2f7 100644--- a/src/components/settings/api-keys-settings.tsx+++ b/src/components/settings/api-keys-settings.tsx@@ -83,7 +83,7 @@ export function ApiKeysSettings() {<label className={`flex items-start gap-3 text-sm ${mcpAllowed ? "opacity-50" : ""}`}><Checkbox checked={!mcpAllowed && standardScopes.includes("jmap")} disabled={mcpAllowed} onChange={(event) => setStandardScopes((current) => event.target.checked ? [...current, "jmap"] : current.filter((scope) => scope !== "jmap"))} /><span><strong>Allow JMAP access</strong><span className="mt-1 block text-neutral-500">{mcpAllowed ? "JMAP access requires a separate standard API key." : "Read and send mail from a JMAP client."}</span></span></label><fieldset className="space-y-2"><legend className="text-sm font-medium">Permissions</legend>{(mcpAllowed ? MCP_KEY_SCOPES : STANDARD_KEY_SCOPES).map((scope) => <label key={scope.value} className="flex items-start gap-3 py-2 text-sm"><Checkbox checked={mcpAllowed ? mcpScopes.includes(scope.value as McpKeyScope) : standardScopes.includes(scope.value as ApiKeyScope)} onChange={(event) => { if (mcpAllowed) setMcpScopes((current) => event.target.checked ? [...current, scope.value as McpKeyScope] : current.filter((item) => item !== scope.value)); else setStandardScopes((current) => event.target.checked ? [...current, scope.value as ApiKeyScope] : current.filter((item) => item !== scope.value)); }} /><span><strong>{scope.label}</strong><span className="block text-neutral-500">{scope.description}</span></span></label>)}</fieldset><fieldset className="space-y-2"><legend className="text-sm font-medium">Allowed mailboxes</legend>{mailboxes.length === 0 ? <p className="text-sm text-neutral-500">No accessible mailboxes.</p> : mailboxes.map((mailbox) => <label key={mailbox.id} className="flex items-center gap-3 text-sm"><Checkbox checked={mailboxIds.includes(mailbox.id)} onChange={(event) => setMailboxIds((current) => event.target.checked ? [...current, mailbox.id] : current.filter((id) => id !== mailbox.id))} />{mailbox.localPart}@{mailbox.hostname}</label>)}<p className="text-xs text-neutral-500">Aliases share their parent mailbox and are included with it.</p></fieldset>- <Button type="submit" disabled={busy || !name.trim() || (!mailboxIds.length && (!mcpAllowed || mcpScopes.some((scope) => !scope.startsWith("mcp:calendar-")))) || (mcpAllowed ? !mcpScopes.length : !standardScopes.length)}><KeyRound className="h-4 w-4" />{busy ? "Creating…" : "Create API key"}</Button>+ <Button type="submit" disabled={busy || !name.trim() || (!mailboxIds.length && (mcpAllowed ? mcpScopes.some((scope) => !scope.startsWith("mcp:calendar-")) : standardScopes.some((scope) => !scope.startsWith("calendar:")))) || (mcpAllowed ? !mcpScopes.length : !standardScopes.length)}><KeyRound className="h-4 w-4" />{busy ? "Creating…" : "Create API key"}</Button></form>}{newKey && <div className="space-y-3 rounded-xl border border-blue-200 bg-blue-50 p-4"><code className="block break-all rounded bg-white p-2 text-xs">{newKey}</code>{createdMcpAllowed && <McpAgentInstructions mode="mail" apiKey={newKey} />}<div className="flex gap-2"><Button type="button" size="sm" variant="outline" onClick={() => void navigator.clipboard.writeText(newKey).then(() => setCopied(true))}><Copy className="h-4 w-4" />{copied ? "Copied" : "Copy key"}</Button><Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => { setCreateOpen(false); setNewKey(null); setCopied(false); }}>Done</Button></div></div>}{error && <p role="alert" className="mt-4 text-sm text-red-600">{error}</p>}diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex 9178c41..7ab19d3 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -9,6 +9,7 @@ export const users = sqliteTable("users", {forwardingEmail: text("forwarding_email"),passwordHash: text("password_hash").notNull(),name: text("name").notNull(),+ bookingUsername: text("booking_username"),timeZone: text("time_zone"),avatarKey: text("avatar_key"),role: text("role", { enum: ["admin", "user"] }).notNull().default("user"),@@ -25,7 +26,7 @@ export const users = sqliteTable("users", {createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),-});+}, (t) => [uniqueIndex("users_booking_username_idx").on(t.bookingUsername)]);export const domains = sqliteTable("domains",@@ -396,6 +397,30 @@ export const calendarEvents = sqliteTable((t) => [index("calendar_events_user_starts_idx").on(t.userId, t.startsAt)],);+export const bookingEvents = sqliteTable(+ "booking_events",+ {+ id: text("id").primaryKey(),+ userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),+ name: text("name").notNull(),+ slug: text("slug").notNull().default(""),+ description: text("description").notNull().default(""),+ color: text("color").notNull().default("#2563eb"),+ hostIds: text("host_ids").notNull().default("[]"),+ durationMinutes: integer("duration_minutes").notNull(),+ location: text("location").notNull().default(""),+ weekdays: text("weekdays").notNull().default("[1,2,3,4,5]"),+ startTime: text("start_time").notNull().default("09:00"),+ endTime: text("end_time").notNull().default("17:00"),+ timeRanges: text("time_ranges").notNull().default('[{"startTime":"09:00","endTime":"17:00"}]'),+ timeZone: text("time_zone").notNull().default("UTC"),+ enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),+ createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),+ },+ (t) => [index("booking_events_user_idx").on(t.userId), uniqueIndex("booking_events_user_slug_idx").on(t.userId, t.slug)],+);+export const routingRules = sqliteTable("routing_rules",{@@ -753,6 +778,7 @@ export const schema = {outboundJobs,emailTemplates,calendarEvents,+ bookingEvents,routingRules,webhooks,webhookDeliveries,diff --git a/src/lib/api/scopes.ts b/src/lib/api/scopes.tsindex 015508a..b712823 100644--- a/src/lib/api/scopes.ts+++ b/src/lib/api/scopes.ts@@ -3,7 +3,7 @@* dashboard's key-creation form can import it without pulling in bcrypt.* Administrative scopes are issued separately from personal mail keys.*/-export const API_KEY_SCOPES = ["send", "read", "jmap"] as const;+export const API_KEY_SCOPES = ["send", "read", "jmap", "calendar:read", "calendar:write"] as const;export type ApiKeyScope = (typeof API_KEY_SCOPES)[number];diff --git a/src/lib/backups/export.ts b/src/lib/backups/export.tsindex 9e832fa..23ce2fd 100644--- a/src/lib/backups/export.ts+++ b/src/lib/backups/export.ts@@ -2,7 +2,7 @@ import type { BackupTableGroupId, DatabaseBackupDocument, DatabaseBackupTable, Dimport { mergeLegacyMessageBodies } from "./utils";import { BACKUP_TABLE_GROUPS, getSelectedBackupTables } from "./table-groups";-const BACKUP_TABLES: DatabaseBackupTable[] = ["users", "domains", "mailboxes", "mailbox_access", "contacts", "folders", "api_keys", "messages", "message_attachments", "shared_attachment_links", "outbound_jobs", "routing_rules", "webhooks", "webhook_deliveries", "sessions", "audit_logs", "backup_settings", "backups", "app_settings", "license_settings", "email_templates", "calendar_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback", "mailbox_aliases", "password_reset_tokens", "mfa_recovery_codes", "login_challenges", "mailbox_agent_settings", "agent_conversations", "agent_chat_messages", "agent_jobs", "agent_draft_metadata", "agent_send_approvals", "mcp_key_mailboxes", 'ai_usage'];+const BACKUP_TABLES: DatabaseBackupTable[] = ["users", "domains", "mailboxes", "mailbox_access", "contacts", "folders", "api_keys", "messages", "message_attachments", "shared_attachment_links", "outbound_jobs", "routing_rules", "webhooks", "webhook_deliveries", "sessions", "audit_logs", "backup_settings", "backups", "app_settings", "license_settings", "email_templates", "calendar_events", "booking_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback", "mailbox_aliases", "password_reset_tokens", "mfa_recovery_codes", "login_challenges", "mailbox_agent_settings", "agent_conversations", "agent_chat_messages", "agent_jobs", "agent_draft_metadata", "agent_send_approvals", "mcp_key_mailboxes", 'ai_usage'];/*** Tables every backup document must contain. Tables added to BACKUP_TABLES* after the format shipped are absent from older documents, so they stay@@ -62,7 +62,7 @@ export async function exportDatabaseRecords(db: D1Database, excludedGroups: Backif (!includedTables.length) throw new Error("Select at least one backup table group");const tables: DatabaseBackupDocument["tables"] = {};for (const table of includedTables) {- if (table === "shared_attachment_links" && !databaseTables.has(table)) {+ if ((table === "shared_attachment_links" || table === "booking_events") && !databaseTables.has(table)) {tables[table] = [];continue;}@@ -81,12 +81,17 @@ export async function restoreDatabaseRecords(db: D1Database, content: ArrayBuffevalidateDatabaseBackup(document);const sharedLinksTable = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'shared_attachment_links'").first<{ name: string }>();if (!sharedLinksTable && document.tables.shared_attachment_links?.length) throw new Error("Apply pending database migrations before restoring shared attachment links.");- const restoreTables = sharedLinksTable ? BACKUP_TABLES : BACKUP_TABLES.filter((table) => table !== "shared_attachment_links");+ const bookingTable = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'booking_events'").first<{ name: string }>();+ if (!bookingTable && document.tables.booking_events?.length) throw new Error("Apply pending database migrations before restoring booking events.");+ const restoreTables = BACKUP_TABLES.filter((table) => (table !== "shared_attachment_links" || sharedLinksTable) && (table !== "booking_events" || bookingTable));+ const userColumns = new Set((await db.prepare("PRAGMA table_info(users)").all<{ name: string }>()).results.map((column) => column.name));+ const bookingColumns = bookingTable ? new Set((await db.prepare("PRAGMA table_info(booking_events)").all<{ name: string }>()).results.map((column) => column.name)) : null;for (const table of [...restoreTables].reverse()) await db.prepare(`DELETE FROM ${table}`).run();for (const table of restoreTables) {const rows = document.tables[table] ?? [];for (let index = 0; index < rows.length; index += INSERT_BATCH_SIZE) {- const statements = rows.slice(index, index + INSERT_BATCH_SIZE).map((row) => createInsertStatement(db, table, row));+ const columns = table === "users" ? userColumns : table === "booking_events" ? bookingColumns : null;+ const statements = rows.slice(index, index + INSERT_BATCH_SIZE).map((row) => createInsertStatement(db, table, row, columns));if (statements.length > 0) await db.batch(statements);}}@@ -113,8 +118,8 @@ function isDatabaseBackupDocument(value: unknown): value is DatabaseBackupDocume});}-function createInsertStatement(db: D1Database, table: DatabaseBackupTable, row: DatabaseRecord) {- const columns = Object.keys(row);+function createInsertStatement(db: D1Database, table: DatabaseBackupTable, row: DatabaseRecord, availableColumns: Set<string> | null = null) {+ const columns = Object.keys(row).filter((column) => !availableColumns || availableColumns.has(column));if (columns.length === 0) throw new Error(`Backup contains an invalid ${table} record`);const placeholders = columns.map(() => "?").join(", ");const identifiers = columns.map((column) => `\`${column.replaceAll("`", "``")}\``).join(", ");@@ -126,6 +131,9 @@ function fillMissingBackupTables(document: DatabaseBackupDocument): void {for (const table of BACKUP_TABLES) {if (!document.tables[table]) document.tables[table] = [];}+ for (const row of document.tables.booking_events ?? []) {+ if (row.slug === undefined && typeof row.id === "string") row.slug = Array.from(new TextEncoder().encode(row.id)).map((byte) => byte.toString(16).padStart(2, "0")).join("");+ }}function validateDatabaseBackup(document: DatabaseBackupDocument): void {diff --git a/src/lib/backups/table-groups.ts b/src/lib/backups/table-groups.tsindex cce8a1f..44eaf2a 100644--- a/src/lib/backups/table-groups.ts+++ b/src/lib/backups/table-groups.ts@@ -2,7 +2,7 @@ import type { BackupTableGroupId, DatabaseBackupTable } from "./types";export const BACKUP_TABLE_GROUPS: { id: BackupTableGroupId; label: string; tables: DatabaseBackupTable[] }[] = [{ id: "accounts", label: "Accounts and mailboxes", tables: ["users", "domains", "mailboxes", "mailbox_access", "mailbox_aliases", "contacts", "api_keys", "mcp_key_mailboxes", "sessions", "password_reset_tokens", "mfa_recovery_codes", "login_challenges"] },- { id: "mail", label: "Mail and related data", tables: ["folders", "messages", "message_attachments", "shared_attachment_links", "outbound_jobs", "email_templates", "calendar_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback"] },+ { id: "mail", label: "Mail and related data", tables: ["folders", "messages", "message_attachments", "shared_attachment_links", "outbound_jobs", "email_templates", "calendar_events", "booking_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback"] },{ id: "automation", label: "Routing and webhooks", tables: ["routing_rules", "webhooks", "webhook_deliveries"] },{ id: "assistant", label: "Assistant and AI usage", tables: ["mailbox_agent_settings", "agent_conversations", "agent_chat_messages", "agent_jobs", "agent_draft_metadata", "agent_send_approvals", "ai_usage"] },{ id: "system", label: "App settings and history", tables: ["audit_logs", "backup_settings", "backups", "app_settings", "license_settings"] },diff --git a/src/lib/backups/types.d.ts b/src/lib/backups/types.d.tsindex 4d20d1e..b0a56e3 100644--- a/src/lib/backups/types.d.ts+++ b/src/lib/backups/types.d.ts@@ -1,6 +1,6 @@export type BackupScheduleType = "daily" | "weekly" | "monthly";export type BackupTableGroupId = "accounts" | "mail" | "automation" | "assistant" | "system";-export type DatabaseBackupTable = "users" | "domains" | "mailboxes" | "mailbox_access" | "contacts" | "folders" | "api_keys" | "messages" | "message_attachments" | "shared_attachment_links" | "outbound_jobs" | "routing_rules" | "webhooks" | "webhook_deliveries" | "sessions" | "audit_logs" | "backup_settings" | "backups" | "app_settings" | "license_settings" | "email_templates" | "calendar_events" | "auto_reply_deliveries" | "spam_token_stats" | "spam_reputation" | "spam_feedback" | "mailbox_aliases" | "password_reset_tokens" | "mfa_recovery_codes" | "login_challenges" | "mailbox_agent_settings" | "agent_conversations" | "agent_chat_messages" | "agent_jobs" | "agent_draft_metadata" | "agent_send_approvals" | "mcp_key_mailboxes" | 'ai_usage';+export type DatabaseBackupTable = "users" | "domains" | "mailboxes" | "mailbox_access" | "contacts" | "folders" | "api_keys" | "messages" | "message_attachments" | "shared_attachment_links" | "outbound_jobs" | "routing_rules" | "webhooks" | "webhook_deliveries" | "sessions" | "audit_logs" | "backup_settings" | "backups" | "app_settings" | "license_settings" | "email_templates" | "calendar_events" | "booking_events" | "auto_reply_deliveries" | "spam_token_stats" | "spam_reputation" | "spam_feedback" | "mailbox_aliases" | "password_reset_tokens" | "mfa_recovery_codes" | "login_challenges" | "mailbox_agent_settings" | "agent_conversations" | "agent_chat_messages" | "agent_jobs" | "agent_draft_metadata" | "agent_send_approvals" | "mcp_key_mailboxes" | 'ai_usage';export type DatabaseRecord = Record<string, string | number | null>;export type DatabaseBackupDocument = { format: "mailflare-database-backup"; version: 1; createdAt: string; includedTables?: DatabaseBackupTable[]; tables: Partial<Record<DatabaseBackupTable, DatabaseRecord[]>>; };diff --git a/src/lib/booking/availability.ts b/src/lib/booking/availability.tsnew file mode 100644index 0000000..75f39f5--- /dev/null+++ b/src/lib/booking/availability.ts@@ -0,0 +1,54 @@+import { and, inArray, lt, or, gt, ne } from "drizzle-orm";+import { getDb } from "@/db";+import { calendarEvents } from "@/db/schema";+import { dateFromZonedFields, zonedDateFields } from "@/lib/time/utils";+import { parseCalendarRepeatDays, parseExcludedOccurrences } from "@/lib/calendar/recurrence";+import { slotFromLocalDate, timeToMinutes } from "./utils";+import type { BookingEventRecord, ExistingCalendarEvent } from "./types";++function repeatsDuring(event: ExistingCalendarEvent, start: Date, end: Date): boolean {+ const first = event.startsAt;+ const duration = event.endsAt.getTime() - first.getTime();+ if (event.repeat === "none") return first < end && event.endsAt > start;+ const zone = event.timeZone || "UTC";+ const firstWall = zonedDateFields(first, zone);+ const candidate = zonedDateFields(new Date(start.getTime() - duration), zone);+ const excluded = new Set(parseExcludedOccurrences(event.excludedOccurrences));+ for (let offset = 0; offset < Math.ceil(duration / 86_400_000) + 2; offset++) {+ const day = new Date(candidate);+ day.setUTCDate(day.getUTCDate() + offset);+ day.setUTCHours(firstWall.getUTCHours(), firstWall.getUTCMinutes(), firstWall.getUTCSeconds(), firstWall.getUTCMilliseconds());+ const days = Math.round((Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate()) - Date.UTC(firstWall.getUTCFullYear(), firstWall.getUTCMonth(), firstWall.getUTCDate())) / 86_400_000);+ if (days < 0) continue;+ const months = (day.getUTCFullYear() - firstWall.getUTCFullYear()) * 12 + day.getUTCMonth() - firstWall.getUTCMonth();+ const occurs = event.repeat === "daily" || (event.repeat === "weekly" && days % 7 === 0) || (event.repeat === "weekdays" && parseCalendarRepeatDays(event.repeatDays).includes(day.getUTCDay())) || (event.repeat === "monthly" && months >= 0 && day.getUTCDate() === Math.min(event.repeatAnchorDay ?? firstWall.getUTCDate(), new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth() + 1, 0)).getUTCDate()));+ if (!occurs) continue;+ const occurrence = dateFromZonedFields(day, zone);+ if (occurrence < first || (event.repeatUntil && occurrence >= event.repeatUntil) || excluded.has(occurrence.getTime())) continue;+ if (occurrence < end && occurrence.getTime() + duration > start.getTime()) return true;+ }+ return false;+}++export async function availableBookingSlots(env: CloudflareEnv, event: BookingEventRecord, days = 14) {+ const now = new Date();+ const today = zonedDateFields(now, event.timeZone);+ today.setUTCHours(0, 0, 0, 0);+ const end = new Date(now.getTime() + (days + 2) * 86_400_000);+ const existing = await getDb(env).select().from(calendarEvents).where(and(inArray(calendarEvents.userId, event.hostIds), lt(calendarEvents.startsAt, end), or(gt(calendarEvents.endsAt, now), ne(calendarEvents.repeat, "none"))));+ const slots: { startsAt: string; endsAt: string; localDate: string; time: string }[] = [];+ for (let offset = 0; offset < days; offset++) {+ const day = new Date(today);+ day.setUTCDate(day.getUTCDate() + offset);+ if (!event.weekdays.includes(day.getUTCDay())) continue;+ const localDate = day.toISOString().slice(0, 10);+ for (const range of event.timeRanges) for (let minute = timeToMinutes(range.startTime); minute + event.durationMinutes <= timeToMinutes(range.endTime); minute += 15) {+ const time = `${String(Math.floor(minute / 60)).padStart(2, "0")}:${String(minute % 60).padStart(2, "0")}`;+ const slot = slotFromLocalDate(event, localDate, time);+ if (!slot || slot.startsAt.getTime() < now.getTime() + 60 * 60_000) continue;+ if (existing.some((calendarEvent) => repeatsDuring(calendarEvent, slot.startsAt, slot.endsAt))) continue;+ slots.push({ startsAt: slot.startsAt.toISOString(), endsAt: slot.endsAt.toISOString(), localDate, time });+ }+ }+ return slots;+}diff --git a/src/lib/booking/create.ts b/src/lib/booking/create.tsnew file mode 100644index 0000000..ec35b3b--- /dev/null+++ b/src/lib/booking/create.ts@@ -0,0 +1,34 @@+import { newId } from "@/lib/ids";+import type { BookingEventRecord } from "./types";++export async function createBookedCalendarEvents(env: CloudflareEnv, event: BookingEventRecord, guestName: string, guestEmail: string, startsAt: string, endsAt: string, guestEmails: string[] = [], notes = ""): Promise<boolean> {+ const hostIds = event.hostIds;+ const startSeconds = Math.floor(new Date(startsAt).getTime() / 1000);+ const endSeconds = Math.floor(new Date(endsAt).getTime() / 1000);+ const nowSeconds = Math.floor(Date.now() / 1000);+ const selectedHosts = hostIds.map(() => "(?, ?)").join(", ");+ const hostPlaceholders = hostIds.map(() => "?").join(", ");+ const result = await env.DB.prepare(`WITH requested_hosts(host_id, event_id) AS (VALUES ${selectedHosts}),+ conflicts AS MATERIALIZED (SELECT COUNT(*) AS total FROM calendar_events WHERE user_id IN (${hostPlaceholders}) AND repeat = 'none' AND starts_at < ? AND ends_at > ?)+ INSERT INTO calendar_events (id, user_id, mailbox_id, title, description, location, attendees, color, repeat, repeat_days, excluded_occurrences, time_zone, starts_at, ends_at, created_at, updated_at)+ SELECT requested_hosts.event_id, requested_hosts.host_id, NULL, ?, ?, ?, ?, ?, 'none', '[]', '[]', ?, ?, ?, ?, ?+ FROM requested_hosts CROSS JOIN conflicts+ WHERE conflicts.total = 0`)+ .bind(+ ...hostIds.flatMap((id) => [id, newId("evt")]),+ ...hostIds,+ endSeconds,+ startSeconds,+ `${event.name} with ${guestName}`,+ [`Booked by ${guestName} (${guestEmail})`, notes].filter(Boolean).join("\n\n"),+ event.location,+ JSON.stringify([guestEmail, ...guestEmails]),+ event.color,+ event.timeZone,+ startSeconds,+ endSeconds,+ nowSeconds,+ nowSeconds,+ ).run();+ return result.meta.changes === hostIds.length;+}diff --git a/src/lib/booking/hosts.ts b/src/lib/booking/hosts.tsnew file mode 100644index 0000000..82f4dde--- /dev/null+++ b/src/lib/booking/hosts.ts@@ -0,0 +1,20 @@+import { and, eq, inArray } from "drizzle-orm";+import type { getDb } from "@/db";+import { users } from "@/db/schema";++type Db = ReturnType<typeof getDb>;++export function parseBookingHostIds(value: string, ownerId: string): string[] {+ try {+ const parsed: unknown = JSON.parse(value);+ if (Array.isArray(parsed) && parsed.length && parsed.every((id) => typeof id === "string" && id.length > 0) && new Set(parsed).size === parsed.length) return [ownerId, ...parsed.filter((id) => id !== ownerId)];+ } catch { /* Older booking events have only the owner. */ }+ return [ownerId];+}++export async function validBookingHostIds(db: Db, ownerId: string, requested: string[], canManageHosts: boolean): Promise<string[] | null> {+ const hostIds = [ownerId, ...requested.filter((id) => id !== ownerId)];+ if (hostIds.length > 20 || (!canManageHosts && hostIds.length > 1)) return null;+ const active = await db.select({ id: users.id }).from(users).where(and(inArray(users.id, hostIds), eq(users.disabled, false)));+ return active.length === hostIds.length ? hostIds : null;+}diff --git a/src/lib/booking/types.d.ts b/src/lib/booking/types.d.tsnew file mode 100644index 0000000..628e72f--- /dev/null+++ b/src/lib/booking/types.d.ts@@ -0,0 +1,24 @@+export type BookingEventInput = {+ name: string;+ slug: string;+ description: string;+ color: string;+ hostIds: string[];+ durationMinutes: number;+ location: string;+ weekdays: number[];+ startTime: string;+ endTime: string;+ timeRanges: BookingTimeRange[];+ timeZone: string;+ enabled: boolean;+};++export type BookingTimeRange = { startTime: string; endTime: string };++export type BookingEventRecord = BookingEventInput & {+ id: string;+ userId: string;+};++export type ExistingCalendarEvent = typeof import("@/db/schema").calendarEvents.$inferSelect;diff --git a/src/lib/booking/username.ts b/src/lib/booking/username.tsnew file mode 100644index 0000000..6336c51--- /dev/null+++ b/src/lib/booking/username.ts@@ -0,0 +1,27 @@+import { and, eq, isNull } from "drizzle-orm";+import { getDb } from "@/db";+import { users } from "@/db/schema";+import { bookingUsernameFromEmail } from "./utils";++export async function ensureBookingUsername(env: CloudflareEnv, userId: string, email: string): Promise<string> {+ const db = getDb(env);+ const [current] = await db.select({ bookingUsername: users.bookingUsername }).from(users).where(eq(users.id, userId)).limit(1);+ if (!current) throw new Error("User not found");+ if (current.bookingUsername) return current.bookingUsername;+ const base = bookingUsernameFromEmail(email);+ for (let number = 1; number < 100_000; number++) {+ const candidate = number === 1 ? base : `${base}${number}`;+ const [taken] = await db.select({ id: users.id }).from(users).where(eq(users.bookingUsername, candidate)).limit(1);+ if (taken) continue;+ try {+ const [updated] = await db.update(users).set({ bookingUsername: candidate }).where(and(eq(users.id, userId), isNull(users.bookingUsername))).returning({ bookingUsername: users.bookingUsername });+ if (updated?.bookingUsername) return updated.bookingUsername;+ const [assigned] = await db.select({ bookingUsername: users.bookingUsername }).from(users).where(eq(users.id, userId)).limit(1);+ if (assigned?.bookingUsername) return assigned.bookingUsername;+ } catch (error) {+ if (error instanceof Error && /UNIQUE constraint failed|users_booking_username_idx/i.test(error.message)) continue;+ throw error;+ }+ }+ throw new Error("Could not assign a booking username");+}diff --git a/src/lib/booking/utils.ts b/src/lib/booking/utils.tsnew file mode 100644index 0000000..99c0eca--- /dev/null+++ b/src/lib/booking/utils.ts@@ -0,0 +1,77 @@+import { dateFromZonedFields, isValidTimeZone, zonedDateFields } from "@/lib/time/utils";+import type { BookingEventInput, BookingEventRecord, BookingTimeRange } from "./types";+import { normalizeCalendarColor } from "@/lib/calendar/colors";++const timePattern = /^([01]\d|2[0-3]):[0-5]\d$/;++export function slugifyBookingName(value: string): string {+ return value.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 80).replace(/-$/, "");+}++export function isValidBookingSlug(value: string): boolean {+ return value.length >= 1 && value.length <= 80 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);+}++export function normalizeBookingUsername(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const username = value.trim().toLowerCase();+ return username.length >= 1 && username.length <= 64 && /^[a-z0-9._+-]+$/.test(username) && /[a-z0-9]/.test(username) ? username : null;+}++export function bookingUsernameFromEmail(email: string): string {+ const localPart = email.split("@")[0] ?? "";+ const candidate = localPart.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9._+-]+/g, "-").slice(0, 56);+ return normalizeBookingUsername(candidate) ?? "user";+}++export function parseBookingTimeRanges(value: string, fallback?: BookingTimeRange): BookingTimeRange[] {+ try {+ const parsed: unknown = JSON.parse(value);+ if (Array.isArray(parsed) && parsed.length && parsed.every((range) => range && typeof range === "object" && typeof range.startTime === "string" && typeof range.endTime === "string")) return parsed as BookingTimeRange[];+ } catch { /* Older rows use the single time window. */ }+ return fallback ? [fallback] : [];+}++export function parseBookingEventInput(value: unknown): BookingEventInput | null {+ if (!value || typeof value !== "object") return null;+ const input = value as Record<string, unknown>;+ const name = typeof input.name === "string" ? input.name.trim() : "";+ const slug = typeof input.slug === "string" ? input.slug.trim().toLowerCase() : slugifyBookingName(name);+ const description = typeof input.description === "string" ? input.description.trim() : "";+ const location = typeof input.location === "string" ? input.location.trim() : "";+ const weekdays = input.weekdays;+ const hostIds = input.hostIds === undefined ? [] : input.hostIds;+ if (!name || name.length > 120 || !isValidBookingSlug(slug) || description.length > 2000 || location.length > 240 || typeof input.durationMinutes !== "number" || !Number.isInteger(input.durationMinutes) || input.durationMinutes < 5 || input.durationMinutes > 480) return null;+ if (!Array.isArray(hostIds) || hostIds.length > 20 || hostIds.some((id) => typeof id !== "string" || !id) || new Set(hostIds).size !== hostIds.length) return null;+ if (!Array.isArray(weekdays) || !weekdays.length || weekdays.some((day) => !Number.isInteger(day) || day < 0 || day > 6) || new Set(weekdays).size !== weekdays.length) return null;+ const timeRanges: unknown = input.timeRanges ?? (typeof input.startTime === "string" && typeof input.endTime === "string" ? [{ startTime: input.startTime, endTime: input.endTime }] : null);+ if (!Array.isArray(timeRanges) || !timeRanges.length || timeRanges.length > 12) return null;+ if (timeRanges.some((range) => !range || typeof range !== "object" || typeof range.startTime !== "string" || typeof range.endTime !== "string" || !timePattern.test(range.startTime) || !timePattern.test(range.endTime) || timeToMinutes(range.startTime) % 15 !== 0 || timeToMinutes(range.endTime) % 15 !== 0 || timeToMinutes(range.endTime) - timeToMinutes(range.startTime) < (input.durationMinutes as number))) return null;+ const normalizedRanges = (timeRanges as BookingTimeRange[]).slice().sort((a, b) => a.startTime.localeCompare(b.startTime));+ if (normalizedRanges.some((range, index) => index > 0 && range.startTime < normalizedRanges[index - 1].endTime)) return null;+ if (typeof input.timeZone !== "string" || !isValidTimeZone(input.timeZone) || typeof input.enabled !== "boolean") return null;+ return { name, slug, description, color: normalizeCalendarColor(typeof input.color === "string" ? input.color : undefined), hostIds, durationMinutes: input.durationMinutes, location, weekdays: [...weekdays].sort(), startTime: normalizedRanges[0].startTime, endTime: normalizedRanges[0].endTime, timeRanges: normalizedRanges, timeZone: input.timeZone, enabled: input.enabled };+}++export function timeToMinutes(value: string): number {+ const [hours, minutes] = value.split(":").map(Number);+ return hours * 60 + minutes;+}++export function slotFromLocalDate(event: BookingEventRecord, localDate: string, time: string): { startsAt: Date; endsAt: Date } | null {+ if (!/^\d{4}-\d{2}-\d{2}$/.test(localDate) || !timePattern.test(time)) return null;+ const wall = new Date(`${localDate}T${time}:00Z`);+ if (Number.isNaN(wall.getTime()) || wall.toISOString().slice(0, 10) !== localDate || !event.weekdays.includes(wall.getUTCDay())) return null;+ const minutes = timeToMinutes(time);+ if (!event.timeRanges.some((range) => minutes >= timeToMinutes(range.startTime) && minutes + event.durationMinutes <= timeToMinutes(range.endTime)) || minutes % 15 !== 0) return null;+ const startsAt = dateFromZonedFields(wall, event.timeZone);+ if (zonedDateFields(startsAt, event.timeZone).toISOString().slice(0, 16) !== `${localDate}T${time}`) return null;+ return { startsAt, endsAt: new Date(startsAt.getTime() + event.durationMinutes * 60_000) };+}++export function parseBookingWeekdays(value: string): number[] {+ try {+ const days: unknown = JSON.parse(value);+ return Array.isArray(days) ? days.filter((day): day is number => Number.isInteger(day) && day >= 0 && day <= 6) : [];+ } catch { return []; }+}diff --git a/src/lib/calendar/api-auth-types.d.ts b/src/lib/calendar/api-auth-types.d.tsnew file mode 100644index 0000000..da0230a--- /dev/null+++ b/src/lib/calendar/api-auth-types.d.ts@@ -0,0 +1,7 @@+import type { NextResponse } from "next/server";+import type { users } from "@/db/schema";+import type { ApiAuthResult } from "@/lib/api/key-auth-types";++export type CalendarAuthorization =+ | { user: typeof users.$inferSelect; key: ApiAuthResult | null; error: null }+ | { user: null; key: null; error: NextResponse };diff --git a/src/lib/calendar/api-auth.ts b/src/lib/calendar/api-auth.tsnew file mode 100644index 0000000..64bb126--- /dev/null+++ b/src/lib/calendar/api-auth.ts@@ -0,0 +1,23 @@+import { NextResponse } from "next/server";+import { getCurrentUser } from "@/lib/auth/cookies";+import { authenticateApiRequest, hasScope } from "@/lib/api/key-auth";+import type { ApiAuthResult } from "@/lib/api/key-auth-types";+import type { CalendarAuthorization } from "./api-auth-types";++export async function authorizeCalendarRequest(env: CloudflareEnv, request: Request, scope: "calendar:read" | "calendar:write"): Promise<CalendarAuthorization> {+ const authorization = request.headers.get("Authorization") ?? "";+ if (authorization.startsWith("Bearer ep_") || authorization.startsWith("Basic ")) {+ const key = await authenticateApiRequest(env, request);+ if (!key) return { user: null, key: null, error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };+ if (!hasScope(key.scopes, scope)) return { user: null, key: null, error: NextResponse.json({ error: "Permission denied" }, { status: 403 }) };+ return { user: key.user, key, error: null };+ }+ const user = await getCurrentUser(env, request);+ return user+ ? { user, key: null, error: null }+ : { user: null, key: null, error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };+}++export function calendarKeyCanSendInvitations(key: ApiAuthResult | null, mailboxId: string | null | undefined): boolean {+ return !key || !!mailboxId && hasScope(key.scopes, "send") && (key.mailboxIds === null || key.mailboxIds.includes(mailboxId));+}diff --git a/src/lib/seed-utils.ts b/src/lib/seed-utils.tsindex ccdc8d1..c23f0a3 100644--- a/src/lib/seed-utils.ts+++ b/src/lib/seed-utils.ts@@ -8,6 +8,7 @@ import {users,} from "@/db/schema";import { hashPassword } from "@/lib/auth/password";+import { ensureBookingUsername } from "@/lib/booking/username";import { upsertContactFromAddress } from "@/lib/contacts/service";import { buildSnippet } from "@/lib/email/parse";import { newId } from "@/lib/ids";@@ -240,6 +241,7 @@ export async function ensureDemoUser(env: CloudflareEnv) {passwordHash: hashPassword(demoCredentials.password),name: "Demo User",});+ await ensureBookingUsername(env, id, demoCredentials.email);const [created] = await db.select().from(users).where(eq(users.id, id)).limit(1);return created!;