@cosmoops/connect-sdk 0.16.1 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SchedulingResource = void 0;
4
+ const http_js_1 = require("../http.js");
5
+ const acting_as_js_1 = require("./acting-as.js");
6
+ /**
7
+ * A subscribing workspace's own calendar.
8
+ *
9
+ * **There is one calendar, not one per application.** A booking made here
10
+ * appears on the workspace's own screen immediately, and a slot their
11
+ * receptionist just took is gone from your next `findSlots`. That is the
12
+ * reason to read it through Connect rather than keeping a copy: two calendars
13
+ * double-book, and nothing reconciles them afterwards.
14
+ *
15
+ * Every method needs a live subscription to your application in the workspace
16
+ * you name. The key says which application is calling; the subscription is
17
+ * what makes you welcome in a given tenant.
18
+ */
19
+ class SchedulingResource {
20
+ transport;
21
+ constructor(transport) {
22
+ this.transport = transport;
23
+ }
24
+ /** What this workspace offers as bookable. Active appointment types only. */
25
+ async listEventTypes(workspaceId, options = {}) {
26
+ const result = await (0, http_js_1.request)(this.transport, {
27
+ method: "GET",
28
+ path: "/scheduling/event-types",
29
+ query: { workspaceId },
30
+ headers: (0, acting_as_js_1.actingAs)(options.asUser),
31
+ });
32
+ // `?? []` for the same reason `apps.list` has it - a collection every
33
+ // caller immediately maps, and a body without the key would hand them
34
+ // `undefined` past every status check in between.
35
+ return result.eventTypes ?? [];
36
+ }
37
+ /**
38
+ * Free times for one appointment type over one window.
39
+ *
40
+ * **Advisory by construction.** Between this answer and `createBooking`,
41
+ * anyone else on that calendar can take any of these - a member, a voice
42
+ * agent mid-call, someone on the workspace's public booking link. That is
43
+ * why `createBooking` can answer `409`, and why that is an ordinary outcome
44
+ * rather than a fault.
45
+ *
46
+ * The window is clamped silently to now and to the appointment type's own
47
+ * booking horizon, so asking for a year of a sixty-day type returns sixty
48
+ * days rather than an error.
49
+ */
50
+ findSlots(input) {
51
+ return (0, http_js_1.request)(this.transport, {
52
+ method: "GET",
53
+ path: "/scheduling/slots",
54
+ query: {
55
+ workspaceId: input.workspaceId,
56
+ eventTypeId: input.eventTypeId,
57
+ from: toInstant(input.from),
58
+ to: toInstant(input.to),
59
+ excludeBookingId: input.excludeBookingId,
60
+ },
61
+ headers: (0, acting_as_js_1.actingAs)(input.asUser),
62
+ });
63
+ }
64
+ /** One page of the workspace's diary. */
65
+ listBookings(input) {
66
+ return (0, http_js_1.request)(this.transport, {
67
+ method: "GET",
68
+ path: "/scheduling/bookings",
69
+ query: {
70
+ workspaceId: input.workspaceId,
71
+ status: input.status,
72
+ hostMemberId: input.hostMemberId,
73
+ from: input.from ? toInstant(input.from) : undefined,
74
+ to: input.to ? toInstant(input.to) : undefined,
75
+ order: input.order,
76
+ cursor: input.cursor,
77
+ limit: input.limit === undefined ? undefined : String(input.limit),
78
+ },
79
+ headers: (0, acting_as_js_1.actingAs)(input.asUser),
80
+ });
81
+ }
82
+ /**
83
+ * Takes one of the times `findSlots` offered.
84
+ *
85
+ * Holds and confirms in one call - you already have the attendee, so there
86
+ * is no half-finished state for your integration to remember. The slot is
87
+ * re-checked inside a transaction, so a time taken since you read it throws
88
+ * a `ConnectError` with `code: "conflict"` rather than double-booking.
89
+ */
90
+ createBooking(input) {
91
+ return (0, http_js_1.request)(this.transport, {
92
+ method: "POST",
93
+ path: "/scheduling/bookings",
94
+ json: {
95
+ workspaceId: input.workspaceId,
96
+ eventTypeId: input.eventTypeId,
97
+ startAt: toInstant(input.startAt),
98
+ attendee: input.attendee,
99
+ notes: input.notes ?? null,
100
+ },
101
+ headers: (0, acting_as_js_1.actingAs)(input.asUser),
102
+ });
103
+ }
104
+ /**
105
+ * Moves an appointment to a different time.
106
+ *
107
+ * **The original is retired, not edited.** It stays on the diary as
108
+ * `rescheduled` with `rescheduledToId` pointing at the replacement, and both
109
+ * come back here - so a booking id you cached still resolves, and still says
110
+ * where the appointment went.
111
+ *
112
+ * A refused move changes nothing: the new slot is claimed before the old one
113
+ * is released, so a `conflict` leaves the customer with the appointment they
114
+ * already had. Re-read the slots (with `excludeBookingId`) and offer another.
115
+ */
116
+ rescheduleBooking(input) {
117
+ return (0, http_js_1.request)(this.transport, {
118
+ method: "POST",
119
+ path: `/scheduling/bookings/${encodeURIComponent(input.bookingId)}/reschedule`,
120
+ json: {
121
+ workspaceId: input.workspaceId,
122
+ startAt: toInstant(input.startAt),
123
+ notes: input.notes ?? null,
124
+ },
125
+ headers: (0, acting_as_js_1.actingAs)(input.asUser),
126
+ });
127
+ }
128
+ /**
129
+ * Frees the slot and records why.
130
+ *
131
+ * Not a deletion: the booking stays on the diary as `cancelled` with the
132
+ * reason, which is what makes a late cancellation something anyone can look
133
+ * up afterwards.
134
+ */
135
+ cancelBooking(input) {
136
+ return (0, http_js_1.request)(this.transport, {
137
+ method: "POST",
138
+ path: `/scheduling/bookings/${encodeURIComponent(input.bookingId)}/cancel`,
139
+ json: { workspaceId: input.workspaceId, reason: input.reason ?? null },
140
+ headers: (0, acting_as_js_1.actingAs)(input.asUser),
141
+ });
142
+ }
143
+ }
144
+ exports.SchedulingResource = SchedulingResource;
145
+ /**
146
+ * A `Date` or an already-ISO string, as the ISO-8601 instant the API takes.
147
+ *
148
+ * `toISOString()` rather than any local formatting: these are instants, and a
149
+ * wall time without a zone is the one input this API cannot interpret.
150
+ */
151
+ function toInstant(value) {
152
+ return typeof value === "string" ? value : value.toISOString();
153
+ }
@@ -0,0 +1,167 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Button, Card, Chip, Skeleton } from "@heroui/react";
4
+ import { CalendarDays, ChevronLeft, ChevronRight, Phone, Video } from "lucide-react";
5
+ import { useMemo, useState } from "react";
6
+ import { ConnectEmptyState } from "../../ui/empty-state.js";
7
+ import { useBookableEventTypes, useBookings, } from "../use-scheduling.js";
8
+ import { dayColumns, dayStartInstant, hourMarks, layoutBookings, zonedInstant, } from "./booking-grid.js";
9
+ import { ConnectBookingDetail, ConnectBookingDialog } from "./booking-dialogs.js";
10
+ /**
11
+ * The visible band of the day. Outside it a booking is drawn at the edge and
12
+ * flagged rather than hidden - see `layoutBookings`.
13
+ *
14
+ * 07:00-21:00 rather than a full day: fourteen hours is the most that stays
15
+ * legible on a laptop without scrolling, and a booking grid whose first screen
16
+ * is six empty night-time hours reads as a broken calendar.
17
+ */
18
+ const DEFAULT_WINDOW = { startMinute: 7 * 60, endMinute: 21 * 60 };
19
+ const LOCATION_ICON = {
20
+ phone: Phone,
21
+ address: CalendarDays,
22
+ link: Video,
23
+ };
24
+ /**
25
+ * A week of the workspace's calendar, with booking, rescheduling and
26
+ * cancelling.
27
+ *
28
+ * **Two views, and which one you get is a viewport decision, not a
29
+ * preference.** A seven-column time grid needs roughly 640px before a column
30
+ * is wide enough to hold a name; below that it degrades into unreadable
31
+ * slivers. So the grid is `sm:` and up, and the same week renders as a grouped
32
+ * agenda underneath - not a cut-down grid, a different and better shape for a
33
+ * phone. Both read the same data and open the same dialogs.
34
+ *
35
+ * Everything it does goes through the bridge as the signed-in member, so
36
+ * Connect checks *their* `calendar:read` / `calendar:manage` rather than the
37
+ * host application's key. A member who may look but not book gets the grid and
38
+ * a refusal on the write, which is the correct shape - see `useBookingActions`.
39
+ */
40
+ export function ConnectBookingCalendar({ timeZone, hostMemberId, window: visibleWindow = DEFAULT_WINDOW, canBook = true, className, }) {
41
+ const zone = timeZone ?? hostTimeZone();
42
+ const [weekAnchor, setWeekAnchor] = useState(() => startOfWeek(new Date(), zone));
43
+ const [selected, setSelected] = useState(null);
44
+ const [booking, setBooking] = useState(null);
45
+ const now = new Date();
46
+ const columns = useMemo(() => dayColumns(weekAnchor, zone, 7, now),
47
+ // `now` is deliberately not a dependency: it changes on every render, and
48
+ // the only thing it decides is which column is highlighted. Recomputing
49
+ // seven columns per keystroke elsewhere on the page to move a highlight
50
+ // that changes once a day is not a trade worth making.
51
+ // eslint-disable-next-line react-hooks/exhaustive-deps
52
+ [weekAnchor, zone]);
53
+ const range = useMemo(() => ({
54
+ from: columns[0]?.startsAt ?? weekAnchor,
55
+ to: new Date((columns.at(-1)?.startsAt.getTime() ?? weekAnchor.getTime()) + 24 * 60 * 60_000),
56
+ }), [columns, weekAnchor]);
57
+ const { eventTypes } = useBookableEventTypes();
58
+ const { bookings, isLoading, error, refetch } = useBookings({
59
+ from: range.from,
60
+ to: range.to,
61
+ hostMemberId,
62
+ });
63
+ const positioned = useMemo(() => layoutBookings(bookings, zone, visibleWindow), [bookings, zone, visibleWindow]);
64
+ const marks = useMemo(() => hourMarks(visibleWindow), [visibleWindow]);
65
+ const shiftWeek = (weeks) => setWeekAnchor((anchor) => new Date(anchor.getTime() + weeks * 7 * 24 * 60 * 60_000));
66
+ const eventTypeById = useMemo(() => new Map(eventTypes.map((eventType) => [eventType.id, eventType])), [eventTypes]);
67
+ return (_jsxs("div", { className: `flex flex-col gap-4 ${className ?? ""}`, children: [_jsxs("header", { className: "flex flex-wrap items-center justify-between gap-3", children: [_jsxs("div", { className: "flex items-center gap-1", children: [_jsx(Button, { isIconOnly: true, size: "sm", variant: "tertiary", "aria-label": "Previous week", onPress: () => shiftWeek(-1), children: _jsx(ChevronLeft, { className: "size-4", "aria-hidden": true }) }), _jsx(Button, { size: "sm", variant: "secondary", onPress: () => setWeekAnchor(startOfWeek(new Date(), zone)), children: "Today" }), _jsx(Button, { isIconOnly: true, size: "sm", variant: "tertiary", "aria-label": "Next week", onPress: () => shiftWeek(1), children: _jsx(ChevronRight, { className: "size-4", "aria-hidden": true }) }), _jsx("p", { className: "ml-2 text-sm font-medium", children: weekLabel(columns, zone) })] }), canBook && eventTypes.length > 0 && (_jsx(Button, { size: "sm", variant: "primary", onPress: () => setBooking({ startAt: nextHour(now) }), children: "New appointment" }))] }), error && _jsx("p", { className: "text-sm text-danger", children: error }), isLoading ? (_jsx(Skeleton, { className: "h-96 w-full rounded-lg" })) : (_jsxs(_Fragment, { children: [_jsx(Card, { className: "hidden overflow-hidden sm:block", children: _jsx(WeekGrid, { columns: columns, marks: marks, window: visibleWindow, positioned: positioned, eventTypeById: eventTypeById, zone: zone, onSelect: setSelected, onPickEmpty: canBook ? (startAt) => setBooking({ startAt }) : undefined }) }), _jsx("div", { className: "sm:hidden", children: _jsx(AgendaView, { columns: columns, bookings: bookings, eventTypeById: eventTypeById, zone: zone, onSelect: setSelected }) })] })), booking && (_jsx(ConnectBookingDialog, { isOpen: true, onOpenChange: (open) => !open && setBooking(null), eventTypes: eventTypes, initialStartAt: booking.startAt, timeZone: zone, onBooked: () => {
68
+ setBooking(null);
69
+ refetch();
70
+ } })), selected && (_jsx(ConnectBookingDetail, { booking: selected, eventType: eventTypeById.get(selected.eventTypeId) ?? null, timeZone: zone, onOpenChange: (open) => !open && setSelected(null), onChanged: () => {
71
+ setSelected(null);
72
+ refetch();
73
+ } }))] }));
74
+ }
75
+ function WeekGrid({ columns, marks, window: visibleWindow, positioned, eventTypeById, zone, onSelect, onPickEmpty, }) {
76
+ const span = visibleWindow.endMinute - visibleWindow.startMinute;
77
+ return (_jsxs("div", { className: "grid grid-cols-[3rem_repeat(7,minmax(0,1fr))]", children: [_jsx("div", { className: "border-b border-separator" }), columns.map((column) => (_jsx("div", { className: `border-b border-l border-separator px-2 py-2 text-center ${column.isToday ? "bg-accent/5" : ""}`, children: _jsx("p", { className: `text-xs font-medium ${column.isToday ? "text-accent" : ""}`, children: column.label }) }, column.dateKey))), _jsx("div", { className: "relative", style: { height: `${(span / 60) * 3}rem` }, children: marks.map((mark) => (_jsx("span", { className: "absolute right-1 -translate-y-1/2 text-[0.625rem] text-muted", style: { top: `${((mark.minute - visibleWindow.startMinute) / span) * 100}%` }, children: mark.label }, mark.minute))) }), columns.map((column) => (_jsxs("div", { className: `relative border-l border-separator ${column.isToday ? "bg-accent/5" : ""}`, style: { height: `${(span / 60) * 3}rem` }, children: [marks.map((mark) => (_jsx("div", { className: "absolute inset-x-0 border-t border-separator/60", style: { top: `${((mark.minute - visibleWindow.startMinute) / span) * 100}%` } }, mark.minute))), onPickEmpty &&
78
+ marks.map((mark) => (_jsx("button", { type: "button", "aria-label": `Book ${column.label} at ${mark.label}`, className: "absolute inset-x-0 cursor-pointer transition-colors hover:bg-accent/10", style: {
79
+ top: `${((mark.minute - visibleWindow.startMinute) / span) * 100}%`,
80
+ height: `${(60 / span) * 100}%`,
81
+ }, onClick: () => onPickEmpty(new Date(column.startsAt.getTime() + mark.minute * 60_000)) }, `slot-${mark.minute}`))), positioned
82
+ .filter((entry) => entry.dateKey === column.dateKey)
83
+ .map((entry) => {
84
+ const eventType = eventTypeById.get(entry.booking.eventTypeId);
85
+ return (_jsxs("button", { type: "button", onClick: () => onSelect(entry.booking), className: "absolute overflow-hidden rounded-[--radius] border border-accent/30 bg-accent/15 px-1 py-0.5 text-left transition-colors hover:bg-accent/25", style: {
86
+ top: `${entry.top * 100}%`,
87
+ height: `${entry.height * 100}%`,
88
+ // Side-by-side within an overlap cluster, with a hairline
89
+ // gap so two adjacent blocks read as two things.
90
+ left: `${(entry.column / entry.columns) * 100}%`,
91
+ width: `calc(${(1 / entry.columns) * 100}% - 2px)`,
92
+ }, children: [_jsx("span", { className: "block truncate text-[0.625rem] font-medium text-accent", children: timeLabel(new Date(entry.booking.startAt), zone) }), _jsx("span", { className: "block truncate text-[0.625rem]", children: entry.booking.attendee.name }), eventType && (_jsx("span", { className: "block truncate text-[0.625rem] text-muted", children: eventType.name }))] }, entry.booking.id));
93
+ })] }, column.dateKey)))] }));
94
+ }
95
+ function AgendaView({ columns, bookings, eventTypeById, zone, onSelect, }) {
96
+ const byDay = useMemo(() => {
97
+ const map = new Map();
98
+ for (const booking of bookings) {
99
+ const { dateKey } = zonedInstant(new Date(booking.startAt), zone);
100
+ map.set(dateKey, [...(map.get(dateKey) ?? []), booking]);
101
+ }
102
+ return map;
103
+ }, [bookings, zone]);
104
+ // Days with nothing on them are omitted rather than rendered empty: an
105
+ // agenda is a list of what is happening, and seven "nothing" rows is six
106
+ // screens of scrolling to find the one day that matters.
107
+ const populated = columns.filter((column) => (byDay.get(column.dateKey)?.length ?? 0) > 0);
108
+ if (populated.length === 0) {
109
+ return (_jsx(ConnectEmptyState, { variant: "dashed", icon: _jsx(CalendarDays, { "aria-hidden": true }), title: "Nothing booked this week", description: "Appointments booked here, on your public link, or by a voice agent all show up together." }));
110
+ }
111
+ return (_jsx("div", { className: "flex flex-col gap-4", children: populated.map((column) => (_jsxs("section", { className: "flex flex-col gap-2", children: [_jsx("h3", { className: `text-sm font-medium ${column.isToday ? "text-accent" : ""}`, children: column.label }), (byDay.get(column.dateKey) ?? []).map((booking) => {
112
+ const eventType = eventTypeById.get(booking.eventTypeId);
113
+ const Icon = eventType ? LOCATION_ICON[eventType.locationKind] : CalendarDays;
114
+ return (_jsx("button", { type: "button", onClick: () => onSelect(booking), children: _jsx(Card, { className: "transition-colors hover:bg-surface", children: _jsxs(Card.Content, { className: "flex items-center gap-3 py-3 text-left", children: [_jsx(Icon, { className: "size-4 shrink-0 text-muted", "aria-hidden": true }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("p", { className: "truncate text-sm font-medium", children: booking.attendee.name }), _jsxs("p", { className: "truncate text-xs text-muted", children: [timeLabel(new Date(booking.startAt), zone), eventType ? ` · ${eventType.name}` : ""] })] }), booking.source === "agent-call" && (_jsxs(Chip, { size: "sm", variant: "secondary", children: [_jsx(Phone, { className: "size-3", "aria-hidden": true }), "Agent"] }))] }) }) }, booking.id));
115
+ })] }, column.dateKey))) }));
116
+ }
117
+ /* ------------------------------------------------------------------ helpers */
118
+ /** The host's zone, used when the caller does not name the business's. */
119
+ function hostTimeZone() {
120
+ try {
121
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
122
+ }
123
+ catch {
124
+ return "UTC";
125
+ }
126
+ }
127
+ /**
128
+ * Monday of the week `instant` falls in, in `zone`.
129
+ *
130
+ * Monday rather than Sunday: this is a *business* calendar, and a week that
131
+ * splits the working days across two screens is the one thing a week view must
132
+ * not do.
133
+ */
134
+ function startOfWeek(instant, zone) {
135
+ const { dateKey } = zonedInstant(instant, zone);
136
+ const midnight = dayStartInstant(dateKey, zone);
137
+ // `getUTCDay` on local midnight-as-an-instant is not the local weekday, so
138
+ // the weekday is read back through the zone.
139
+ const weekday = new Intl.DateTimeFormat("en-US", { timeZone: zone, weekday: "short" }).format(midnight);
140
+ const offset = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(weekday);
141
+ return new Date(midnight.getTime() - (offset < 0 ? 0 : offset) * 24 * 60 * 60_000);
142
+ }
143
+ function weekLabel(columns, zone) {
144
+ const first = columns[0];
145
+ const last = columns.at(-1);
146
+ if (!first || !last)
147
+ return "";
148
+ const month = new Intl.DateTimeFormat("en-IN", { timeZone: zone, month: "long", year: "numeric" });
149
+ return first.monthLabel === last.monthLabel
150
+ ? month.format(first.startsAt)
151
+ : `${first.monthLabel} - ${month.format(last.startsAt)}`;
152
+ }
153
+ function timeLabel(instant, zone) {
154
+ return new Intl.DateTimeFormat("en-IN", {
155
+ timeZone: zone,
156
+ hour: "numeric",
157
+ minute: "2-digit",
158
+ hour12: true,
159
+ }).format(instant);
160
+ }
161
+ /** The next whole hour - where "New appointment" opens with no slot picked. */
162
+ function nextHour(now) {
163
+ const next = new Date(now);
164
+ next.setMinutes(0, 0, 0);
165
+ return new Date(next.getTime() + 60 * 60_000);
166
+ }
167
+ export { timeLabel as connectBookingTimeLabel };
@@ -0,0 +1,120 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Button, Input, Label, Modal, TextField } from "@heroui/react";
4
+ import { CalendarX2, Clock } from "lucide-react";
5
+ import { useMemo, useState } from "react";
6
+ import { useAvailableSlots, useBookingActions } from "../use-scheduling.js";
7
+ const SEARCH_DAYS = 14;
8
+ /**
9
+ * Picking a time, and then who it is for.
10
+ *
11
+ * The slot list is read fresh every time this opens and is **never cached
12
+ * across an open**: it is a snapshot of contention, and offering a time
13
+ * somebody took ninety seconds ago is how two people end up in the same slot.
14
+ * The server re-checks inside its transaction regardless, so a stale list
15
+ * costs a refusal rather than a double booking - this only makes the refusal
16
+ * rare enough to be surprising when it happens.
17
+ */
18
+ export function ConnectBookingDialog({ isOpen, onOpenChange, eventTypes, initialStartAt, timeZone, onBooked, }) {
19
+ const [eventTypeId, setEventTypeId] = useState(eventTypes[0]?.id ?? "");
20
+ const [chosen, setChosen] = useState(null);
21
+ const [name, setName] = useState("");
22
+ const [phone, setPhone] = useState("");
23
+ const window = useMemo(() => ({
24
+ // From the start of the day that was clicked, so the times on offer are
25
+ // the ones near where the person was looking.
26
+ from: new Date(initialStartAt.getTime() - 12 * 60 * 60_000),
27
+ to: new Date(initialStartAt.getTime() + SEARCH_DAYS * 24 * 60 * 60_000),
28
+ }), [initialStartAt]);
29
+ const { slots, isLoading } = useAvailableSlots(eventTypeId ? { eventTypeId, from: window.from, to: window.to } : null);
30
+ const { createBooking, isPending, error, clearError } = useBookingActions();
31
+ const canSubmit = Boolean(chosen && name.trim() && phone.trim()) && !isPending;
32
+ return (_jsx(Modal, { isOpen: isOpen, onOpenChange: onOpenChange, children: _jsx(Modal.Backdrop, { children: _jsx(Modal.Container, { children: _jsxs(Modal.Dialog, { children: [_jsx(Modal.Header, { children: "New appointment" }), _jsxs(Modal.Body, { className: "flex flex-col gap-4", children: [eventTypes.length > 1 && (_jsx("div", { className: "flex flex-wrap gap-2", children: eventTypes.map((eventType) => (_jsx(Button, { size: "sm", variant: eventType.id === eventTypeId ? "primary" : "secondary", onPress: () => {
33
+ setEventTypeId(eventType.id);
34
+ // The old pick belongs to the old type's grid and is
35
+ // almost never a legal slot on the new one.
36
+ setChosen(null);
37
+ }, children: eventType.name }, eventType.id))) })), _jsx(SlotPicker, { slots: slots, isLoading: isLoading, chosen: chosen, onChoose: setChosen, timeZone: timeZone }), _jsxs(TextField, { isRequired: true, variant: "secondary", children: [_jsx(Label, { children: "Name" }), _jsx(Input, { value: name, onChange: (e) => setName(e.currentTarget.value), disabled: isPending })] }), _jsxs(TextField, { isRequired: true, variant: "secondary", children: [_jsx(Label, { children: "Phone" }), _jsx(Input, { type: "tel", value: phone, onChange: (e) => setPhone(e.currentTarget.value), disabled: isPending })] }), error && _jsx("p", { className: "text-sm text-danger", children: error }), _jsxs("div", { className: "flex justify-end gap-2", children: [_jsx(Button, { variant: "secondary", onPress: () => onOpenChange(false), isDisabled: isPending, children: "Cancel" }), _jsx(Button, { variant: "primary", isDisabled: !canSubmit, onPress: async () => {
38
+ clearError();
39
+ const booked = await createBooking({
40
+ eventTypeId,
41
+ startAt: chosen,
42
+ attendee: { name: name.trim(), phone: phone.trim(), email: null },
43
+ });
44
+ if (booked)
45
+ onBooked(booked);
46
+ }, children: isPending ? "Booking…" : "Book" })] })] })] }) }) }) }));
47
+ }
48
+ /**
49
+ * One appointment, and the two things anyone opens it to do.
50
+ *
51
+ * Rescheduling re-reads the slots with `excludeBookingId` set to this booking.
52
+ * Without that the appointment blocks its own replacement, and moving it by
53
+ * half an hour - the only move most people ever make - offers nothing.
54
+ */
55
+ export function ConnectBookingDetail({ booking, eventType, timeZone, onOpenChange, onChanged, }) {
56
+ const [isMoving, setMoving] = useState(false);
57
+ const [chosen, setChosen] = useState(null);
58
+ const { rescheduleBooking, cancelBooking, isPending, error, clearError } = useBookingActions();
59
+ const start = new Date(booking.startAt);
60
+ const window = useMemo(() => ({
61
+ from: new Date(start.getTime() - 12 * 60 * 60_000),
62
+ to: new Date(start.getTime() + SEARCH_DAYS * 24 * 60 * 60_000),
63
+ }), [start]);
64
+ const { slots, isLoading } = useAvailableSlots(isMoving ? { eventTypeId: booking.eventTypeId, ...window, excludeBookingId: booking.id } : null);
65
+ return (_jsx(Modal, { isOpen: true, onOpenChange: onOpenChange, children: _jsx(Modal.Backdrop, { children: _jsx(Modal.Container, { children: _jsxs(Modal.Dialog, { children: [_jsx(Modal.Header, { children: booking.attendee.name }), _jsxs(Modal.Body, { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("p", { className: "flex items-center gap-2 text-sm", children: [_jsx(Clock, { className: "size-4 text-muted", "aria-hidden": true }), longLabel(start, timeZone)] }), eventType && _jsx("p", { className: "text-sm text-muted", children: eventType.name }), _jsx("p", { className: "text-sm text-muted", children: booking.attendee.phone }), booking.notes && _jsx("p", { className: "pt-1 text-sm", children: booking.notes })] }), isMoving && (_jsx(SlotPicker, { slots: slots, isLoading: isLoading, chosen: chosen, onChoose: setChosen, timeZone: timeZone })), error && _jsx("p", { className: "text-sm text-danger", children: error }), _jsx("div", { className: "flex flex-wrap justify-end gap-2", children: isMoving ? (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "secondary", onPress: () => setMoving(false), isDisabled: isPending, children: "Back" }), _jsx(Button, { variant: "primary", isDisabled: !chosen || isPending, onPress: async () => {
66
+ clearError();
67
+ const moved = await rescheduleBooking({
68
+ bookingId: booking.id,
69
+ startAt: chosen,
70
+ });
71
+ if (moved)
72
+ onChanged();
73
+ }, children: isPending ? "Moving…" : "Move appointment" })] })) : (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "danger", isDisabled: isPending, onPress: async () => {
74
+ clearError();
75
+ const cancelled = await cancelBooking({ bookingId: booking.id });
76
+ if (cancelled)
77
+ onChanged();
78
+ }, children: isPending ? "Cancelling…" : "Cancel appointment" }), _jsx(Button, { variant: "secondary", onPress: () => setMoving(true), children: "Reschedule" })] })) })] })] }) }) }) }));
79
+ }
80
+ function SlotPicker({ slots, isLoading, chosen, onChoose, timeZone, }) {
81
+ const byDay = useMemo(() => {
82
+ const groups = new Map();
83
+ const dayFormat = new Intl.DateTimeFormat("en-IN", {
84
+ timeZone,
85
+ weekday: "short",
86
+ day: "numeric",
87
+ month: "short",
88
+ });
89
+ for (const slot of slots) {
90
+ const label = dayFormat.format(new Date(slot.startAt));
91
+ groups.set(label, [...(groups.get(label) ?? []), slot]);
92
+ }
93
+ return [...groups.entries()];
94
+ }, [slots, timeZone]);
95
+ if (isLoading)
96
+ return _jsx("p", { className: "text-sm text-muted", children: "Finding free times\u2026" });
97
+ if (byDay.length === 0) {
98
+ return (_jsxs("div", { className: "flex items-center gap-2 rounded-lg border border-dashed border-separator p-4", children: [_jsx(CalendarX2, { className: "size-4 text-muted", "aria-hidden": true }), _jsx("p", { className: "text-sm text-muted", children: "Nothing free in the next two weeks." })] }));
99
+ }
100
+ return (_jsx("div", { className: "flex max-h-56 flex-col gap-3 overflow-y-auto", children: byDay.map(([day, daySlots]) => (_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("p", { className: "text-xs font-medium text-muted", children: day }), _jsx("div", { className: "grid grid-cols-2 gap-1.5 sm:grid-cols-4", children: daySlots.map((slot) => (_jsx(Button, { size: "sm", className: "w-full", variant: slot.startAt === chosen ? "primary" : "secondary", onPress: () => onChoose(slot.startAt), children: shortTime(new Date(slot.startAt), timeZone) }, slot.startAt))) })] }, day))) }));
101
+ }
102
+ function shortTime(instant, timeZone) {
103
+ return new Intl.DateTimeFormat("en-IN", {
104
+ timeZone,
105
+ hour: "numeric",
106
+ minute: "2-digit",
107
+ hour12: true,
108
+ }).format(instant);
109
+ }
110
+ function longLabel(instant, timeZone) {
111
+ return new Intl.DateTimeFormat("en-IN", {
112
+ timeZone,
113
+ weekday: "long",
114
+ day: "numeric",
115
+ month: "long",
116
+ hour: "numeric",
117
+ minute: "2-digit",
118
+ hour12: true,
119
+ }).format(instant);
120
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * An instant, as the local day and minute it lands on in `timeZone`.
3
+ *
4
+ * Built from `formatToParts` rather than by adding a fixed offset. An offset
5
+ * is only correct until a DST boundary, and "add 5.5 hours" is wrong the
6
+ * moment the same code is pointed at a zone that observes one - which is
7
+ * exactly the kind of bug that appears twice a year and never in a test.
8
+ */
9
+ export function zonedInstant(instant, timeZone) {
10
+ const parts = partsFormatter(timeZone).formatToParts(instant);
11
+ const read = (type) => parts.find((part) => part.type === type)?.value ?? "00";
12
+ // `hourCycle: "h23"` so midnight is 00 rather than 24 - `hour12: false`
13
+ // alone still yields 24 in some engines, and a 24 would push midnight onto
14
+ // the wrong day.
15
+ return {
16
+ dateKey: `${read("year")}-${read("month")}-${read("day")}`,
17
+ minutes: Number(read("hour")) * 60 + Number(read("minute")),
18
+ };
19
+ }
20
+ const formatterCache = new Map();
21
+ function partsFormatter(timeZone) {
22
+ let formatter = formatterCache.get(timeZone);
23
+ if (!formatter) {
24
+ // Cached because a grid calls this once per booking per render, and
25
+ // constructing an `Intl.DateTimeFormat` is the expensive part by a wide
26
+ // margin.
27
+ formatter = new Intl.DateTimeFormat("en-CA", {
28
+ timeZone,
29
+ year: "numeric",
30
+ month: "2-digit",
31
+ day: "2-digit",
32
+ hour: "2-digit",
33
+ minute: "2-digit",
34
+ hourCycle: "h23",
35
+ });
36
+ formatterCache.set(timeZone, formatter);
37
+ }
38
+ return formatter;
39
+ }
40
+ /**
41
+ * `count` consecutive days starting at the local day `anchor` falls on.
42
+ *
43
+ * Days are stepped by adding 24 hours and re-reading the zone rather than by
44
+ * incrementing a date field, so a day that is 23 or 25 hours long still
45
+ * produces the right sequence of `dateKey`s - the midday anchor is what keeps
46
+ * a DST shift from landing the step on the previous or next day.
47
+ */
48
+ export function dayColumns(anchor, timeZone, count, now) {
49
+ const todayKey = zonedInstant(now, timeZone).dateKey;
50
+ const columns = [];
51
+ for (let index = 0; index < count; index += 1) {
52
+ const probe = new Date(anchor.getTime() + index * 24 * 60 * 60_000);
53
+ const { dateKey } = zonedInstant(probe, timeZone);
54
+ const startsAt = dayStartInstant(dateKey, timeZone);
55
+ columns.push({
56
+ dateKey,
57
+ label: new Intl.DateTimeFormat("en-IN", {
58
+ timeZone,
59
+ weekday: "short",
60
+ day: "numeric",
61
+ }).format(startsAt),
62
+ monthLabel: new Intl.DateTimeFormat("en-IN", { timeZone, month: "short" }).format(startsAt),
63
+ startsAt,
64
+ isToday: dateKey === todayKey,
65
+ });
66
+ }
67
+ return columns;
68
+ }
69
+ /**
70
+ * Local midnight of `dateKey` in `timeZone`, as an instant.
71
+ *
72
+ * Solved by probing rather than by arithmetic: guess UTC midnight, read what
73
+ * local time that actually is, and subtract the difference. One correction is
74
+ * always enough because a zone's offset cannot change within the few hours the
75
+ * correction spans - and unlike a fixed-offset formula it is right across DST
76
+ * and for the half-hour zones (`Asia/Kolkata`, `Australia/Adelaide`) that a
77
+ * naive implementation quietly breaks on.
78
+ */
79
+ export function dayStartInstant(dateKey, timeZone) {
80
+ const utcGuess = new Date(`${dateKey}T00:00:00.000Z`);
81
+ const { dateKey: landedOn, minutes } = zonedInstant(utcGuess, timeZone);
82
+ // Whether the guess landed on the day before, the day itself, or the day
83
+ // after decides which way to correct.
84
+ const dayDelta = compareDateKeys(landedOn, dateKey);
85
+ return new Date(utcGuess.getTime() - (minutes + dayDelta * 1440) * 60_000);
86
+ }
87
+ function compareDateKeys(a, b) {
88
+ if (a === b)
89
+ return 0;
90
+ return a < b ? -1 : 1;
91
+ }
92
+ /**
93
+ * A fifteen-minute appointment on a twelve-hour grid is two percent tall -
94
+ * unreadable and unclickable. Short appointments are drawn at a floor and
95
+ * allowed to overhang, which is what every calendar does and what makes a
96
+ * back-to-back pair still look like two things.
97
+ */
98
+ const MIN_VISIBLE_FRACTION = 0.02;
99
+ /**
100
+ * Places bookings on the grid, side by side where they collide.
101
+ *
102
+ * Overlap handling is the part worth stating. Two appointments at the same
103
+ * time are not an error - a workspace with two hosts has them constantly - and
104
+ * stacking them would hide one entirely. So overlapping bookings are grouped
105
+ * into *clusters* and each cluster is split into equal columns. The cluster is
106
+ * built transitively: A overlapping B and B overlapping C puts all three in one
107
+ * cluster even when A and C do not touch, because anything else lets two of
108
+ * them land on the same column.
109
+ */
110
+ export function layoutBookings(bookings, timeZone, window) {
111
+ const span = window.endMinute - window.startMinute;
112
+ if (span <= 0)
113
+ return [];
114
+ const byDay = new Map();
115
+ for (const booking of bookings) {
116
+ const start = zonedInstant(new Date(booking.startAt), timeZone);
117
+ const end = zonedInstant(new Date(booking.endAt), timeZone);
118
+ // An appointment that crosses local midnight is clamped to the end of the
119
+ // day it started on. Splitting it across two columns would be more correct
120
+ // and is not worth the complexity for a booking grid, where the longest
121
+ // event type is capped at eight hours server-side.
122
+ const endMinutes = end.dateKey === start.dateKey ? end.minutes : 1440;
123
+ const entries = byDay.get(start.dateKey) ?? [];
124
+ entries.push({ booking, start: start.minutes, end: Math.max(endMinutes, start.minutes + 1) });
125
+ byDay.set(start.dateKey, entries);
126
+ }
127
+ const positioned = [];
128
+ for (const [dateKey, entries] of byDay) {
129
+ entries.sort((a, b) => a.start - b.start || a.end - b.end);
130
+ for (const cluster of clusterOverlapping(entries)) {
131
+ cluster.forEach((entry, column) => {
132
+ const clampedStart = Math.max(entry.start, window.startMinute);
133
+ const clampedEnd = Math.min(entry.end, window.endMinute);
134
+ positioned.push({
135
+ booking: entry.booking,
136
+ dateKey,
137
+ top: (clampedStart - window.startMinute) / span,
138
+ height: Math.max((clampedEnd - clampedStart) / span, MIN_VISIBLE_FRACTION),
139
+ column,
140
+ columns: cluster.length,
141
+ clipped: entry.start < window.startMinute || entry.end > window.endMinute,
142
+ });
143
+ });
144
+ }
145
+ }
146
+ return positioned;
147
+ }
148
+ /**
149
+ * Transitive overlap grouping - see `layoutBookings`.
150
+ *
151
+ * Entries arrive sorted by start. A cluster stays open while the next entry
152
+ * begins before the *furthest* end seen so far, not before the previous
153
+ * entry's end: a long appointment that swallows several short ones has to keep
154
+ * the whole run together.
155
+ */
156
+ function clusterOverlapping(entries) {
157
+ const clusters = [];
158
+ let current = [];
159
+ let clusterEnd = -Infinity;
160
+ for (const entry of entries) {
161
+ if (current.length > 0 && entry.start >= clusterEnd) {
162
+ clusters.push(current);
163
+ current = [];
164
+ clusterEnd = -Infinity;
165
+ }
166
+ current.push(entry);
167
+ clusterEnd = Math.max(clusterEnd, entry.end);
168
+ }
169
+ if (current.length > 0)
170
+ clusters.push(current);
171
+ return clusters;
172
+ }
173
+ /**
174
+ * The hour labels down the left edge, inclusive of both ends.
175
+ *
176
+ * Takes no timezone, deliberately: these label *wall-clock hours on the grid*,
177
+ * not instants. The grid is already drawn in the business's zone, so "10 am"
178
+ * means the business's ten - running the label through a zone conversion would
179
+ * shift it away from the row it sits on.
180
+ */
181
+ export function hourMarks(window) {
182
+ const marks = [];
183
+ const formatter = new Intl.DateTimeFormat("en-IN", {
184
+ timeZone: "UTC",
185
+ hour: "numeric",
186
+ hour12: true,
187
+ });
188
+ const firstHour = Math.ceil(window.startMinute / 60);
189
+ const lastHour = Math.floor(window.endMinute / 60);
190
+ for (let hour = firstHour; hour <= lastHour; hour += 1) {
191
+ marks.push({
192
+ minute: hour * 60,
193
+ // A synthetic UTC instant formatted in UTC - the round trip exists only
194
+ // to borrow `Intl`'s "10 am" / "12 pm" spelling, not to convert anything.
195
+ label: formatter.format(new Date(Date.UTC(2000, 0, 1, hour % 24))),
196
+ });
197
+ }
198
+ return marks;
199
+ }
@@ -113,3 +113,7 @@ export { formatPrice, monthlyOf, resolveAction, annualSaving, discountLabel, ACT
113
113
  groupPlansByTier, resolvePlanGroup, } from "./components/plan-pricing.js";
114
114
  export { ConnectWorkspaceSwitcher } from "./components/workspace-switcher.js";
115
115
  export { useConnectWorkspaces, useConnectWorkspaceMembers } from "./provider.js";
116
+ export { ConnectBookingCalendar } from "./components/booking-calendar.js";
117
+ export { ConnectBookingDialog, ConnectBookingDetail } from "./components/booking-dialogs.js";
118
+ export { useBookableEventTypes, useAvailableSlots, useBookings, useBookingActions, } from "./use-scheduling.js";
119
+ export { layoutBookings, dayColumns, zonedInstant, } from "./components/booking-grid.js";