Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 89 additions & 4 deletions docs/content/docs/plugins/calendar.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ rules: ({ calendar }) => [
facts.tokenValid || identity?.id === facts.hostId),
calendar.booking.cancel.when(({ identity, facts }) =>
facts.tokenValid || identity?.id === facts.hostId),
calendar.booking.reschedule.when(({ facts }) => facts.tokenValid),
calendar.booking.remind.when(({ identity, facts }) =>
identity?.id === facts.hostId),
],
Expand All @@ -102,7 +103,8 @@ rules: ({ calendar }) => [
The backend derives `hostId` from the authenticated request identity for host
operations. Trusted server jobs may explicitly supply `hostId` when creating
event types or listing a host's records. Keep cancellation URLs private: anyone
holding the token can view and cancel that booking.
holding the token can view, cancel, or reschedule that booking. Rescheduling uses
the same private `cancelToken`; a booking ID alone does not grant access.

## Availability and limits

Expand All @@ -116,14 +118,68 @@ holding the token can view and cancel that booking.
- `capacity` limits attendees sharing a slot. Existing host appointments
also prevent overlapping bookings across event types.
- `limits` accepts optional `perHour`, `perDay`, `perWeek`, and `total`
positive counts per event type. Counts include each confirmed attendee
positive counts per event type. Counts include each confirmed or pending-payment attendee
reservation, using calendar periods in the host timezone; `total` counts
all confirmed reservations. Cancellations release availability and limits.
all active reservations. Cancellations release availability and limits.

The public page interprets the selected date in the visitor's selected timezone
and displays slot times there. The backend validates the slot again on booking,
including availability, capacity, limits, and whether its start is in the future.

### External busy intervals

Pass an optional `getBusyIntervals(hostId, range)` callback in
`CalendarBackendConfig` (also exported as `CalendarBackendOptions`):

```ts
calendarBackendPlugin({
getBusyIntervals: async (hostId, range) => {
const events = await externalCalendar.listBusy(hostId, range)
return events.map((event) => ({
start: new Date(event.start),
end: new Date(event.end),
}))
},
})
```

Both the requested range and returned intervals use absolute `Date` instants,
with exclusive ends. The range includes padding for viewer timezone offsets and
event duration; query all external events overlapping it. Any overlap blocks a
slot, including partial overlaps. Adjacent intervals do not block one another.
Booking and rescheduling fetch busy intervals again inside the host transaction.
Provider failures or invalid intervals reject the request rather than showing or
reserving unchecked times. Your integration owns credentials and provider access;
external calendar changes cannot be locked by the BTST database transaction.

### Prices and payment holds

Event types accept optional `price` and `currency` fields. Supply both or neither:
`price` is a nonnegative integer in minor currency units (`2500` means USD 25.00),
and `currency` is a three-letter uppercase currency code such as `USD`. Omit both
or set both to `null` to remove pricing. A zero price creates a free booking.
Existing databases need the two nullable columns on `calendarEventType`.

Positive prices create `pending_payment` bookings. These hold capacity, block
overlapping host events, and count toward booking limits just like confirmed
bookings. They can be rescheduled or cancelled using the private booking token.
Rescheduling preserves their payment status. Pending bookings do not fire
confirmation hooks or qualify for confirmed-booking reminders.

After your application verifies payment with its provider, its trusted webhook or
server job can confirm the hold:

```ts
await myStack.trusted.calendar.confirmBookingPayment({ id: bookingId })
```

This operation has the `calendar.booking.confirmPayment` permission descriptor,
has no HTTP route, and rejects request-scoped calls. It confirms under the host
lock and fires `onAfterConfirmBooking` once for the transition; repeated calls
are idempotent. A cancelled hold cannot be confirmed. Your application owns
checkout, verified webhook handling, and cancellation of abandoned holds. There
is no automatic payment expiry or payment-provider integration.

## Routes

With `site.basePath: "/pages"`, the client registers:
Expand All @@ -135,6 +191,7 @@ With `site.basePath: "/pages"`, the client registers:
| `/pages/calendar/events/:id/edit` | Edit availability, limits, and event details |
| `/pages/calendar/book/:slug` | Public booking page |
| `/pages/calendar/cancel/:token` | Booking details and cancellation |
| `/pages/calendar/reschedule/:token` | Choose a replacement time with the booking token |

API routes are relative to `api.basePath`, for example `/api/data`:

Expand All @@ -148,20 +205,48 @@ API routes are relative to `api.basePath`, for example `/api/data`:
| GET | `/calendar/bookings?period=upcoming` | List host bookings; also accepts `past` or `all` |
| POST | `/calendar/bookings/:id/cancel` | Cancel a booking as its owning host |
| GET, POST | `/calendar/cancel/:token` | Read or cancel a booking using its token |
| GET | `/calendar/reschedule/:token/slots?date=YYYY-MM-DD&timezone=UTC` | Available replacement times, excluding this booking's reservation |
| POST | `/calendar/reschedule/:token` | Move the booking using `{ start, timezone }` |

Slot responses contain `{ date, timezone, slots }`; each slot has UTC `start`
and `end` timestamps and a `remaining` capacity. A confirmed booking includes
its `cancelToken`. Show or deliver the cancellation link to the attendee. Host
dashboard responses omit the token value; hosts cancel through the protected
booking ID endpoint.

## Rescheduling and calendar invites

The confirmation links to booking management, where an attendee can reschedule
an upcoming active booking. A successful move keeps the booking ID and token and
releases the previous time. A failed move leaves the original booking intact.
The replacement is validated with the same host lock, external busy intervals,
timezone rules, group capacity and limits as a new booking. The existing booking
is excluded from those counts during replacement validation. Cancelled or past
bookings cannot be moved; deactivated event types offer no replacement times.

Confirmation, booking management, the host dashboard and reschedule confirmation
provide a **Download calendar invite (.ics)** link. The file uses UTC instants
(including across DST changes), a stable booking UID, escaped text and folded
UTF-8 lines following [RFC 5545](https://www.rfc-editor.org/rfc/rfc5545).
Pending holds export as `TENTATIVE`; cancelled bookings export as `CANCELLED`.
Files contain no booking token. Downloads are manual snapshots, not calendar
subscriptions or automatic update notifications. Server applications can also
import `generateBookingInvite(booking)` from `@btst/plugin-calendar/api`; the
client entry is `@btst/plugin-calendar/client/hooks`.

## Lifecycle hooks and reminders

Pass hooks to `calendarBackendPlugin({ hooks })` to connect confirmation and
cancellation to your own email or notification service. `onAfterConfirmBooking`
receives the confirmed booking, and `onAfterCancelBooking` receives the cancelled
booking. Hooks run after the corresponding booking write.

`onAfterRescheduleBooking(booking, previous)` receives the committed replacement
and original booking. Confirmed moves also fire `onAfterConfirmBooking`; moving a
pending-payment hold only fires the reschedule hook. Repeating a move with the
same instants and timezone fires neither hook. Post-commit hook failures do not
undo the reservation, so delivery and retry handling belong to the application.

Calendar does not run a scheduler or deliver email. From your application-owned
scheduled job, call:

Expand All @@ -180,5 +265,5 @@ keys from `@btst/plugin-calendar/query-keys`, and page components from
`btst-calendar` shadcn registry item and pass replacement pages through the client
plugin's `pageComponents` option.

Version 1 excludes round-robin assignment, external calendar sync, payments,
The plugin excludes round-robin assignment, automatic external calendar sync, payment processing,
video conferencing, recurring bookings, waitlists, and workflow automation.
122 changes: 118 additions & 4 deletions e2e/tests/smoke.calendar.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { expect, test } from "@playwright/test";
import { readFile } from "node:fs/promises";
import { mockAuthHeaders, setMockAuthCookie } from "./helpers/mock-auth";

test("guest books and cancels an appointment, releasing its capacity", async ({
test("guest books, downloads an invite, reschedules and cancels an appointment", async ({
page,
request,
}) => {
Expand All @@ -16,7 +17,7 @@ test("guest books and cancels an appointment, releasing its capacity", async ({
capacity: 1,
timezone: "UTC",
weeklyAvailability: [],
dateOverrides: [{ date, intervals: [{ start: "09:00", end: "09:30" }] }],
dateOverrides: [{ date, intervals: [{ start: "09:00", end: "10:00" }] }],
},
});
expect(created.ok(), await created.text()).toBe(true);
Expand All @@ -33,7 +34,7 @@ test("guest books and cancels an appointment, releasing its capacity", async ({
await page.goto(`/pages/calendar/book/${slug}`);
await page.getByLabel("Timezone", { exact: true }).selectOption("UTC");
await page.getByLabel("Date", { exact: true }).fill(date);
await page.getByTestId("calendar-slot").click();
await page.getByTestId("calendar-slot").first().click();
await page
.getByLabel("Your name", { exact: true })
.fill("Calendar attendee");
Expand All @@ -48,9 +49,45 @@ test("guest books and cancels an appointment, releasing its capacity", async ({
).toBeVisible();
const bookedSlots = await request.get(slotsPath);
expect(bookedSlots.ok()).toBe(true);
expect((await bookedSlots.json()).slots).toEqual([]);
expect((await bookedSlots.json()).slots).toHaveLength(1);
const inviteDownload = page.waitForEvent("download");
await page
.getByRole("link", { name: "Download calendar invite (.ics)" })
.click();
const invite = await inviteDownload;
expect(invite.suggestedFilename()).toBe("booking.ics");
expect(await readFile((await invite.path())!, "utf8")).toContain(
`DTSTART:${date.replaceAll("-", "")}T090000Z`,
);

await page.getByRole("link", { name: "Manage or cancel booking" }).click();
await expect(page).toHaveURL(/\/calendar\/cancel\//);
const managementURL = page.url();
await page
.getByRole("link", { name: "Reschedule booking", exact: true })
.click();
await page
.getByLabel("Timezone", { exact: true })
.selectOption("America/New_York");
await page.getByTestId("calendar-slot").last().click();
await page.getByRole("button", { name: "Confirm new time" }).click();
await expect(
page.getByRole("heading", { name: "Booking rescheduled", exact: true }),
).toBeVisible();
const updatedDownload = page.waitForEvent("download");
await page
.getByRole("link", { name: "Download calendar invite (.ics)" })
.click();
expect(
await readFile((await (await updatedDownload).path())!, "utf8"),
).toContain(`DTSTART:${date.replaceAll("-", "")}T093000Z`);
await page
.getByRole("link", { name: "Manage booking", exact: true })
.click();
await expect(page).toHaveURL(managementURL);
await expect(
page.getByText("America/New_York", { exact: false }),
).toBeVisible();
await page
.getByRole("button", { name: "Cancel booking", exact: true })
.click();
Expand All @@ -65,6 +102,11 @@ test("guest books and cancels an appointment, releasing its capacity", async ({
end: `${date}T09:30:00.000Z`,
remaining: 1,
},
{
start: `${date}T09:30:00.000Z`,
end: `${date}T10:00:00.000Z`,
remaining: 1,
},
]);
await page.goto("/pages/calendar/cancel/invalid-calendar-token");
await expect(
Expand All @@ -82,3 +124,75 @@ test("guest books and cancels an appointment, releasing its capacity", async ({
});
}
});

test("paid booking holds a time and shows pending payment in guest and host management", async ({
page,
request,
}) => {
const slug = `calendar-paid-${Date.now()}`;
const date = new Date(Date.now() + 8 * 86_400_000).toISOString().slice(0, 10);
const response = await request.post("/api/data/calendar/events", {
headers: mockAuthHeaders(),
data: {
slug,
name: "Paid calendar appointment",
duration: 30,
timezone: "UTC",
price: 2500,
currency: "USD",
weeklyAvailability: [],
dateOverrides: [{ date, intervals: [{ start: "09:00", end: "09:30" }] }],
},
});
expect(response.ok(), await response.text()).toBe(true);
const event = await response.json();
try {
await page.goto(`/pages/calendar/book/${slug}`);
await page.getByLabel("Timezone", { exact: true }).selectOption("UTC");
await page.getByLabel("Date", { exact: true }).fill(date);
await expect(page.getByText(/Price:.*25\.00/)).toBeVisible();
await page.getByTestId("calendar-slot").click();
await page.getByLabel("Your name", { exact: true }).fill("Paid attendee");
await page
.getByLabel("Email", { exact: true })
.fill("paid-calendar@example.com");
await page.getByRole("button", { name: "Reserve pending payment" }).click();
await expect(
page.getByRole("heading", { name: "Booking awaiting payment" }),
).toBeVisible();
expect(
(
await (
await request.get(
`/api/data/calendar/book/${slug}/slots?date=${date}&timezone=UTC`,
)
).json()
).slots,
).toEqual([]);
await page.getByRole("link", { name: "Manage or cancel booking" }).click();
await expect(page).toHaveURL(/\/calendar\/cancel\//);
const token = page.url().split("/").at(-1)!;
await expect(
page.getByText(/Payment pending\. Your time is held/),
).toBeVisible();
await setMockAuthCookie(page.context());
await page.goto("/pages/calendar");
const row = page
.getByRole("listitem")
.filter({
has: page.getByRole("heading", { name: "Paid calendar appointment" }),
})
.filter({ hasText: "paid-calendar@example.com" });
await expect(
row.getByText("Payment pending", { exact: true }),
).toBeVisible();
await expect(
row.getByRole("link", { name: "Download calendar invite (.ics)" }),
).toBeVisible();
await request.post(`/api/data/calendar/cancel/${token}`);
} finally {
await request.delete(`/api/data/calendar/events/${event.id}`, {
headers: mockAuthHeaders(),
});
}
});
Loading
Loading