diff --git a/docs/content/docs/plugins/calendar.mdx b/docs/content/docs/plugins/calendar.mdx index 31ea79f2b..96cfa4531 100644 --- a/docs/content/docs/plugins/calendar.mdx +++ b/docs/content/docs/plugins/calendar.mdx @@ -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), ], @@ -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 @@ -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: @@ -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`: @@ -148,6 +205,8 @@ 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 @@ -155,6 +214,26 @@ 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 @@ -162,6 +241,12 @@ 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: @@ -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. diff --git a/e2e/tests/smoke.calendar.spec.ts b/e2e/tests/smoke.calendar.spec.ts index 4ed688e20..0503f0e00 100644 --- a/e2e/tests/smoke.calendar.spec.ts +++ b/e2e/tests/smoke.calendar.spec.ts @@ -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, }) => { @@ -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); @@ -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"); @@ -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(); @@ -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( @@ -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(), + }); + } +}); diff --git a/packages/plugin-calendar/src/__tests__/plugin.test.ts b/packages/plugin-calendar/src/__tests__/plugin.test.ts index 8c1378d74..905beb0ff 100644 --- a/packages/plugin-calendar/src/__tests__/plugin.test.ts +++ b/packages/plugin-calendar/src/__tests__/plugin.test.ts @@ -5,7 +5,12 @@ import { z } from "zod"; import { createBackendStack } from "@btst/stack/api"; import { defineAuthorization } from "@btst/stack/authorization"; import { createServerAuth } from "@btst/stack/authorization/server"; -import { calendarBackendPlugin, type CalendarBackendHooks } from "../api"; +import { + calendarBackendPlugin, + generateBookingInvite, + type CalendarBackendHooks, + type CalendarBackendConfig, +} from "../api"; import { calendarPermissions } from "../permissions"; import type { Booking, EventType } from "../types"; @@ -38,14 +43,21 @@ const authorization = defineAuthorization({ calendar.booking.remind.when( ({ identity, facts }) => identity?.id === facts.hostId, ), + calendar.booking.reschedule.when(({ facts }) => facts.tokenValid), + calendar.booking.confirmPayment.when( + ({ identity, facts }) => identity?.id === facts.hostId, + ), ], }); -function setup(hooks?: CalendarBackendHooks) { +function setup( + hooks?: CalendarBackendHooks, + getBusyIntervals?: CalendarBackendConfig["getBusyIntervals"], +) { let adapter!: DBAdapter; const stack = createBackendStack({ basePath: "/api/data", - plugins: { calendar: calendarBackendPlugin({ hooks }) }, + plugins: { calendar: calendarBackendPlugin({ hooks, getBusyIntervals }) }, adapter: (db) => { adapter = createMemoryAdapter(db)({}); return adapter; @@ -672,4 +684,471 @@ describe("Calendar API", () => { .status, ).toBe(503); }); + + it("reschedules by token atomically, excludes itself from limits, and reports previous and confirmed times", async () => { + const confirmed = vi.fn(); + const moved = vi.fn(); + const { stack, request } = setup({ + onAfterConfirmBooking: confirmed, + onAfterRescheduleBooking: moved, + }); + await request( + "/calendar/events", + "POST", + { ...eventInput, limits: { total: 1 } }, + "host", + ); + const booking = (await ( + await request("/calendar/book/consultation", "POST", attendee()) + ).json()) as Booking; + const path = `/calendar/reschedule/${booking.cancelToken}`; + expect( + ( + await request(`/calendar/reschedule/${booking.id}`, "POST", { + start: "2030-01-07T10:00:00Z", + timezone: "UTC", + }) + ).status, + ).toBe(404); + expect( + (await request(`${path}/slots?date=2030-01-07&timezone=UTC`)).status, + ).toBe(200); + const result = await request(path, "POST", { + start: "2030-01-07T05:00:00-05:00", + timezone: "America/New_York", + }); + expect(result.status).toBe(200); + const rescheduled = await result.json(); + expect(rescheduled).toMatchObject({ + id: booking.id, + cancelToken: booking.cancelToken, + start: "2030-01-07T10:00:00.000Z", + end: "2030-01-07T10:30:00.000Z", + timezone: "America/New_York", + status: "confirmed", + }); + expect(moved).toHaveBeenCalledWith(rescheduled, booking); + expect(confirmed).toHaveBeenCalledTimes(2); + await stack.trusted.calendar.rescheduleBooking({ + token: booking.cancelToken, + start: rescheduled.start, + timezone: rescheduled.timezone, + }); + expect(moved).toHaveBeenCalledTimes(1); + expect(confirmed).toHaveBeenCalledTimes(2); + expect( + (await request(path, "POST", { start: "bad", timezone: "UTC" })).status, + ).toBe(400); + expect( + ( + await request(path, "POST", { + start: "2030-01-07T10:01:00Z", + timezone: "UTC", + }) + ).status, + ).toBe(409); + expect( + (await (await request(`/calendar/cancel/${booking.cancelToken}`)).json()) + .start, + ).toBe(rescheduled.start); + await request(`/calendar/cancel/${booking.cancelToken}`, "POST"); + expect( + ( + await request(path, "POST", { + start: "2030-01-07T11:00:00Z", + timezone: "UTC", + }) + ).status, + ).toBe(409); + }); + + it("locks reschedules against concurrent new reservations and preserves the losing booking", async () => { + const { request } = setup(); + await request("/calendar/events", "POST", eventInput, "host"); + await request( + "/calendar/events", + "POST", + { ...eventInput, slug: "other-event" }, + "host", + ); + const original = (await ( + await request("/calendar/book/consultation", "POST", attendee()) + ).json()) as Booking; + const results = await Promise.all([ + request(`/calendar/reschedule/${original.cancelToken}`, "POST", { + start: "2030-01-07T10:00:00Z", + timezone: "UTC", + }), + request( + "/calendar/book/other-event", + "POST", + attendee("2030-01-07T10:00:00Z", "other@example.com"), + ), + ]); + expect(results.map((r) => r.status).sort()).toEqual([200, 409]); + const current = (await ( + await request(`/calendar/cancel/${original.cancelToken}`) + ).json()) as Booking; + expect(current.start).toBe( + results[0]!.status === 200 ? "2030-01-07T10:00:00.000Z" : original.start, + ); + const otherTime = + current.start === original.start + ? "2030-01-07T10:00:00Z" + : "2030-01-07T11:00:00Z"; + if (results[0]!.status === 200) + await request( + "/calendar/book/other-event", + "POST", + attendee(otherTime, "taken@example.com"), + ); + expect( + ( + await request(`/calendar/reschedule/${original.cancelToken}`, "POST", { + start: otherTime, + timezone: "UTC", + }) + ).status, + ).toBe(409); + expect( + (await (await request(`/calendar/cancel/${original.cancelToken}`)).json()) + .start, + ).toBe(current.start); + }); + + it("rechecks external busy intervals during booking and moving, respecting exclusive boundaries and viewer timezones", async () => { + let busy = [ + { + start: new Date("2030-01-07T09:30:00Z"), + end: new Date("2030-01-07T10:00:00Z"), + }, + ]; + const getBusy = vi.fn(() => busy); + const { request } = setup(undefined, getBusy); + await request("/calendar/events", "POST", eventInput, "host"); + const slots = await ( + await request( + "/calendar/book/consultation/slots?date=2030-01-07&timezone=America%2FNew_York", + ) + ).json(); + expect(slots.slots.map((slot: { start: string }) => slot.start)).toContain( + "2030-01-07T09:00:00.000Z", + ); + expect( + slots.slots.map((slot: { start: string }) => slot.start), + ).not.toContain("2030-01-07T09:30:00.000Z"); + expect(slots.slots.map((slot: { start: string }) => slot.start)).toContain( + "2030-01-07T10:00:00.000Z", + ); + expect(getBusy).toHaveBeenCalledWith("host", { + start: new Date("2030-01-06T00:00:00Z"), + end: new Date("2030-01-09T00:30:00Z"), + }); + const original = (await ( + await request("/calendar/book/consultation", "POST", attendee()) + ).json()) as Booking; + busy = [ + { + start: new Date("2030-01-07T10:10:00Z"), + end: new Date("2030-01-07T10:20:00Z"), + }, + ]; + expect( + ( + await request( + "/calendar/book/consultation", + "POST", + attendee("2030-01-07T10:00:00Z", "other@example.com"), + ) + ).status, + ).toBe(409); + expect( + ( + await request(`/calendar/reschedule/${original.cancelToken}`, "POST", { + start: "2030-01-07T10:00:00Z", + timezone: "UTC", + }) + ).status, + ).toBe(409); + expect( + (await (await request(`/calendar/cancel/${original.cancelToken}`)).json()) + .start, + ).toBe(original.start); + }); + + it("fails closed when an external calendar throws or returns an invalid interval", async () => { + const getBusy = vi.fn< + NonNullable + >(() => { + throw new Error("External calendar unavailable"); + }); + const { request } = setup(undefined, getBusy); + await request("/calendar/events", "POST", eventInput, "host"); + expect( + ( + await request( + "/calendar/book/consultation/slots?date=2030-01-07&timezone=UTC", + ) + ).status, + ).toBe(500); + expect( + (await request("/calendar/book/consultation", "POST", attendee())).status, + ).toBe(500); + getBusy.mockReturnValue([ + { + start: new Date("2030-01-07T10:00:00Z"), + end: new Date("2030-01-07T09:00:00Z"), + }, + ]); + expect( + (await request("/calendar/book/consultation", "POST", attendee())).ok, + ).toBe(false); + expect( + await ( + await request("/calendar/bookings", "GET", undefined, "host") + ).json(), + ).toEqual([]); + }); + + it("holds capacity and limits for paid bookings, preserves payment state on moves, and confirms only from trusted payment handlers", async () => { + const confirmed = vi.fn(); + const moved = vi.fn(); + const { request, stack } = setup({ + onAfterConfirmBooking: confirmed, + onAfterRescheduleBooking: moved, + }); + const event = (await ( + await request( + "/calendar/events", + "POST", + { ...eventInput, price: 2500, currency: "USD", limits: { total: 1 } }, + "host", + ) + ).json()) as EventType; + const booking = (await ( + await request("/calendar/book/consultation", "POST", attendee()) + ).json()) as Booking; + expect(booking.status).toBe("pending_payment"); + expect(confirmed).not.toHaveBeenCalled(); + await expect( + stack.trusted.calendar.remindBooking({ id: booking.id }), + ).rejects.toMatchObject({ statusCode: 409 }); + expect( + ( + await request( + "/calendar/book/consultation", + "POST", + attendee("2030-01-07T10:00:00Z", "other@example.com"), + ) + ).status, + ).toBe(409); + expect( + ( + await request( + `/calendar/events/${event.id}`, + "DELETE", + undefined, + "host", + ) + ).status, + ).toBe(409); + const result = await request( + `/calendar/reschedule/${booking.cancelToken}`, + "POST", + { start: "2030-01-07T10:00:00Z", timezone: "UTC" }, + ); + expect(await result.json()).toMatchObject({ + status: "pending_payment", + id: booking.id, + }); + expect(moved).toHaveBeenCalledTimes(1); + expect(confirmed).not.toHaveBeenCalled(); + await expect( + stack + .forRequest( + new Request("http://localhost", { headers: { "x-host": "host" } }), + ) + .operations.calendar.confirmBookingPayment({ id: booking.id }), + ).rejects.toMatchObject({ statusCode: 403 }); + await stack.trusted.calendar.confirmBookingPayment({ id: booking.id }); + await stack.trusted.calendar.confirmBookingPayment({ id: booking.id }); + expect(confirmed).toHaveBeenCalledTimes(1); + await request(`/calendar/cancel/${booking.cancelToken}`, "POST"); + await expect( + stack.trusted.calendar.confirmBookingPayment({ id: booking.id }), + ).rejects.toMatchObject({ statusCode: 409 }); + expect( + ( + await request( + "/calendar/book/consultation", + "POST", + attendee("2030-01-07T11:00:00Z"), + ) + ).status, + ).toBe(200); + }); + + it("validates price and currency together and clears optional pricing on update", async () => { + const { request } = setup(); + for (const pricing of [ + { price: -1, currency: "USD" }, + { price: 1.5, currency: "USD" }, + { price: 500 }, + { currency: "USD" }, + { price: 500, currency: "usd" }, + ]) { + expect( + ( + await request( + "/calendar/events", + "POST", + { ...eventInput, ...pricing }, + "host", + ) + ).status, + ).toBe(400); + } + const event = (await ( + await request( + "/calendar/events", + "POST", + { ...eventInput, price: 500, currency: "USD" }, + "host", + ) + ).json()) as EventType; + const response = await request( + `/calendar/events/${event.id}`, + "PATCH", + eventInput, + "host", + ); + expect(await response.json()).toMatchObject({ + price: null, + currency: null, + }); + expect( + await ( + await request("/calendar/book/consultation", "POST", attendee()) + ).json(), + ).toMatchObject({ status: "confirmed" }); + }); + + it("serializes paid holds, protects their capacity during edits, and releases a cancelled hold", async () => { + const { request } = setup(); + const input = { ...eventInput, price: 500, currency: "USD", capacity: 2 }; + const event = (await ( + await request("/calendar/events", "POST", input, "host") + ).json()) as EventType; + const results = await Promise.all( + ["a", "b", "c"].map((guest) => + request( + "/calendar/book/consultation", + "POST", + attendee(undefined, `${guest}@example.com`), + ), + ), + ); + expect(results.map((result) => result.status).sort()).toEqual([ + 200, 200, 409, + ]); + const hold = (await results.find((result) => result.ok)!.json()) as Booking; + expect(hold.status).toBe("pending_payment"); + expect( + ( + await request( + `/calendar/events/${event.id}`, + "PATCH", + { ...input, capacity: 1 }, + "host", + ) + ).status, + ).toBe(409); + await request(`/calendar/cancel/${hold.cancelToken}`, "POST"); + expect( + ( + await request( + "/calendar/book/consultation", + "POST", + attendee(undefined, "replacement@example.com"), + ) + ).status, + ).toBe(200); + }); + + it("reschedules between repeated DST instants and rejects moving a booking after its start", async () => { + const { request } = setup(); + await request( + "/calendar/events", + "POST", + { + ...eventInput, + timezone: "America/New_York", + weeklyAvailability: [], + dateOverrides: [ + { date: "2030-11-03", intervals: [{ start: "01:30", end: "02:00" }] }, + ], + }, + "host", + ); + const original = (await ( + await request("/calendar/book/consultation", "POST", { + ...attendee("2030-11-03T01:30:00-04:00"), + timezone: "America/New_York", + }) + ).json()) as Booking; + const result = await request( + `/calendar/reschedule/${original.cancelToken}`, + "POST", + { start: "2030-11-03T01:30:00-05:00", timezone: "America/New_York" }, + ); + expect(result.status).toBe(200); + expect(await result.json()).toMatchObject({ + start: "2030-11-03T06:30:00.000Z", + end: "2030-11-03T07:00:00.000Z", + }); + vi.setSystemTime(new Date("2030-11-03T06:30:00Z")); + expect( + ( + await request(`/calendar/reschedule/${original.cancelToken}`, "POST", { + start: "2030-11-03T06:30:00Z", + timezone: "UTC", + }) + ).status, + ).toBe(409); + }); + + it("exports UTC calendar invites with escaped text, UTF-8 folding, and stable IDs after moving", () => { + const booking = { + id: "booking-1", + eventName: "Consultation, notes; \\ room\r\n" + "đź—“Ă©".repeat(40), + start: "2030-11-03T01:30:00-05:00", + end: "2030-11-03T02:00:00-05:00", + createdAt: "2030-01-01T00:00:00Z", + status: "confirmed" as const, + cancelToken: "private", + }; + const invite = generateBookingInvite(booking); + const unfolded = invite.replace(/\r\n /g, ""); + expect(unfolded).toContain( + "DTSTART:20301103T063000Z\r\nDTEND:20301103T070000Z\r\n", + ); + expect(unfolded).toContain("SUMMARY:Consultation\\, notes\\; \\\\ room\\n"); + expect(invite).not.toContain("private"); + expect(invite).not.toContain("ďż˝"); + for (const line of invite.split("\r\n")) + expect(new TextEncoder().encode(line).length).toBeLessThanOrEqual(75); + expect( + generateBookingInvite({ + ...booking, + start: "2030-11-04T09:00:00Z", + status: "pending_payment", + }), + ).toContain("STATUS:TENTATIVE\r\n"); + expect( + generateBookingInvite({ ...booking, status: "cancelled" }), + ).toContain("STATUS:CANCELLED\r\n"); + expect( + generateBookingInvite({ ...booking, start: "2030-11-04T09:00:00Z" }), + ).toContain("UID:booking-1@btst-calendar\r\n"); + }); }); diff --git a/packages/plugin-calendar/src/api/index.ts b/packages/plugin-calendar/src/api/index.ts index b194cd512..1921d838e 100644 --- a/packages/plugin-calendar/src/api/index.ts +++ b/packages/plugin-calendar/src/api/index.ts @@ -2,6 +2,7 @@ export { calendarBackendPlugin, type CalendarApiRouter } from "./plugin"; export type { CalendarBackendHooks, CalendarBackendOptions, + CalendarBackendConfig, } from "./operations"; export { calendarSchema } from "../db"; export * from "../types"; @@ -19,4 +20,7 @@ export { deleteEventType, createBooking, cancelBooking, + rescheduleBooking, + confirmBookingPayment, } from "./mutations"; +export { generateBookingInvite } from "../ical"; diff --git a/packages/plugin-calendar/src/api/mutations.ts b/packages/plugin-calendar/src/api/mutations.ts index 9743cfb4a..a88fe9881 100644 --- a/packages/plugin-calendar/src/api/mutations.ts +++ b/packages/plugin-calendar/src/api/mutations.ts @@ -84,6 +84,8 @@ export async function withHostTransaction( function eventData(input: z.output) { return { ...input, + price: input.price ?? null, + currency: input.currency ?? null, weeklyAvailability: JSON.stringify(input.weeklyAvailability), dateOverrides: JSON.stringify(input.dateOverrides), limits: JSON.stringify(input.limits), @@ -138,6 +140,7 @@ export async function deleteEventType( export async function createBooking( adapter: CalendarDataAdapter, input: Omit, + status: "confirmed" | "pending_payment" = "confirmed", ) { return serializeBooking( await adapter.create({ @@ -146,7 +149,7 @@ export async function createBooking( ...input, start: new Date(input.start), end: new Date(input.end), - status: "confirmed", + status, cancelToken: crypto.randomUUID() + crypto.randomUUID(), createdAt: new Date(), }, @@ -154,6 +157,24 @@ export async function createBooking( ); } +/** Lower-level write: callers own validation, authorization, transaction and lifecycle. */ +export async function rescheduleBooking( + adapter: CalendarDataAdapter, + id: string, + input: Pick, +) { + const row = await adapter.update({ + model: "calendarBooking", + where: [{ field: "id", value: id, operator: "eq" }], + update: { + ...input, + start: new Date(input.start), + end: new Date(input.end), + }, + }); + return row ? serializeBooking(row) : null; +} + /** Lower-level write: callers own validation, authorization, transaction and lifecycle. */ export async function cancelBooking(adapter: CalendarDataAdapter, id: string) { const row = await adapter.update({ @@ -163,3 +184,16 @@ export async function cancelBooking(adapter: CalendarDataAdapter, id: string) { }); return row ? serializeBooking(row) : null; } + +/** Lower-level write: callers own payment verification, validation, authorization, transaction and lifecycle. */ +export async function confirmBookingPayment( + adapter: CalendarDataAdapter, + id: string, +) { + const row = await adapter.update({ + model: "calendarBooking", + where: [{ field: "id", value: id, operator: "eq" }], + update: { status: "confirmed" }, + }); + return row ? serializeBooking(row) : null; +} diff --git a/packages/plugin-calendar/src/api/operations.ts b/packages/plugin-calendar/src/api/operations.ts index 1bb9d81b4..1623fbef0 100644 --- a/packages/plugin-calendar/src/api/operations.ts +++ b/packages/plugin-calendar/src/api/operations.ts @@ -11,9 +11,10 @@ import { createBookingSchema, createEventTypeSchema, listBookingsQuerySchema, + rescheduleBookingSchema, } from "../schemas"; import { calculateAvailability, dateInTimezone } from "../scheduling"; -import type { Booking, EventType } from "../types"; +import type { Booking, BusyInterval, EventType } from "../types"; import { getBookingById, getBookingByToken, @@ -36,6 +37,10 @@ export type CalendarBackendHooks = { onAfterCancelBooking?: ( booking: DeepReadonly, ) => Promise | void; + onAfterRescheduleBooking?: ( + booking: DeepReadonly, + previous: DeepReadonly, + ) => Promise | void; onBeforeRemindBooking?: ( booking: DeepReadonly, ) => Promise | void; @@ -45,12 +50,21 @@ export type CalendarBackendHooks = { }; /** Calendar configuration; adapters must advertise enabled transaction support. */ -export type CalendarBackendOptions = { hooks?: CalendarBackendHooks }; +export type CalendarBackendConfig = { + hooks?: CalendarBackendHooks; + /** Return external occupancy for the host over the supplied UTC range. Errors fail closed. */ + getBusyIntervals?: ( + hostId: string, + range: BusyInterval, + ) => readonly BusyInterval[] | Promise; +}; +/** Backwards-compatible name for calendar backend configuration. */ +export type CalendarBackendOptions = CalendarBackendConfig; const hostInput = z.object({ hostId: z.string().min(1).optional() }); const idInput = z.object({ id: z.string().min(1) }); const slugInput = z.object({ slug: z.string().min(1) }); -export const createEventTypeOperationSchema = createEventTypeSchema.extend({ +export const createEventTypeOperationSchema = createEventTypeSchema.safeExtend({ hostId: z.string().min(1).optional(), }); export const updateEventTypeOperationSchema = idInput.extend({ @@ -136,6 +150,46 @@ export function createCalendarOperations( options: CalendarBackendOptions, ) { const cancelled = new WeakSet(); + const rescheduled = new WeakMap(); + const paymentConfirmed = new WeakSet(); + async function availability( + event: EventType, + bookings: Booking[], + date: string, + timezone: string, + ) { + const day = Date.parse(`${date}T00:00:00Z`); + const busy = options.getBusyIntervals + ? await options.getBusyIntervals(event.hostId, { + start: new Date(day - 86_400_000), + end: new Date(day + 2 * 86_400_000 + event.duration * 60_000), + }) + : []; + const intervals = z + .array( + z + .object({ start: z.date(), end: z.date() }) + .refine((interval) => interval.end > interval.start), + ) + .parse(busy); + return calculateAvailability( + event, + bookings, + date, + timezone, + new Date(), + intervals, + ); + } + async function movableBooking(tx: CalendarDataAdapter, token: string) { + const booking = await requireBooking(tx, token); + if ( + booking.status === "cancelled" || + Date.parse(booking.start) <= Date.now() + ) + failure(409, "Only upcoming active bookings can be rescheduled"); + return booking; + } async function cancelReservation( input: object, bookingId: string, @@ -218,7 +272,7 @@ export function createCalendarOperations( for (const booking of bookings) { if ( booking.eventTypeId !== input.id || - booking.status !== "confirmed" || + booking.status === "cancelled" || Date.parse(booking.end) <= Date.now() ) continue; @@ -253,7 +307,7 @@ export function createCalendarOperations( bookings.some( (booking) => booking.eventTypeId === input.id && - booking.status === "confirmed" && + booking.status !== "cancelled" && Date.parse(booking.end) > Date.now(), ) ) @@ -272,7 +326,7 @@ export function createCalendarOperations( eventFacts(await requirePublicEvent(adapter, input.slug)), execute: async ({ input }) => { const event = await requirePublicEvent(adapter, input.slug); - return calculateAvailability( + return availability( event, await listHostBookings(adapter, event.hostId), input.date, @@ -295,13 +349,13 @@ export function createCalendarOperations( failure(409, "Event type changed"); const bookings = await listHostBookings(tx, event.hostId); const start = new Date(input.start).toISOString(); - const availability = calculateAvailability( + const available = await availability( event, bookings, dateInTimezone(start, input.timezone), input.timezone, ); - const slot = availability.slots.find( + const slot = available.slots.find( (candidate) => candidate.start === start, ); if (!slot) @@ -315,24 +369,155 @@ export function createCalendarOperations( (booking) => booking.eventTypeId === event.id && booking.start === start && - booking.status === "confirmed" && + booking.status !== "cancelled" && booking.email === input.email, ) ) failure(409, "This email already has a reservation for this time"); - return mutations.createBooking(tx, { - eventTypeId: event.id, - hostId: event.hostId, - eventName: event.name, - start: slot.start, - end: slot.end, - timezone: input.timezone, - name: input.name, - email: input.email, - }); + return mutations.createBooking( + tx, + { + eventTypeId: event.id, + hostId: event.hostId, + eventName: event.name, + start: slot.start, + end: slot.end, + timezone: input.timezone, + name: input.name, + email: input.email, + }, + (event.price ?? 0) > 0 ? "pending_payment" : "confirmed", + ); }), - after: async ({ result }) => - options.hooks?.onAfterConfirmBooking?.(result), + after: async ({ result }) => { + if (result.status === "confirmed") + await options.hooks?.onAfterConfirmBooking?.(result); + }, + }), + getRescheduleAvailability: defineOperation({ + input: tokenInput.extend(availabilityQuerySchema.shape), + permission: calendarPermissions.booking.reschedule, + facts: async ({ input }) => { + const booking = await requireBooking(adapter, input.token); + return { + bookingId: booking.id, + hostId: booking.hostId, + tokenValid: true, + }; + }, + execute: async ({ input }) => { + const booking = await movableBooking(adapter, input.token); + const event = await requireEvent(adapter, booking.eventTypeId); + return availability( + event, + (await listHostBookings(adapter, booking.hostId)).filter( + (item) => item.id !== booking.id, + ), + input.date, + input.timezone, + ); + }, + }), + rescheduleBooking: defineOperation({ + input: tokenInput.extend(rescheduleBookingSchema.shape), + permission: calendarPermissions.booking.reschedule, + facts: async ({ input }) => { + const booking = await requireBooking(adapter, input.token); + return { + bookingId: booking.id, + hostId: booking.hostId, + tokenValid: true, + }; + }, + execute: ({ input, facts }) => + mutations.withHostTransaction(adapter, facts.hostId, async (tx) => { + const booking = await movableBooking(tx, input.token); + if (booking.hostId !== facts.hostId || booking.id !== facts.bookingId) + failure(409, "Booking changed"); + const event = await requireEvent(tx, booking.eventTypeId); + assertHost(event, facts.hostId); + const bookings = (await listHostBookings(tx, facts.hostId)).filter( + (item) => item.id !== booking.id, + ); + const start = new Date(input.start).toISOString(); + const available = await availability( + event, + bookings, + dateInTimezone(start, input.timezone), + input.timezone, + ); + const slot = available.slots.find( + (candidate) => candidate.start === start, + ); + if (!slot) + failure( + 409, + "This time is no longer available", + "CALENDAR_SLOT_UNAVAILABLE", + ); + if ( + bookings.some( + (item) => + item.eventTypeId === event.id && + item.start === start && + item.status !== "cancelled" && + item.email === booking.email, + ) + ) + failure(409, "This email already has a reservation for this time"); + const result = + (await mutations.rescheduleBooking(tx, booking.id, { + start: slot.start, + end: slot.end, + timezone: input.timezone, + })) ?? failure(404, "Booking not found"); + if ( + booking.start !== result.start || + booking.end !== result.end || + booking.timezone !== result.timezone + ) + rescheduled.set(input, booking); + return result; + }), + after: async ({ input, result }) => { + const previous = rescheduled.get(input); + if (!previous) return; + await options.hooks?.onAfterRescheduleBooking?.(result, previous); + if (result.status === "confirmed") + await options.hooks?.onAfterConfirmBooking?.(result); + }, + }), + confirmBookingPayment: defineOperation({ + input: idInput, + permission: calendarPermissions.booking.confirmPayment, + facts: async ({ input }) => { + const booking = + (await getBookingById(adapter, input.id)) ?? + failure(404, "Booking not found"); + return { bookingId: booking.id, hostId: booking.hostId }; + }, + before: ({ request }) => { + if (request) + failure(403, "Only trusted payment handlers can confirm payment"); + }, + execute: ({ input, facts }) => + mutations.withHostTransaction(adapter, facts.hostId, async (tx) => { + const booking = + (await getBookingById(tx, input.id)) ?? + failure(404, "Booking not found"); + if (booking.hostId !== facts.hostId || booking.status === "cancelled") + failure(409, "Booking is no longer awaiting payment"); + if (booking.status === "confirmed") return booking; + const result = + (await mutations.confirmBookingPayment(tx, input.id)) ?? + failure(404, "Booking not found"); + paymentConfirmed.add(input); + return result; + }), + after: async ({ input, result }) => { + if (paymentConfirmed.has(input)) + await options.hooks?.onAfterConfirmBooking?.(result); + }, }), getBooking: defineOperation({ input: tokenInput, diff --git a/packages/plugin-calendar/src/api/plugin.ts b/packages/plugin-calendar/src/api/plugin.ts index 706d67ead..b08a4e6f3 100644 --- a/packages/plugin-calendar/src/api/plugin.ts +++ b/packages/plugin-calendar/src/api/plugin.ts @@ -5,6 +5,7 @@ import { createBookingSchema, createEventTypeSchema, listBookingsQuerySchema, + rescheduleBookingSchema, } from "../schemas"; import { createCalendarOperations, @@ -73,6 +74,22 @@ export const calendarBackendPlugin = (options: CalendarBackendOptions = {}) => { method: "GET", requireRequest: true }, operations.getBooking.route((ctx) => ({ token: ctx.params.token })), ), + getRescheduleAvailability: createEndpoint( + "/calendar/reschedule/:token/slots", + { method: "GET", query: availabilityQuerySchema, requireRequest: true }, + operations.getRescheduleAvailability.route((ctx) => ({ + token: ctx.params.token, + ...ctx.query, + })), + ), + rescheduleBooking: createEndpoint( + "/calendar/reschedule/:token", + { method: "POST", body: rescheduleBookingSchema, requireRequest: true }, + operations.rescheduleBooking.route((ctx) => ({ + token: ctx.params.token, + ...ctx.body, + })), + ), cancelBooking: createEndpoint( "/calendar/cancel/:token", { method: "POST", requireRequest: true }, diff --git a/packages/plugin-calendar/src/client/components/index.tsx b/packages/plugin-calendar/src/client/components/index.tsx index 69a15851b..0b3b38055 100644 --- a/packages/plugin-calendar/src/client/components/index.tsx +++ b/packages/plugin-calendar/src/client/components/index.tsx @@ -3,4 +3,5 @@ export { CalendarEventEditorPageComponent, CalendarBookingPageComponent, CalendarCancellationPageComponent, + CalendarReschedulePageComponent, } from "./pages"; diff --git a/packages/plugin-calendar/src/client/components/invite-download.tsx b/packages/plugin-calendar/src/client/components/invite-download.tsx new file mode 100644 index 000000000..2ad42d670 --- /dev/null +++ b/packages/plugin-calendar/src/client/components/invite-download.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { Button } from "@workspace/ui/components/button"; +import { generateBookingInvite } from "../hooks"; +import type { Booking } from "../../types"; + +export function CalendarInviteDownload({ + booking, +}: { + booking: Omit; +}) { + return ( + + ); +} diff --git a/packages/plugin-calendar/src/client/components/pages.tsx b/packages/plugin-calendar/src/client/components/pages.tsx index d3f3186ca..f379c8593 100644 --- a/packages/plugin-calendar/src/client/components/pages.tsx +++ b/packages/plugin-calendar/src/client/components/pages.tsx @@ -23,6 +23,11 @@ const Cancellation = lazy(() => default: m.CalendarCancellationPage, })), ); +const Reschedule = lazy(() => + import("./pages/reschedule").then((m) => ({ + default: m.CalendarReschedulePage, + })), +); const boundary = { ErrorComponent: CalendarError, @@ -79,3 +84,14 @@ export function CalendarCancellationPageComponent({ /> ); } + +export function CalendarReschedulePageComponent({ token }: { token: string }) { + return ( + + ); +} diff --git a/packages/plugin-calendar/src/client/components/pages/booking.tsx b/packages/plugin-calendar/src/client/components/pages/booking.tsx index e638fa26a..ac2405734 100644 --- a/packages/plugin-calendar/src/client/components/pages/booking.tsx +++ b/packages/plugin-calendar/src/client/components/pages/booking.tsx @@ -14,23 +14,16 @@ import { import { CalendarPage, Field, - calendarSelectClass, formatCalendarTime, + formatCalendarPrice, } from "../shared"; - -function today(timezone: string) { - return new Intl.DateTimeFormat("en-CA", { - timeZone: timezone, - year: "numeric", - month: "2-digit", - day: "2-digit", - }).format(new Date()); -} +import { CalendarInviteDownload } from "../invite-download"; +import { CalendarTimePicker, calendarToday } from "../time-picker"; export function CalendarBookingPage({ slug }: { slug: string }) { const { data: event } = usePublicCalendarEvent(slug); const [timezone, setTimezone] = useState(event.timezone); - const [date, setDate] = useState(() => today(event.timezone)); + const [date, setDate] = useState(() => calendarToday(event.timezone)); const [start, setStart] = useState(""); const [confirmation, setConfirmation] = useState(); const slots = useCalendarSlots(slug, date, timezone); @@ -39,11 +32,8 @@ export function CalendarBookingPage({ slug }: { slug: string }) { useEffect(() => { const localZone = Intl.DateTimeFormat().resolvedOptions().timeZone; setTimezone(localZone); - setDate(today(localZone)); + setDate(calendarToday(localZone)); }, []); - const zones = Array.from( - new Set([timezone, "UTC", ...Intl.supportedValuesOf("timeZone")]), - ); const chosenSlot = slots.data?.slots.find((slot) => slot.start === start); const submit = async (e: FormEvent) => { e.preventDefault(); @@ -67,8 +57,16 @@ export function CalendarBookingPage({ slug }: { slug: string }) {

- Booking confirmed + {confirmation.status === "pending_payment" + ? "Booking awaiting payment" + : "Booking confirmed"}

+ {confirmation.status === "pending_payment" && ( +

+ Your time is held while payment is pending. Contact the host to + complete payment. +

+ )}

{confirmation.eventName}

{formatCalendarTime(confirmation.start, confirmation.timezone)} ( @@ -78,6 +76,7 @@ export function CalendarBookingPage({ slug }: { slug: string }) {

Location: {event.location}

)}

Save this link to manage your booking.

+ - - ) : slots.data?.slots.length === 0 ? ( -

- No available times on this date. Choose another date. -

- ) : ( -
- {slots.data?.slots.map((slot) => ( - - ))} -
- )} -
+
- {create.isPending ? "Confirming booking…" : "Confirm booking"} + {create.isPending + ? "Reserving booking…" + : (event.price ?? 0) > 0 + ? "Reserve pending payment" + : "Confirm booking"}
diff --git a/packages/plugin-calendar/src/client/components/pages/cancellation.tsx b/packages/plugin-calendar/src/client/components/pages/cancellation.tsx index 0d7f31c55..58b071e27 100644 --- a/packages/plugin-calendar/src/client/components/pages/cancellation.tsx +++ b/packages/plugin-calendar/src/client/components/pages/cancellation.tsx @@ -1,6 +1,9 @@ "use client"; import { Button } from "@workspace/ui/components/button"; +import { usePluginSiteNavigation } from "@btst/stack/context"; +import { CALENDAR_PLUGIN_ID } from "../../constants"; +import { CalendarInviteDownload } from "../invite-download"; import { useCalendarBooking, useCancelCalendarBooking } from "../../hooks"; import { CalendarPage, formatCalendarTime } from "../shared"; @@ -8,6 +11,7 @@ export function CalendarCancellationPage({ token }: { token: string }) { const { data } = useCalendarBooking(token); const cancel = useCancelCalendarBooking(); const booking = cancel.data ?? data; + const { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID); return (
@@ -21,10 +25,24 @@ export function CalendarCancellationPage({ token }: { token: string }) { {formatCalendarTime(booking.start, booking.timezone)} ( {booking.timezone})

+ {booking.status === "pending_payment" && ( +

+ Payment pending. Your time is held until the host confirms payment + or the booking is cancelled. +

+ )} + {booking.status === "cancelled" ? (

Your booking has been cancelled.

) : ( <> + {Date.parse(booking.start) > Date.now() && ( + + )}

Cancel this booking if you can no longer attend.

{cancel.error && (

diff --git a/packages/plugin-calendar/src/client/components/pages/dashboard.tsx b/packages/plugin-calendar/src/client/components/pages/dashboard.tsx index 26113f51b..d12f656db 100644 --- a/packages/plugin-calendar/src/client/components/pages/dashboard.tsx +++ b/packages/plugin-calendar/src/client/components/pages/dashboard.tsx @@ -12,6 +12,7 @@ import { useDeleteCalendarEvent, } from "../../hooks"; import { CalendarPage, formatCalendarTime } from "../shared"; +import { CalendarInviteDownload } from "../invite-download"; export function CalendarDashboardPage() { const { data: events } = useCalendarEvents(); @@ -164,7 +165,11 @@ function BookingsSection() {

{booking.eventName}

- {booking.status === "cancelled" ? "Cancelled" : "Confirmed"} + {booking.status === "cancelled" + ? "Cancelled" + : booking.status === "pending_payment" + ? "Payment pending" + : "Confirmed"}

@@ -174,7 +179,8 @@ function BookingsSection() {

{booking.name} · {booking.email}

- {booking.status === "confirmed" && ( + + {booking.status !== "cancelled" && ( + + + setForm({ + ...form, + price: e.target.value === "" ? null : Number(e.target.value), + }) + } + /> + + + + setForm({ + ...form, + currency: + e.target.value === "" ? null : e.target.value.toUpperCase(), + }) + } + /> + +

Booking cannot be rescheduled

+

Only upcoming active bookings can be rescheduled.

+ + ) : ( + + ); +} + +function RescheduleForm({ + token, + booking, +}: { + token: string; + booking: Booking; +}) { + const [timezone, setTimezone] = useState(booking.timezone); + const [date, setDate] = useState(() => + new Intl.DateTimeFormat("en-CA", { + timeZone: booking.timezone, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(new Date(booking.start)), + ); + const [start, setStart] = useState(""); + const slots = useCalendarRescheduleSlots(token, date, timezone); + const reschedule = useRescheduleCalendarBooking(); + const { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID); + const chosen = slots.data?.slots.find((slot) => slot.start === start); + const current = reschedule.data ?? booking; + return ( + +
+

+ {reschedule.data ? "Booking rescheduled" : "Reschedule booking"} +

+

{booking.eventName}

+

+ {formatCalendarTime(current.start, current.timezone)} ( + {current.timezone}) +

+
+ {reschedule.data ? ( +
+

+ {reschedule.data.status === "pending_payment" + ? "Your time has moved. Payment is still pending." + : "Your booking has moved to the new time."} +

+ +
+ ) : ( +
+

+ Your current time stays reserved until the new time is confirmed. +

+ + {reschedule.error && ( +

+ {reschedule.error.message} +

+ )} + +
+ )} + + Manage booking + +
+ ); +} diff --git a/packages/plugin-calendar/src/client/components/shared.tsx b/packages/plugin-calendar/src/client/components/shared.tsx index 1a8fcc1e4..1fedbba52 100644 --- a/packages/plugin-calendar/src/client/components/shared.tsx +++ b/packages/plugin-calendar/src/client/components/shared.tsx @@ -82,3 +82,13 @@ export function formatCalendarTime(value: string, timezone: string) { timeZone: timezone, }).format(new Date(value)); } + +export function formatCalendarPrice(price: number, currency: string) { + const formatter = new Intl.NumberFormat(undefined, { + style: "currency", + currency, + }); + return formatter.format( + price / 10 ** (formatter.resolvedOptions().maximumFractionDigits ?? 2), + ); +} diff --git a/packages/plugin-calendar/src/client/components/time-picker.tsx b/packages/plugin-calendar/src/client/components/time-picker.tsx new file mode 100644 index 000000000..6837f32e9 --- /dev/null +++ b/packages/plugin-calendar/src/client/components/time-picker.tsx @@ -0,0 +1,125 @@ +"use client"; + +import { Button } from "@workspace/ui/components/button"; +import { Input } from "@workspace/ui/components/input"; +import type { useCalendarSlots } from "../hooks"; +import { Field, calendarSelectClass } from "./shared"; + +export function calendarToday(timezone: string) { + return new Intl.DateTimeFormat("en-CA", { + timeZone: timezone, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(new Date()); +} + +export function CalendarTimePicker({ + date, + timezone, + start, + onDate, + onTimezone, + onStart, + slots, + capacity = 1, +}: { + date: string; + timezone: string; + start: string; + onDate: (date: string) => void; + onTimezone: (timezone: string) => void; + onStart: (start: string) => void; + slots: ReturnType; + capacity?: number; +}) { + const zones = Array.from( + new Set([timezone, "UTC", ...Intl.supportedValuesOf("timeZone")]), + ); + return ( +
+

+ Choose a time +

+
+ + { + if (e.target.value) { + onDate(e.target.value); + onStart(""); + } + }} + /> + + + + +
+ {slots.isPending || slots.isFetching ? ( +

Loading available times…

+ ) : slots.error ? ( +
+

{slots.error.message}

+ +
+ ) : slots.data?.slots.length === 0 ? ( +

+ No available times on this date. Choose another date. +

+ ) : ( +
+ {slots.data?.slots.map((slot) => ( + + ))} +
+ )} +
+ ); +} diff --git a/packages/plugin-calendar/src/client/hooks/index.tsx b/packages/plugin-calendar/src/client/hooks/index.tsx index e4f5880f5..3c84aa31f 100644 --- a/packages/plugin-calendar/src/client/hooks/index.tsx +++ b/packages/plugin-calendar/src/client/hooks/index.tsx @@ -57,3 +57,11 @@ export const useCancelCalendarBooking = () => calendar.calendarBookings.cancel.use(); export const useCancelHostCalendarBooking = () => calendar.calendarBookings.cancelHost.use(); +export const useRescheduleCalendarBooking = () => + calendar.calendarBookings.reschedule.use(); +export const useCalendarRescheduleSlots = ( + token: string, + date: string, + timezone: string, +) => calendar.calendarRescheduleSlots.list.use([token, date, timezone]); +export { generateBookingInvite } from "../../ical"; diff --git a/packages/plugin-calendar/src/client/plugin.tsx b/packages/plugin-calendar/src/client/plugin.tsx index c21fe0b49..b789c235e 100644 --- a/packages/plugin-calendar/src/client/plugin.tsx +++ b/packages/plugin-calendar/src/client/plugin.tsx @@ -33,6 +33,11 @@ const Cancellation = lazy(() => default: m.CalendarCancellationPageComponent, })), ); +const Reschedule = lazy(() => + import("./components/pages").then((m) => ({ + default: m.CalendarReschedulePageComponent, + })), +); /** Server prefetch context; path excludes the site's mounting base path. */ export interface CalendarLoaderContext { @@ -63,6 +68,7 @@ export interface CalendarClientConfig { editEvent?: ComponentType<{ params: { id: string } }>; booking?: ComponentType<{ params: { slug: string } }>; cancellation?: ComponentType<{ params: { token: string } }>; + reschedule?: ComponentType<{ params: { token: string } }>; }; } @@ -201,6 +207,14 @@ export const calendarClientPlugin = (config: CalendarClientConfig = {}) => ])(), meta: () => meta("Manage booking"), }), + calendarReschedule: defineRoute("/calendar/reschedule/:token", { + page: ({ params }) => , + loader: ({ params }) => + preload(`/calendar/reschedule/${params.token}`, [ + queries.calendarBookings.detail(params.token), + ])(), + meta: () => meta("Reschedule booking"), + }), }, { pages: { @@ -209,6 +223,7 @@ export const calendarClientPlugin = (config: CalendarClientConfig = {}) => calendarEditEvent: config.pageComponents?.editEvent, calendarBooking: config.pageComponents?.booking, calendarCancellation: config.pageComponents?.cancellation, + calendarReschedule: config.pageComponents?.reschedule, }, }, ), diff --git a/packages/plugin-calendar/src/db.ts b/packages/plugin-calendar/src/db.ts index ddab7cef5..334ba04d2 100644 --- a/packages/plugin-calendar/src/db.ts +++ b/packages/plugin-calendar/src/db.ts @@ -18,6 +18,8 @@ export const calendarSchema = createDbPlugin("calendar", { location: { type: "string", required: true }, duration: { type: "number", required: true }, capacity: { type: "number", required: true }, + price: { type: "number", required: false }, + currency: { type: "string", required: false }, timezone: { type: "string", required: true }, weeklyAvailability: { type: "string", required: true }, dateOverrides: { type: "string", required: true }, diff --git a/packages/plugin-calendar/src/ical.ts b/packages/plugin-calendar/src/ical.ts new file mode 100644 index 000000000..9dfe6e65a --- /dev/null +++ b/packages/plugin-calendar/src/ical.ts @@ -0,0 +1,57 @@ +import type { Booking } from "./types"; + +function escapeText(value: string) { + return value + .replace(/\\/g, "\\\\") + .replace(/\r\n|\r|\n/g, "\\n") + .replace(/[,;]/g, "\\$&"); +} + +function foldLine(value: string) { + const encoder = new TextEncoder(); + let line = ""; + let length = 0; + for (const character of value) { + const size = encoder.encode(character).length; + if (length + size > 75) { + line += "\r\n "; + length = 1; + } + line += character; + length += size; + } + return line; +} + +/** RFC 5545 invite with UTC instants, a stable UID, escaped text and UTF-8 line folding. No bearer token is included. */ +export function generateBookingInvite( + booking: Pick< + Booking, + "id" | "eventName" | "start" | "end" | "createdAt" | "status" + >, +) { + const timestamp = (value: string) => + new Date(value) + .toISOString() + .replace(/[-:]/g, "") + .replace(/\.\d{3}Z$/, "Z"); + return ( + [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//BTST//Calendar//EN", + "CALSCALE:GREGORIAN", + "BEGIN:VEVENT", + `UID:${escapeText(booking.id)}@btst-calendar`, + `DTSTAMP:${timestamp(booking.createdAt)}`, + `DTSTART:${timestamp(booking.start)}`, + `DTEND:${timestamp(booking.end)}`, + `SUMMARY:${escapeText(booking.eventName)}`, + `STATUS:${booking.status === "cancelled" ? "CANCELLED" : booking.status === "pending_payment" ? "TENTATIVE" : "CONFIRMED"}`, + "END:VEVENT", + "END:VCALENDAR", + ] + .map(foldLine) + .join("\r\n") + "\r\n" + ); +} diff --git a/packages/plugin-calendar/src/permissions.ts b/packages/plugin-calendar/src/permissions.ts index 3e2d109d2..c9dc29c9e 100644 --- a/packages/plugin-calendar/src/permissions.ts +++ b/packages/plugin-calendar/src/permissions.ts @@ -19,6 +19,10 @@ export const calendarPermissions = definePermissions("calendar", { create: permission(z.object(eventFacts)), read: permission(z.object({ ...bookingFacts, tokenValid: z.boolean() })), cancel: permission(z.object({ ...bookingFacts, tokenValid: z.boolean() })), + reschedule: permission( + z.object({ ...bookingFacts, tokenValid: z.boolean() }), + ), + confirmPayment: permission(z.object(bookingFacts)), remind: permission(z.object(bookingFacts)), }, }); diff --git a/packages/plugin-calendar/src/query-keys.ts b/packages/plugin-calendar/src/query-keys.ts index b9f865679..de66098d0 100644 --- a/packages/plugin-calendar/src/query-keys.ts +++ b/packages/plugin-calendar/src/query-keys.ts @@ -72,6 +72,7 @@ export const calendarResources = { "calendarEvents", "calendarPublicEvents", "calendarSlots", + "calendarRescheduleSlots", ], refresh: false, }, @@ -83,6 +84,7 @@ export const calendarResources = { "calendarEvents", "calendarPublicEvents", "calendarSlots", + "calendarRescheduleSlots", ], refresh: false, }, @@ -110,6 +112,21 @@ export const calendarResources = { }, }, }, + calendarRescheduleSlots: { + queries: { + list: { + path: "/calendar/reschedule/:token/slots", + params: (token: string, _date: string, _timezone: string) => ({ + token, + }), + query: (_token: string, date: string, timezone: string) => ({ + date, + timezone, + }), + select: (data: unknown): CalendarSlots => data as CalendarSlots, + }, + }, + }, calendarBookings: { queries: { list: { @@ -140,7 +157,11 @@ export const calendarResources = { body, }), select: (data: unknown): Booking => data as Booking, - invalidates: ["calendarSlots", "calendarBookings.list"], + invalidates: [ + "calendarSlots", + "calendarRescheduleSlots", + "calendarBookings.list", + ], refresh: false, }, cancelHost: { @@ -149,7 +170,11 @@ export const calendarResources = { input: (id: string) => ({ params: { id } }), select: (data: unknown): Omit => data as Omit, - invalidates: ["calendarSlots", "calendarBookings"], + invalidates: [ + "calendarSlots", + "calendarRescheduleSlots", + "calendarBookings", + ], refresh: false, }, cancel: { @@ -157,7 +182,30 @@ export const calendarResources = { method: "POST", input: (token: string) => ({ params: { token } }), select: (data: unknown): Booking => data as Booking, - invalidates: ["calendarSlots", "calendarBookings"], + invalidates: [ + "calendarSlots", + "calendarRescheduleSlots", + "calendarBookings", + ], + refresh: false, + }, + reschedule: { + path: "@post/calendar/reschedule/:token", + method: "POST", + input: ({ + token, + ...body + }: { + token: string; + start: string; + timezone: string; + }) => ({ params: { token }, body }), + select: (data: unknown): Booking => data as Booking, + invalidates: [ + "calendarSlots", + "calendarRescheduleSlots", + "calendarBookings", + ], refresh: false, }, }, diff --git a/packages/plugin-calendar/src/scheduling.ts b/packages/plugin-calendar/src/scheduling.ts index 67e585c27..9886ef0c5 100644 --- a/packages/plugin-calendar/src/scheduling.ts +++ b/packages/plugin-calendar/src/scheduling.ts @@ -1,5 +1,5 @@ import type { DeepReadonly } from "@btst/stack/plugins/api"; -import type { Availability, Booking, EventType } from "./types"; +import type { Availability, Booking, BusyInterval, EventType } from "./types"; function dateFormatter(timezone: string) { return new Intl.DateTimeFormat("en-CA", { @@ -41,6 +41,7 @@ export function calculateAvailability( date: string, timezone: string, now = new Date(), + busyIntervals: readonly BusyInterval[] = [], ): Availability { const slots: Availability["slots"] = []; if (!event.active) return { date, timezone, slots }; @@ -63,7 +64,7 @@ export function calculateAvailability( end: number; }[] = []; for (const booking of bookings) { - if (booking.status !== "confirmed") continue; + if (booking.status === "cancelled") continue; const start = Date.parse(booking.start); const end = Date.parse(booking.end); if (start < latestStart + duration && end > earliestStart) @@ -124,6 +125,12 @@ export function calculateAvailability( return true; }); if (!fits) continue; + if ( + busyIntervals.some( + (busy) => busy.start.getTime() < end && busy.end.getTime() > start, + ) + ) + continue; let attendeeCount = 0; let blocked = false; for (const booking of possibleOverlaps) { diff --git a/packages/plugin-calendar/src/schemas.ts b/packages/plugin-calendar/src/schemas.ts index eeb5ffb5c..371b3eda1 100644 --- a/packages/plugin-calendar/src/schemas.ts +++ b/packages/plugin-calendar/src/schemas.ts @@ -44,32 +44,47 @@ export const bookingLimitsSchema = z.object({ total: limitSchema, }); -export const createEventTypeSchema = z.object({ - slug: z - .string() - .min(1) - .max(100) - .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/), - name: z.string().trim().min(1).max(200), - description: z.string().max(5000).default(""), - location: z.string().max(500).default(""), - duration: z.number().int().min(1).max(1440), - capacity: z.number().int().min(1).max(10000).default(1), - timezone: timezoneSchema, - weeklyAvailability: z.array(weeklyAvailabilitySchema).max(168).default([]), - dateOverrides: z - .array(dateOverrideSchema) - .max(366) - .default([]) - .refine( - (overrides) => - new Set(overrides.map((override) => override.date)).size === - overrides.length, - "Only one override is allowed per date", - ), - limits: bookingLimitsSchema.default({}), - active: z.boolean().default(true), -}); +export const createEventTypeSchema = z + .object({ + slug: z + .string() + .min(1) + .max(100) + .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/), + name: z.string().trim().min(1).max(200), + description: z.string().max(5000).default(""), + location: z.string().max(500).default(""), + duration: z.number().int().min(1).max(1440), + capacity: z.number().int().min(1).max(10000).default(1), + price: z + .number() + .int() + .nonnegative() + .max(Number.MAX_SAFE_INTEGER) + .nullish(), + currency: z + .string() + .regex(/^[A-Z]{3}$/) + .nullish(), + timezone: timezoneSchema, + weeklyAvailability: z.array(weeklyAvailabilitySchema).max(168).default([]), + dateOverrides: z + .array(dateOverrideSchema) + .max(366) + .default([]) + .refine( + (overrides) => + new Set(overrides.map((override) => override.date)).size === + overrides.length, + "Only one override is allowed per date", + ), + limits: bookingLimitsSchema.default({}), + active: z.boolean().default(true), + }) + .refine(({ price, currency }) => (price != null) === (currency != null), { + message: "Supply price and currency together", + path: ["currency"], + }); export const createBookingSchema = z.object({ start: z.iso.datetime({ offset: true }), @@ -84,6 +99,10 @@ export const availabilityQuerySchema = z.object({ date: calendarDateSchema, timezone: timezoneSchema, }); +export const rescheduleBookingSchema = z.object({ + start: z.iso.datetime({ offset: true }), + timezone: timezoneSchema, +}); export const listBookingsQuerySchema = z.object({ period: z.enum(["upcoming", "past", "all"]).default("upcoming"), eventTypeId: z.string().min(1).optional(), diff --git a/packages/plugin-calendar/src/types.ts b/packages/plugin-calendar/src/types.ts index e02fb9c15..d388836ba 100644 --- a/packages/plugin-calendar/src/types.ts +++ b/packages/plugin-calendar/src/types.ts @@ -4,7 +4,7 @@ export type TimeInterval = { start: string; end: string }; export type WeeklyAvailability = TimeInterval & { dayOfWeek: number }; /** Replaces weekly availability on a host-local YYYY-MM-DD date; [] blocks the date. */ export type DateOverride = { date: string; intervals: TimeInterval[] }; -/** Confirmed attendee limits per event type, in host-local calendar periods; total is lifetime. */ +/** Reserved attendee limits per event type, in host-local calendar periods; total is lifetime. */ export type BookingLimits = { perHour?: number; perDay?: number; @@ -22,6 +22,10 @@ export type EventType = { location: string; duration: number; capacity: number; + /** Optional nonnegative price in minor currency units; null/zero means free. */ + price?: number | null; + /** Three-letter uppercase currency code, supplied together with price. */ + currency?: string | null; timezone: string; weeklyAvailability: WeeklyAvailability[]; dateOverrides: DateOverride[]; @@ -42,13 +46,15 @@ export type Booking = { timezone: string; name: string; email: string; - status: "confirmed" | "cancelled"; + status: "confirmed" | "pending_payment" | "cancelled"; cancelToken: string; createdAt: string; }; /** UTC ISO slot instants and the remaining attendee reservations, including booking limits. */ export type AvailableSlot = { start: string; end: string; remaining: number }; +/** External calendar occupancy as absolute instants, with an exclusive end. */ +export type BusyInterval = { start: Date; end: Date }; /** Availability for one viewer-local date in the requested IANA timezone. */ export type Availability = { slots: AvailableSlot[]; diff --git a/packages/stack/registry/btst-calendar.json b/packages/stack/registry/btst-calendar.json index 9c1d6fc2b..4596fc1f6 100644 --- a/packages/stack/registry/btst-calendar.json +++ b/packages/stack/registry/btst-calendar.json @@ -19,57 +19,75 @@ { "path": "btst/calendar/types.ts", "type": "registry:lib", - "content": "/** Host-local wall-clock interval, using HH:mm and exclusive end (24:00 allowed). */\nexport type TimeInterval = { start: string; end: string };\n/** Repeating host availability; Sunday is 0 and Saturday is 6. */\nexport type WeeklyAvailability = TimeInterval & { dayOfWeek: number };\n/** Replaces weekly availability on a host-local YYYY-MM-DD date; [] blocks the date. */\nexport type DateOverride = { date: string; intervals: TimeInterval[] };\n/** Confirmed attendee limits per event type, in host-local calendar periods; total is lifetime. */\nexport type BookingLimits = {\n\tperHour?: number;\n\tperDay?: number;\n\tperWeek?: number;\n\ttotal?: number;\n};\n\n/** Event configuration serialized for HTTP and React Query. Duration is real elapsed minutes. */\nexport type EventType = {\n\tid: string;\n\thostId: string;\n\tslug: string;\n\tname: string;\n\tdescription: string;\n\tlocation: string;\n\tduration: number;\n\tcapacity: number;\n\ttimezone: string;\n\tweeklyAvailability: WeeklyAvailability[];\n\tdateOverrides: DateOverride[];\n\tlimits: BookingLimits;\n\tactive: boolean;\n\tcreatedAt: string;\n\tupdatedAt: string;\n};\n\n/** Reservation with ISO instants. cancelToken is a private bearer secret; management responses redact it. */\nexport type Booking = {\n\tid: string;\n\teventTypeId: string;\n\thostId: string;\n\teventName: string;\n\tstart: string;\n\tend: string;\n\ttimezone: string;\n\tname: string;\n\temail: string;\n\tstatus: \"confirmed\" | \"cancelled\";\n\tcancelToken: string;\n\tcreatedAt: string;\n};\n\n/** UTC ISO slot instants and the remaining attendee reservations, including booking limits. */\nexport type AvailableSlot = { start: string; end: string; remaining: number };\n/** Availability for one viewer-local date in the requested IANA timezone. */\nexport type Availability = {\n\tslots: AvailableSlot[];\n\tdate: string;\n\ttimezone: string;\n};\n\n/** Storage shape: structured configuration is JSON text and timestamps are Date values. */\nexport type EventTypeRecord = Omit<\n\tEventType,\n\t\"weeklyAvailability\" | \"dateOverrides\" | \"limits\" | \"createdAt\" | \"updatedAt\"\n> & {\n\tweeklyAvailability: string;\n\tdateOverrides: string;\n\tlimits: string;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n};\n\n/** Storage shape of a reservation, including its private cancellation token. */\nexport type BookingRecord = Omit & {\n\tstart: Date;\n\tend: Date;\n\tcreatedAt: Date;\n};\n", + "content": "/** Host-local wall-clock interval, using HH:mm and exclusive end (24:00 allowed). */\nexport type TimeInterval = { start: string; end: string };\n/** Repeating host availability; Sunday is 0 and Saturday is 6. */\nexport type WeeklyAvailability = TimeInterval & { dayOfWeek: number };\n/** Replaces weekly availability on a host-local YYYY-MM-DD date; [] blocks the date. */\nexport type DateOverride = { date: string; intervals: TimeInterval[] };\n/** Reserved attendee limits per event type, in host-local calendar periods; total is lifetime. */\nexport type BookingLimits = {\n\tperHour?: number;\n\tperDay?: number;\n\tperWeek?: number;\n\ttotal?: number;\n};\n\n/** Event configuration serialized for HTTP and React Query. Duration is real elapsed minutes. */\nexport type EventType = {\n\tid: string;\n\thostId: string;\n\tslug: string;\n\tname: string;\n\tdescription: string;\n\tlocation: string;\n\tduration: number;\n\tcapacity: number;\n\t/** Optional nonnegative price in minor currency units; null/zero means free. */\n\tprice?: number | null;\n\t/** Three-letter uppercase currency code, supplied together with price. */\n\tcurrency?: string | null;\n\ttimezone: string;\n\tweeklyAvailability: WeeklyAvailability[];\n\tdateOverrides: DateOverride[];\n\tlimits: BookingLimits;\n\tactive: boolean;\n\tcreatedAt: string;\n\tupdatedAt: string;\n};\n\n/** Reservation with ISO instants. cancelToken is a private bearer secret; management responses redact it. */\nexport type Booking = {\n\tid: string;\n\teventTypeId: string;\n\thostId: string;\n\teventName: string;\n\tstart: string;\n\tend: string;\n\ttimezone: string;\n\tname: string;\n\temail: string;\n\tstatus: \"confirmed\" | \"pending_payment\" | \"cancelled\";\n\tcancelToken: string;\n\tcreatedAt: string;\n};\n\n/** UTC ISO slot instants and the remaining attendee reservations, including booking limits. */\nexport type AvailableSlot = { start: string; end: string; remaining: number };\n/** External calendar occupancy as absolute instants, with an exclusive end. */\nexport type BusyInterval = { start: Date; end: Date };\n/** Availability for one viewer-local date in the requested IANA timezone. */\nexport type Availability = {\n\tslots: AvailableSlot[];\n\tdate: string;\n\ttimezone: string;\n};\n\n/** Storage shape: structured configuration is JSON text and timestamps are Date values. */\nexport type EventTypeRecord = Omit<\n\tEventType,\n\t\"weeklyAvailability\" | \"dateOverrides\" | \"limits\" | \"createdAt\" | \"updatedAt\"\n> & {\n\tweeklyAvailability: string;\n\tdateOverrides: string;\n\tlimits: string;\n\tcreatedAt: Date;\n\tupdatedAt: Date;\n};\n\n/** Storage shape of a reservation, including its private cancellation token. */\nexport type BookingRecord = Omit & {\n\tstart: Date;\n\tend: Date;\n\tcreatedAt: Date;\n};\n", "target": "src/components/btst/calendar/types.ts" }, { "path": "btst/calendar/schemas.ts", "type": "registry:lib", - "content": "import { z } from \"zod\";\n\nexport const timezoneSchema = z\n\t.string()\n\t.min(1)\n\t.max(100)\n\t.refine((zone) => {\n\t\ttry {\n\t\t\tnew Intl.DateTimeFormat(\"en\", { timeZone: zone }).format();\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}, \"Invalid timezone\");\n\nexport const calendarDateSchema = z.iso.date();\nconst timeSchema = z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/);\nconst endTimeSchema = z.union([timeSchema, z.literal(\"24:00\")]);\nconst intervalSchema = z\n\t.object({ start: timeSchema, end: endTimeSchema })\n\t.refine(\n\t\t({ start, end }) => start < end,\n\t\t\"Availability must end after it starts\",\n\t);\nexport const weeklyAvailabilitySchema = z\n\t.object({\n\t\tdayOfWeek: z.number().int().min(0).max(6),\n\t\tstart: timeSchema,\n\t\tend: endTimeSchema,\n\t})\n\t.refine(\n\t\t({ start, end }) => start < end,\n\t\t\"Availability must end after it starts\",\n\t);\nexport const dateOverrideSchema = z.object({\n\tdate: calendarDateSchema,\n\tintervals: z.array(intervalSchema).max(24),\n});\nconst limitSchema = z.number().int().positive().max(1_000_000).optional();\nexport const bookingLimitsSchema = z.object({\n\tperHour: limitSchema,\n\tperDay: limitSchema,\n\tperWeek: limitSchema,\n\ttotal: limitSchema,\n});\n\nexport const createEventTypeSchema = z.object({\n\tslug: z\n\t\t.string()\n\t\t.min(1)\n\t\t.max(100)\n\t\t.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),\n\tname: z.string().trim().min(1).max(200),\n\tdescription: z.string().max(5000).default(\"\"),\n\tlocation: z.string().max(500).default(\"\"),\n\tduration: z.number().int().min(1).max(1440),\n\tcapacity: z.number().int().min(1).max(10000).default(1),\n\ttimezone: timezoneSchema,\n\tweeklyAvailability: z.array(weeklyAvailabilitySchema).max(168).default([]),\n\tdateOverrides: z\n\t\t.array(dateOverrideSchema)\n\t\t.max(366)\n\t\t.default([])\n\t\t.refine(\n\t\t\t(overrides) =>\n\t\t\t\tnew Set(overrides.map((override) => override.date)).size ===\n\t\t\t\toverrides.length,\n\t\t\t\"Only one override is allowed per date\",\n\t\t),\n\tlimits: bookingLimitsSchema.default({}),\n\tactive: z.boolean().default(true),\n});\n\nexport const createBookingSchema = z.object({\n\tstart: z.iso.datetime({ offset: true }),\n\ttimezone: timezoneSchema,\n\tname: z.string().trim().min(1).max(200),\n\temail: z\n\t\t.email()\n\t\t.max(320)\n\t\t.transform((value) => value.toLowerCase()),\n});\nexport const availabilityQuerySchema = z.object({\n\tdate: calendarDateSchema,\n\ttimezone: timezoneSchema,\n});\nexport const listBookingsQuerySchema = z.object({\n\tperiod: z.enum([\"upcoming\", \"past\", \"all\"]).default(\"upcoming\"),\n\teventTypeId: z.string().min(1).optional(),\n});\n", + "content": "import { z } from \"zod\";\n\nexport const timezoneSchema = z\n\t.string()\n\t.min(1)\n\t.max(100)\n\t.refine((zone) => {\n\t\ttry {\n\t\t\tnew Intl.DateTimeFormat(\"en\", { timeZone: zone }).format();\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}, \"Invalid timezone\");\n\nexport const calendarDateSchema = z.iso.date();\nconst timeSchema = z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/);\nconst endTimeSchema = z.union([timeSchema, z.literal(\"24:00\")]);\nconst intervalSchema = z\n\t.object({ start: timeSchema, end: endTimeSchema })\n\t.refine(\n\t\t({ start, end }) => start < end,\n\t\t\"Availability must end after it starts\",\n\t);\nexport const weeklyAvailabilitySchema = z\n\t.object({\n\t\tdayOfWeek: z.number().int().min(0).max(6),\n\t\tstart: timeSchema,\n\t\tend: endTimeSchema,\n\t})\n\t.refine(\n\t\t({ start, end }) => start < end,\n\t\t\"Availability must end after it starts\",\n\t);\nexport const dateOverrideSchema = z.object({\n\tdate: calendarDateSchema,\n\tintervals: z.array(intervalSchema).max(24),\n});\nconst limitSchema = z.number().int().positive().max(1_000_000).optional();\nexport const bookingLimitsSchema = z.object({\n\tperHour: limitSchema,\n\tperDay: limitSchema,\n\tperWeek: limitSchema,\n\ttotal: limitSchema,\n});\n\nexport const createEventTypeSchema = z\n\t.object({\n\t\tslug: z\n\t\t\t.string()\n\t\t\t.min(1)\n\t\t\t.max(100)\n\t\t\t.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),\n\t\tname: z.string().trim().min(1).max(200),\n\t\tdescription: z.string().max(5000).default(\"\"),\n\t\tlocation: z.string().max(500).default(\"\"),\n\t\tduration: z.number().int().min(1).max(1440),\n\t\tcapacity: z.number().int().min(1).max(10000).default(1),\n\t\tprice: z\n\t\t\t.number()\n\t\t\t.int()\n\t\t\t.nonnegative()\n\t\t\t.max(Number.MAX_SAFE_INTEGER)\n\t\t\t.nullish(),\n\t\tcurrency: z\n\t\t\t.string()\n\t\t\t.regex(/^[A-Z]{3}$/)\n\t\t\t.nullish(),\n\t\ttimezone: timezoneSchema,\n\t\tweeklyAvailability: z.array(weeklyAvailabilitySchema).max(168).default([]),\n\t\tdateOverrides: z\n\t\t\t.array(dateOverrideSchema)\n\t\t\t.max(366)\n\t\t\t.default([])\n\t\t\t.refine(\n\t\t\t\t(overrides) =>\n\t\t\t\t\tnew Set(overrides.map((override) => override.date)).size ===\n\t\t\t\t\toverrides.length,\n\t\t\t\t\"Only one override is allowed per date\",\n\t\t\t),\n\t\tlimits: bookingLimitsSchema.default({}),\n\t\tactive: z.boolean().default(true),\n\t})\n\t.refine(({ price, currency }) => (price != null) === (currency != null), {\n\t\tmessage: \"Supply price and currency together\",\n\t\tpath: [\"currency\"],\n\t});\n\nexport const createBookingSchema = z.object({\n\tstart: z.iso.datetime({ offset: true }),\n\ttimezone: timezoneSchema,\n\tname: z.string().trim().min(1).max(200),\n\temail: z\n\t\t.email()\n\t\t.max(320)\n\t\t.transform((value) => value.toLowerCase()),\n});\nexport const availabilityQuerySchema = z.object({\n\tdate: calendarDateSchema,\n\ttimezone: timezoneSchema,\n});\nexport const rescheduleBookingSchema = z.object({\n\tstart: z.iso.datetime({ offset: true }),\n\ttimezone: timezoneSchema,\n});\nexport const listBookingsQuerySchema = z.object({\n\tperiod: z.enum([\"upcoming\", \"past\", \"all\"]).default(\"upcoming\"),\n\teventTypeId: z.string().min(1).optional(),\n});\n", "target": "src/components/btst/calendar/schemas.ts" }, { "path": "btst/calendar/permissions.ts", "type": "registry:lib", - "content": "import { definePermissions, permission } from \"@btst/stack/authorization\";\nimport { z } from \"zod\";\n\nconst eventFacts = { eventTypeId: z.string(), hostId: z.string() };\nconst hostFacts = { hostId: z.string().optional() };\nconst bookingFacts = { bookingId: z.string(), hostId: z.string() };\n\nexport const calendarPermissions = definePermissions(\"calendar\", {\n\teventType: {\n\t\tlist: permission(z.object(hostFacts)),\n\t\tread: permission(z.object({ ...eventFacts, public: z.boolean() })),\n\t\tcreate: permission(z.object(hostFacts)),\n\t\tupdate: permission(z.object(eventFacts)),\n\t\tdelete: permission(z.object(eventFacts)),\n\t},\n\tavailability: { read: permission(z.object(eventFacts)) },\n\tbooking: {\n\t\tlist: permission(z.object(hostFacts)),\n\t\tcreate: permission(z.object(eventFacts)),\n\t\tread: permission(z.object({ ...bookingFacts, tokenValid: z.boolean() })),\n\t\tcancel: permission(z.object({ ...bookingFacts, tokenValid: z.boolean() })),\n\t\tremind: permission(z.object(bookingFacts)),\n\t},\n});\n", + "content": "import { definePermissions, permission } from \"@btst/stack/authorization\";\nimport { z } from \"zod\";\n\nconst eventFacts = { eventTypeId: z.string(), hostId: z.string() };\nconst hostFacts = { hostId: z.string().optional() };\nconst bookingFacts = { bookingId: z.string(), hostId: z.string() };\n\nexport const calendarPermissions = definePermissions(\"calendar\", {\n\teventType: {\n\t\tlist: permission(z.object(hostFacts)),\n\t\tread: permission(z.object({ ...eventFacts, public: z.boolean() })),\n\t\tcreate: permission(z.object(hostFacts)),\n\t\tupdate: permission(z.object(eventFacts)),\n\t\tdelete: permission(z.object(eventFacts)),\n\t},\n\tavailability: { read: permission(z.object(eventFacts)) },\n\tbooking: {\n\t\tlist: permission(z.object(hostFacts)),\n\t\tcreate: permission(z.object(eventFacts)),\n\t\tread: permission(z.object({ ...bookingFacts, tokenValid: z.boolean() })),\n\t\tcancel: permission(z.object({ ...bookingFacts, tokenValid: z.boolean() })),\n\t\treschedule: permission(\n\t\t\tz.object({ ...bookingFacts, tokenValid: z.boolean() }),\n\t\t),\n\t\tconfirmPayment: permission(z.object(bookingFacts)),\n\t\tremind: permission(z.object(bookingFacts)),\n\t},\n});\n", "target": "src/components/btst/calendar/permissions.ts" }, + { + "path": "btst/calendar/client/components/invite-download.tsx", + "type": "registry:component", + "content": "\"use client\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { generateBookingInvite } from \"@btst/plugin-calendar/client/hooks\";\nimport type { Booking } from \"../../types\";\n\nexport function CalendarInviteDownload({\n\tbooking,\n}: {\n\tbooking: Omit;\n}) {\n\treturn (\n\t\t\n\t);\n}\n", + "target": "src/components/btst/calendar/client/components/invite-download.tsx" + }, { "path": "btst/calendar/client/components/pages.tsx", "type": "registry:component", - "content": "\"use client\";\n\nimport { lazy } from \"react\";\nimport { ComposedRoute } from \"@btst/stack/client/components\";\nimport { calendarPermissions } from \"../../permissions\";\nimport { CalendarError, CalendarLoading, CalendarNotFound } from \"./shared\";\n\nconst Dashboard = lazy(() =>\n\timport(\"./pages/dashboard\").then((m) => ({\n\t\tdefault: m.CalendarDashboardPage,\n\t})),\n);\nconst Editor = lazy(() =>\n\timport(\"./pages/event-editor\").then((m) => ({\n\t\tdefault: m.CalendarEventEditorPage,\n\t})),\n);\nconst Booking = lazy(() =>\n\timport(\"./pages/booking\").then((m) => ({ default: m.CalendarBookingPage })),\n);\nconst Cancellation = lazy(() =>\n\timport(\"./pages/cancellation\").then((m) => ({\n\t\tdefault: m.CalendarCancellationPage,\n\t})),\n);\n\nconst boundary = {\n\tErrorComponent: CalendarError,\n\tLoadingComponent: CalendarLoading,\n\tNotFoundComponent: CalendarNotFound,\n\tonError: (error: Error) => console.error(\"[btst/calendar]\", error),\n};\n\nexport function CalendarDashboardPageComponent() {\n\treturn (\n\t\t\n\t);\n}\n\nexport function CalendarEventEditorPageComponent({ id }: { id?: string }) {\n\treturn (\n\t\t\n\t);\n}\n\nexport function CalendarBookingPageComponent({ slug }: { slug: string }) {\n\treturn (\n\t\t\n\t);\n}\n\nexport function CalendarCancellationPageComponent({\n\ttoken,\n}: {\n\ttoken: string;\n}) {\n\treturn (\n\t\t\n\t);\n}\n", + "content": "\"use client\";\n\nimport { lazy } from \"react\";\nimport { ComposedRoute } from \"@btst/stack/client/components\";\nimport { calendarPermissions } from \"../../permissions\";\nimport { CalendarError, CalendarLoading, CalendarNotFound } from \"./shared\";\n\nconst Dashboard = lazy(() =>\n\timport(\"./pages/dashboard\").then((m) => ({\n\t\tdefault: m.CalendarDashboardPage,\n\t})),\n);\nconst Editor = lazy(() =>\n\timport(\"./pages/event-editor\").then((m) => ({\n\t\tdefault: m.CalendarEventEditorPage,\n\t})),\n);\nconst Booking = lazy(() =>\n\timport(\"./pages/booking\").then((m) => ({ default: m.CalendarBookingPage })),\n);\nconst Cancellation = lazy(() =>\n\timport(\"./pages/cancellation\").then((m) => ({\n\t\tdefault: m.CalendarCancellationPage,\n\t})),\n);\nconst Reschedule = lazy(() =>\n\timport(\"./pages/reschedule\").then((m) => ({\n\t\tdefault: m.CalendarReschedulePage,\n\t})),\n);\n\nconst boundary = {\n\tErrorComponent: CalendarError,\n\tLoadingComponent: CalendarLoading,\n\tNotFoundComponent: CalendarNotFound,\n\tonError: (error: Error) => console.error(\"[btst/calendar]\", error),\n};\n\nexport function CalendarDashboardPageComponent() {\n\treturn (\n\t\t\n\t);\n}\n\nexport function CalendarEventEditorPageComponent({ id }: { id?: string }) {\n\treturn (\n\t\t\n\t);\n}\n\nexport function CalendarBookingPageComponent({ slug }: { slug: string }) {\n\treturn (\n\t\t\n\t);\n}\n\nexport function CalendarCancellationPageComponent({\n\ttoken,\n}: {\n\ttoken: string;\n}) {\n\treturn (\n\t\t\n\t);\n}\n\nexport function CalendarReschedulePageComponent({ token }: { token: string }) {\n\treturn (\n\t\t\n\t);\n}\n", "target": "src/components/btst/calendar/client/components/pages.tsx" }, { "path": "btst/calendar/client/components/pages/booking.tsx", "type": "registry:page", - "content": "\"use client\";\n\nimport { useEffect, useState, type FormEvent } from \"react\";\nimport { usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport type { Booking } from \"../../../types\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseCalendarSlots,\n\tuseCreateCalendarBooking,\n\tusePublicCalendarEvent,\n} from \"@btst/plugin-calendar/client/hooks\";\nimport {\n\tCalendarPage,\n\tField,\n\tcalendarSelectClass,\n\tformatCalendarTime,\n} from \"../shared\";\n\nfunction today(timezone: string) {\n\treturn new Intl.DateTimeFormat(\"en-CA\", {\n\t\ttimeZone: timezone,\n\t\tyear: \"numeric\",\n\t\tmonth: \"2-digit\",\n\t\tday: \"2-digit\",\n\t}).format(new Date());\n}\n\nexport function CalendarBookingPage({ slug }: { slug: string }) {\n\tconst { data: event } = usePublicCalendarEvent(slug);\n\tconst [timezone, setTimezone] = useState(event.timezone);\n\tconst [date, setDate] = useState(() => today(event.timezone));\n\tconst [start, setStart] = useState(\"\");\n\tconst [confirmation, setConfirmation] = useState();\n\tconst slots = useCalendarSlots(slug, date, timezone);\n\tconst create = useCreateCalendarBooking();\n\tconst { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\tuseEffect(() => {\n\t\tconst localZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n\t\tsetTimezone(localZone);\n\t\tsetDate(today(localZone));\n\t}, []);\n\tconst zones = Array.from(\n\t\tnew Set([timezone, \"UTC\", ...Intl.supportedValuesOf(\"timeZone\")]),\n\t);\n\tconst chosenSlot = slots.data?.slots.find((slot) => slot.start === start);\n\tconst submit = async (e: FormEvent) => {\n\t\te.preventDefault();\n\t\tif (!chosenSlot) return;\n\t\tconst data = new FormData(e.currentTarget);\n\t\ttry {\n\t\t\tconst booking = await create.mutateAsync({\n\t\t\t\tslug,\n\t\t\t\tstart,\n\t\t\t\ttimezone,\n\t\t\t\tname: String(data.get(\"name\")),\n\t\t\t\temail: String(data.get(\"email\")),\n\t\t\t});\n\t\t\tsetConfirmation(booking);\n\t\t} catch {\n\t\t\t// The mutation exposes its error beside the booking form.\n\t\t}\n\t};\n\tif (confirmation)\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t

\n\t\t\t\t\t\tBooking confirmed\n\t\t\t\t\t

\n\t\t\t\t\t

{confirmation.eventName}

\n\t\t\t\t\t

\n\t\t\t\t\t\t{formatCalendarTime(confirmation.start, confirmation.timezone)} (\n\t\t\t\t\t\t{confirmation.timezone})\n\t\t\t\t\t

\n\t\t\t\t\t{event.location && (\n\t\t\t\t\t\t

Location: {event.location}

\n\t\t\t\t\t)}\n\t\t\t\t\t

Save this link to manage your booking.

\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\t{event.name}\n\t\t\t\t

\n\t\t\t\t

\n\t\t\t\t\t{event.duration} minutes ·{\" \"}\n\t\t\t\t\t{event.capacity === 1\n\t\t\t\t\t\t? \"1:1 booking\"\n\t\t\t\t\t\t: `Up to ${event.capacity} attendees`}\n\t\t\t\t

\n\t\t\t\t{event.description && (\n\t\t\t\t\t

{event.description}

\n\t\t\t\t)}\n\t\t\t\t{event.location && (\n\t\t\t\t\t

Location: {event.location}

\n\t\t\t\t)}\n\t\t\t
\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\t

\n\t\t\t\t\t\tChoose a time\n\t\t\t\t\t

\n\t\t\t\t\t
\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\tif (e.target.value) {\n\t\t\t\t\t\t\t\t\t\tsetDate(e.target.value);\n\t\t\t\t\t\t\t\t\t\tsetStart(\"\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\tsetTimezone(e.target.value);\n\t\t\t\t\t\t\t\t\tsetStart(\"\");\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{zones.map((zone) => (\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t
\n\t\t\t\t\t{slots.isPending || slots.isFetching ? (\n\t\t\t\t\t\t

Loading available times…

\n\t\t\t\t\t) : slots.error ? (\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t

{slots.error.message}

\n\t\t\t\t\t\t\t void slots.refetch()}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tRetry available times\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\n\t\t\t\t\t) : slots.data?.slots.length === 0 ? (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\tNo available times on this date. Choose another date.\n\t\t\t\t\t\t

\n\t\t\t\t\t) : (\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t{slots.data?.slots.map((slot) => (\n\t\t\t\t\t\t\t\t setStart(slot.start)}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{new Intl.DateTimeFormat(undefined, {\n\t\t\t\t\t\t\t\t\t\thour: \"numeric\",\n\t\t\t\t\t\t\t\t\t\tminute: \"2-digit\",\n\t\t\t\t\t\t\t\t\t\ttimeZoneName: \"short\",\n\t\t\t\t\t\t\t\t\t\ttimeZone: timezone,\n\t\t\t\t\t\t\t\t\t}).format(new Date(slot.start))}\n\t\t\t\t\t\t\t\t\t{event.capacity > 1 && (\n\t\t\t\t\t\t\t\t\t\t({slot.remaining} left)\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t
\n\t\t\t\t\t)}\n\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\t

Your details

\n\t\t\t\t\t{chosenSlot ? (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\t{formatCalendarTime(chosenSlot.start, timezone)} ({timezone})\n\t\t\t\t\t\t

\n\t\t\t\t\t) : (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\tSelect an available time to confirm your booking.\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t{create.error && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\t{create.error.message}\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t\n\t\t\t\t\t\t{create.isPending ? \"Confirming booking…\" : \"Confirm booking\"}\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\n\nimport { useEffect, useState, type FormEvent } from \"react\";\nimport { usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport type { Booking } from \"../../../types\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseCalendarSlots,\n\tuseCreateCalendarBooking,\n\tusePublicCalendarEvent,\n} from \"@btst/plugin-calendar/client/hooks\";\nimport {\n\tCalendarPage,\n\tField,\n\tformatCalendarTime,\n\tformatCalendarPrice,\n} from \"../shared\";\nimport { CalendarInviteDownload } from \"../invite-download\";\nimport { CalendarTimePicker, calendarToday } from \"../time-picker\";\n\nexport function CalendarBookingPage({ slug }: { slug: string }) {\n\tconst { data: event } = usePublicCalendarEvent(slug);\n\tconst [timezone, setTimezone] = useState(event.timezone);\n\tconst [date, setDate] = useState(() => calendarToday(event.timezone));\n\tconst [start, setStart] = useState(\"\");\n\tconst [confirmation, setConfirmation] = useState();\n\tconst slots = useCalendarSlots(slug, date, timezone);\n\tconst create = useCreateCalendarBooking();\n\tconst { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\tuseEffect(() => {\n\t\tconst localZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n\t\tsetTimezone(localZone);\n\t\tsetDate(calendarToday(localZone));\n\t}, []);\n\tconst chosenSlot = slots.data?.slots.find((slot) => slot.start === start);\n\tconst submit = async (e: FormEvent) => {\n\t\te.preventDefault();\n\t\tif (!chosenSlot) return;\n\t\tconst data = new FormData(e.currentTarget);\n\t\ttry {\n\t\t\tconst booking = await create.mutateAsync({\n\t\t\t\tslug,\n\t\t\t\tstart,\n\t\t\t\ttimezone,\n\t\t\t\tname: String(data.get(\"name\")),\n\t\t\t\temail: String(data.get(\"email\")),\n\t\t\t});\n\t\t\tsetConfirmation(booking);\n\t\t} catch {\n\t\t\t// The mutation exposes its error beside the booking form.\n\t\t}\n\t};\n\tif (confirmation)\n\t\treturn (\n\t\t\t\n\t\t\t\t
\n\t\t\t\t\t

\n\t\t\t\t\t\t{confirmation.status === \"pending_payment\"\n\t\t\t\t\t\t\t? \"Booking awaiting payment\"\n\t\t\t\t\t\t\t: \"Booking confirmed\"}\n\t\t\t\t\t

\n\t\t\t\t\t{confirmation.status === \"pending_payment\" && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\tYour time is held while payment is pending. Contact the host to\n\t\t\t\t\t\t\tcomplete payment.\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t

{confirmation.eventName}

\n\t\t\t\t\t

\n\t\t\t\t\t\t{formatCalendarTime(confirmation.start, confirmation.timezone)} (\n\t\t\t\t\t\t{confirmation.timezone})\n\t\t\t\t\t

\n\t\t\t\t\t{event.location && (\n\t\t\t\t\t\t

Location: {event.location}

\n\t\t\t\t\t)}\n\t\t\t\t\t

Save this link to manage your booking.

\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\t{event.name}\n\t\t\t\t

\n\t\t\t\t

\n\t\t\t\t\t{event.duration} minutes ·{\" \"}\n\t\t\t\t\t{event.capacity === 1\n\t\t\t\t\t\t? \"1:1 booking\"\n\t\t\t\t\t\t: `Up to ${event.capacity} attendees`}\n\t\t\t\t

\n\t\t\t\t{event.description && (\n\t\t\t\t\t

{event.description}

\n\t\t\t\t)}\n\t\t\t\t{event.location && (\n\t\t\t\t\t

Location: {event.location}

\n\t\t\t\t)}\n\t\t\t\t{(event.price ?? 0) > 0 && event.currency && (\n\t\t\t\t\t

\n\t\t\t\t\t\tPrice: {formatCalendarPrice(event.price!, event.currency)}. Payment\n\t\t\t\t\t\tis required to confirm your booking.\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t
\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t

Your details

\n\t\t\t\t\t{chosenSlot ? (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\t{formatCalendarTime(chosenSlot.start, timezone)} ({timezone})\n\t\t\t\t\t\t

\n\t\t\t\t\t) : (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\tSelect an available time to confirm your booking.\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t{create.error && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\t{create.error.message}\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t\n\t\t\t\t\t\t{create.isPending\n\t\t\t\t\t\t\t? \"Reserving booking…\"\n\t\t\t\t\t\t\t: (event.price ?? 0) > 0\n\t\t\t\t\t\t\t\t? \"Reserve pending payment\"\n\t\t\t\t\t\t\t\t: \"Confirm booking\"}\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t
\n\t\t
\n\t);\n}\n", "target": "src/components/btst/calendar/client/components/pages/booking.tsx" }, { "path": "btst/calendar/client/components/pages/cancellation.tsx", "type": "registry:page", - "content": "\"use client\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { useCalendarBooking, useCancelCalendarBooking } from \"@btst/plugin-calendar/client/hooks\";\nimport { CalendarPage, formatCalendarTime } from \"../shared\";\n\nexport function CalendarCancellationPage({ token }: { token: string }) {\n\tconst { data } = useCalendarBooking(token);\n\tconst cancel = useCancelCalendarBooking();\n\tconst booking = cancel.data ?? data;\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\t{booking.status === \"cancelled\"\n\t\t\t\t\t\t? \"Booking cancelled\"\n\t\t\t\t\t\t: \"Manage booking\"}\n\t\t\t\t

\n\t\t\t\t

{booking.eventName}

\n\t\t\t\t

\n\t\t\t\t\t{formatCalendarTime(booking.start, booking.timezone)} (\n\t\t\t\t\t{booking.timezone})\n\t\t\t\t

\n\t\t\t\t{booking.status === \"cancelled\" ? (\n\t\t\t\t\t

Your booking has been cancelled.

\n\t\t\t\t) : (\n\t\t\t\t\t<>\n\t\t\t\t\t\t

Cancel this booking if you can no longer attend.

\n\t\t\t\t\t\t{cancel.error && (\n\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t{cancel.error.message}\n\t\t\t\t\t\t\t

\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t cancel.mutate(token)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{cancel.isPending ? \"Cancelling booking…\" : \"Cancel booking\"}\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t
\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport { CalendarInviteDownload } from \"../invite-download\";\nimport { useCalendarBooking, useCancelCalendarBooking } from \"@btst/plugin-calendar/client/hooks\";\nimport { CalendarPage, formatCalendarTime } from \"../shared\";\n\nexport function CalendarCancellationPage({ token }: { token: string }) {\n\tconst { data } = useCalendarBooking(token);\n\tconst cancel = useCancelCalendarBooking();\n\tconst booking = cancel.data ?? data;\n\tconst { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\t{booking.status === \"cancelled\"\n\t\t\t\t\t\t? \"Booking cancelled\"\n\t\t\t\t\t\t: \"Manage booking\"}\n\t\t\t\t

\n\t\t\t\t

{booking.eventName}

\n\t\t\t\t

\n\t\t\t\t\t{formatCalendarTime(booking.start, booking.timezone)} (\n\t\t\t\t\t{booking.timezone})\n\t\t\t\t

\n\t\t\t\t{booking.status === \"pending_payment\" && (\n\t\t\t\t\t

\n\t\t\t\t\t\tPayment pending. Your time is held until the host confirms payment\n\t\t\t\t\t\tor the booking is cancelled.\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t\t\n\t\t\t\t{booking.status === \"cancelled\" ? (\n\t\t\t\t\t

Your booking has been cancelled.

\n\t\t\t\t) : (\n\t\t\t\t\t<>\n\t\t\t\t\t\t{Date.parse(booking.start) > Date.now() && (\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t

Cancel this booking if you can no longer attend.

\n\t\t\t\t\t\t{cancel.error && (\n\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t{cancel.error.message}\n\t\t\t\t\t\t\t

\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t cancel.mutate(token)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{cancel.isPending ? \"Cancelling booking…\" : \"Cancel booking\"}\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t
\n\t\t
\n\t);\n}\n", "target": "src/components/btst/calendar/client/components/pages/cancellation.tsx" }, { "path": "btst/calendar/client/components/pages/dashboard.tsx", "type": "registry:page", - "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { PermissionAccess, usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { Button } from \"@/components/ui/button\";\nimport { calendarPermissions } from \"../../../permissions\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseCalendarBookings,\n\tuseCalendarEvents,\n\tuseCancelHostCalendarBooking,\n\tuseDeleteCalendarEvent,\n} from \"@btst/plugin-calendar/client/hooks\";\nimport { CalendarPage, formatCalendarTime } from \"../shared\";\n\nexport function CalendarDashboardPage() {\n\tconst { data: events } = useCalendarEvents();\n\tconst remove = useDeleteCalendarEvent();\n\tconst { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t

Calendar

\n\t\t\t\t\t

\n\t\t\t\t\t\tManage event types and scheduled bookings.\n\t\t\t\t\t

\n\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t
\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\tEvent types\n\t\t\t\t

\n\t\t\t\t{remove.error && (\n\t\t\t\t\t

\n\t\t\t\t\t\t{remove.error.message}\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t\t{events.length === 0 ? (\n\t\t\t\t\t

\n\t\t\t\t\t\tNo event types yet. Create one to set your availability and share a\n\t\t\t\t\t\tbooking page.\n\t\t\t\t\t

\n\t\t\t\t) : (\n\t\t\t\t\t
    \n\t\t\t\t\t\t{events.map((event) => (\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t\t

    {event.name}

    \n\t\t\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t\t\t{event.duration} minutes ·{\" \"}\n\t\t\t\t\t\t\t\t\t\t{event.capacity === 1\n\t\t\t\t\t\t\t\t\t\t\t? \"1:1\"\n\t\t\t\t\t\t\t\t\t\t\t: `Up to ${event.capacity} attendees`}{\" \"}\n\t\t\t\t\t\t\t\t\t\t· {event.active ? \"Accepting bookings\" : \"Paused\"}\n\t\t\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t\t{event.active && (\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t\twindow.confirm(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`Delete ${event.name}? Existing bookings must be cancelled first.`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tremove.mutate(event.id);\n\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\tDelete {event.name}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t))}\n\t\t\t\t\t
\n\t\t\t\t)}\n\t\t\t
\n\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t
\n\t);\n}\n\nfunction BookingsSection() {\n\tconst [period, setPeriod] = useState<\"upcoming\" | \"past\">(\"upcoming\");\n\tconst { data: bookings } = useCalendarBookings(period);\n\tconst cancel = useCancelHostCalendarBooking();\n\treturn (\n\t\t
\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\tBookings\n\t\t\t\t

\n\t\t\t\t
\n\t\t\t\t\t{([\"upcoming\", \"past\"] as const).map((value) => (\n\t\t\t\t\t\t setPeriod(value)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{value === \"upcoming\" ? \"Upcoming\" : \"Past\"}\n\t\t\t\t\t\t\n\t\t\t\t\t))}\n\t\t\t\t
\n\t\t\t
\n\t\t\t{cancel.error && (\n\t\t\t\t

\n\t\t\t\t\t{cancel.error.message}\n\t\t\t\t

\n\t\t\t)}\n\t\t\t{bookings.length === 0 ? (\n\t\t\t\t

\n\t\t\t\t\tNo {period} bookings.\n\t\t\t\t

\n\t\t\t) : (\n\t\t\t\t
    \n\t\t\t\t\t{bookings.map((booking) => (\n\t\t\t\t\t\t
  • \n\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t

    {booking.eventName}

    \n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t{booking.status === \"cancelled\" ? \"Cancelled\" : \"Confirmed\"}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t{formatCalendarTime(booking.start, booking.timezone)} (\n\t\t\t\t\t\t\t\t{booking.timezone})\n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t{booking.name} · {booking.email}\n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t{booking.status === \"confirmed\" && (\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t cancel.mutate(booking.id)}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tCancel booking\n\t\t\t\t\t\t\t\t\t\t for {booking.name}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t
  • \n\t\t\t\t\t))}\n\t\t\t\t
\n\t\t\t)}\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { PermissionAccess, usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { Button } from \"@/components/ui/button\";\nimport { calendarPermissions } from \"../../../permissions\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseCalendarBookings,\n\tuseCalendarEvents,\n\tuseCancelHostCalendarBooking,\n\tuseDeleteCalendarEvent,\n} from \"@btst/plugin-calendar/client/hooks\";\nimport { CalendarPage, formatCalendarTime } from \"../shared\";\nimport { CalendarInviteDownload } from \"../invite-download\";\n\nexport function CalendarDashboardPage() {\n\tconst { data: events } = useCalendarEvents();\n\tconst remove = useDeleteCalendarEvent();\n\tconst { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t

Calendar

\n\t\t\t\t\t

\n\t\t\t\t\t\tManage event types and scheduled bookings.\n\t\t\t\t\t

\n\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t
\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\tEvent types\n\t\t\t\t

\n\t\t\t\t{remove.error && (\n\t\t\t\t\t

\n\t\t\t\t\t\t{remove.error.message}\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t\t{events.length === 0 ? (\n\t\t\t\t\t

\n\t\t\t\t\t\tNo event types yet. Create one to set your availability and share a\n\t\t\t\t\t\tbooking page.\n\t\t\t\t\t

\n\t\t\t\t) : (\n\t\t\t\t\t
    \n\t\t\t\t\t\t{events.map((event) => (\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t\t

    {event.name}

    \n\t\t\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t\t\t{event.duration} minutes ·{\" \"}\n\t\t\t\t\t\t\t\t\t\t{event.capacity === 1\n\t\t\t\t\t\t\t\t\t\t\t? \"1:1\"\n\t\t\t\t\t\t\t\t\t\t\t: `Up to ${event.capacity} attendees`}{\" \"}\n\t\t\t\t\t\t\t\t\t\t· {event.active ? \"Accepting bookings\" : \"Paused\"}\n\t\t\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t\t{event.active && (\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t\twindow.confirm(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`Delete ${event.name}? Existing bookings must be cancelled first.`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tremove.mutate(event.id);\n\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\tDelete {event.name}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t))}\n\t\t\t\t\t
\n\t\t\t\t)}\n\t\t\t
\n\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t
\n\t);\n}\n\nfunction BookingsSection() {\n\tconst [period, setPeriod] = useState<\"upcoming\" | \"past\">(\"upcoming\");\n\tconst { data: bookings } = useCalendarBookings(period);\n\tconst cancel = useCancelHostCalendarBooking();\n\treturn (\n\t\t
\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\tBookings\n\t\t\t\t

\n\t\t\t\t
\n\t\t\t\t\t{([\"upcoming\", \"past\"] as const).map((value) => (\n\t\t\t\t\t\t setPeriod(value)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{value === \"upcoming\" ? \"Upcoming\" : \"Past\"}\n\t\t\t\t\t\t\n\t\t\t\t\t))}\n\t\t\t\t
\n\t\t\t
\n\t\t\t{cancel.error && (\n\t\t\t\t

\n\t\t\t\t\t{cancel.error.message}\n\t\t\t\t

\n\t\t\t)}\n\t\t\t{bookings.length === 0 ? (\n\t\t\t\t

\n\t\t\t\t\tNo {period} bookings.\n\t\t\t\t

\n\t\t\t) : (\n\t\t\t\t
    \n\t\t\t\t\t{bookings.map((booking) => (\n\t\t\t\t\t\t
  • \n\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t\t

    {booking.eventName}

    \n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t{booking.status === \"cancelled\"\n\t\t\t\t\t\t\t\t\t\t? \"Cancelled\"\n\t\t\t\t\t\t\t\t\t\t: booking.status === \"pending_payment\"\n\t\t\t\t\t\t\t\t\t\t\t? \"Payment pending\"\n\t\t\t\t\t\t\t\t\t\t\t: \"Confirmed\"}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
    \n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t{formatCalendarTime(booking.start, booking.timezone)} (\n\t\t\t\t\t\t\t\t{booking.timezone})\n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\t{booking.name} · {booking.email}\n\t\t\t\t\t\t\t

    \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t{booking.status !== \"cancelled\" && (\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t cancel.mutate(booking.id)}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tCancel booking\n\t\t\t\t\t\t\t\t\t\t for {booking.name}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t
  • \n\t\t\t\t\t))}\n\t\t\t\t
\n\t\t\t)}\n\t\t
\n\t);\n}\n", "target": "src/components/btst/calendar/client/components/pages/dashboard.tsx" }, { "path": "btst/calendar/client/components/pages/event-editor.tsx", "type": "registry:page", - "content": "\"use client\";\n\nimport { useId, useState, type FormEvent } from \"react\";\nimport { PermissionRouteAccess } from \"@btst/stack/client/components\";\nimport { usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { calendarPermissions } from \"../../../permissions\";\nimport { createEventTypeSchema } from \"../../../schemas\";\nimport type { CalendarEventInput } from \"@btst/plugin-calendar/query-keys\";\nimport type { TimeInterval } from \"../../../types\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseCalendarEvent,\n\tuseCreateCalendarEvent,\n\tuseUpdateCalendarEvent,\n} from \"@btst/plugin-calendar/client/hooks\";\nimport {\n\tCalendarLoading,\n\tCalendarPage,\n\tField,\n\tcalendarSelectClass,\n} from \"../shared\";\n\nconst days = [\n\t\"Sunday\",\n\t\"Monday\",\n\t\"Tuesday\",\n\t\"Wednesday\",\n\t\"Thursday\",\n\t\"Friday\",\n\t\"Saturday\",\n];\nconst emptyEvent: CalendarEventInput = {\n\tname: \"\",\n\tslug: \"\",\n\tdescription: \"\",\n\tlocation: \"\",\n\tduration: 30,\n\tcapacity: 1,\n\ttimezone: \"UTC\",\n\tactive: true,\n\tlimits: {},\n\tdateOverrides: [],\n\tweeklyAvailability: [1, 2, 3, 4, 5].map((dayOfWeek) => ({\n\t\tdayOfWeek,\n\t\tstart: \"09:00\",\n\t\tend: \"17:00\",\n\t})),\n};\n\nexport function CalendarEventEditorPage({ id }: { id?: string }) {\n\treturn id ? (\n\t\t\n\t) : (\n\t\t\n\t);\n}\n\nfunction ExistingEventEditor({ id }: { id: string }) {\n\tconst { data: event } = useCalendarEvent(id);\n\treturn (\n\t\t\n\t\t\t\n\t\t\n\t);\n}\n\nfunction IntervalFields({\n\tvalue,\n\tonChange,\n\tlabel,\n}: {\n\tvalue: TimeInterval;\n\tonChange: (value: TimeInterval) => void;\n\tlabel: string;\n}) {\n\tconst endHintId = useId();\n\treturn (\n\t\t
\n\t\t\t onChange({ ...value, start: e.target.value })}\n\t\t\t/>\n\t\t\t
\n\t\t\t\t onChange({ ...value, end: e.target.value })}\n\t\t\t\t/>\n\t\t\t\t

\n\t\t\t\t\tHH:mm, up to 24:00.\n\t\t\t\t

\n\t\t\t
\n\t\t
\n\t);\n}\n\nfunction EventForm({\n\tid,\n\tinitial,\n}: {\n\tid?: string;\n\tinitial: CalendarEventInput;\n}) {\n\tconst [form, setForm] = useState(initial);\n\tconst [validationError, setValidationError] = useState(\"\");\n\tconst create = useCreateCalendarEvent();\n\tconst update = useUpdateCalendarEvent();\n\tconst { Link, navigate, resolve } =\n\t\tusePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\tconst pending = create.isPending || update.isPending;\n\tconst error =\n\t\tvalidationError || create.error?.message || update.error?.message;\n\tconst submit = async (e: FormEvent) => {\n\t\te.preventDefault();\n\t\tconst parsed = createEventTypeSchema.safeParse(form);\n\t\tif (!parsed.success) {\n\t\t\tsetValidationError(\n\t\t\t\tparsed.error.issues[0]?.message ??\n\t\t\t\t\t\"Check the event details and availability.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tsetValidationError(\"\");\n\t\ttry {\n\t\t\tif (id) await update.mutateAsync({ id, data: parsed.data });\n\t\t\telse await create.mutateAsync(parsed.data);\n\t\t\tvoid navigate(\"calendar\");\n\t\t} catch {\n\t\t\t// The mutation exposes its validation or authorization error in the form.\n\t\t}\n\t};\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\tBack to calendar\n\t\t\t\t\n\t\t\t\t

\n\t\t\t\t\t{id ? \"Edit event type\" : \"New event type\"}\n\t\t\t\t

\n\t\t\t
\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\tEvent details\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, name: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, slug: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tsetForm({ ...form, duration: Number(e.target.value) })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{[15, 30, 45, 60].map((value) => (\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tsetForm({ ...form, capacity: Number(e.target.value) })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, timezone: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, location: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t
\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({ ...form, description: e.target.value })\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\tWeekly availability\n\t\t\t\t\t

\n\t\t\t\t\t\tAdd time windows in the host timezone. Days without a window are\n\t\t\t\t\t\tunavailable.\n\t\t\t\t\t

\n\t\t\t\t\t{form.weeklyAvailability.map((rule, index) => (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tweeklyAvailability: form.weeklyAvailability.map(\n\t\t\t\t\t\t\t\t\t\t\t(item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t? { ...item, dayOfWeek: Number(e.target.value) }\n\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{days.map((day, value) => (\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tweeklyAvailability: form.weeklyAvailability.map(\n\t\t\t\t\t\t\t\t\t\t\t(item, i) => (i === index ? { ...item, ...value } : item),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tweeklyAvailability: form.weeklyAvailability.filter(\n\t\t\t\t\t\t\t\t\t\t\t(_, i) => i !== index,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tRemove\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t))}\n\t\t\t\t\t\n\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\tweeklyAvailability: [\n\t\t\t\t\t\t\t\t\t...form.weeklyAvailability,\n\t\t\t\t\t\t\t\t\t{ dayOfWeek: 1, start: \"09:00\", end: \"17:00\" },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\t\t\t\tAdd availability window\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\tDate overrides\n\t\t\t\t\t

\n\t\t\t\t\t\tOverride a date in the host timezone. Leave its time windows empty\n\t\t\t\t\t\tto block the whole day.\n\t\t\t\t\t

\n\t\t\t\t\t{form.dateOverrides.length === 0 && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\tNo date overrides. Weekly availability applies every week.\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t{form.dateOverrides.map((override, index) => (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? { ...item, date: e.target.value }\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.filter(\n\t\t\t\t\t\t\t\t\t\t\t\t(_, i) => i !== index,\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\tRemove date\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t{override.intervals.length === 0 && (\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\tUnavailable all day.\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{override.intervals.map((interval, intervalIndex) => (\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tintervals: item.intervals.map((entry, j) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tj === intervalIndex ? value : entry,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tintervals: item.intervals.filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(_, j) => j !== intervalIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tRemove window\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintervals: [\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item.intervals,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ start: \"09:00\", end: \"17:00\" },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tAdd override window\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t))}\n\t\t\t\t\t\n\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\tdateOverrides: [\n\t\t\t\t\t\t\t\t\t...form.dateOverrides,\n\t\t\t\t\t\t\t\t\t{ date: \"\", intervals: [] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\t\t\t\tAdd date override\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\tBooking limits\n\t\t\t\t\t

\n\t\t\t\t\t\tLeave a limit empty for no limit.\n\t\t\t\t\t

\n\t\t\t\t\t
\n\t\t\t\t\t\t{(\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t[\"perHour\", \"Max bookings per hour\"],\n\t\t\t\t\t\t\t\t[\"perDay\", \"Max bookings per day\"],\n\t\t\t\t\t\t\t\t[\"perWeek\", \"Max bookings per week\"],\n\t\t\t\t\t\t\t\t[\"total\", \"Max bookings total\"],\n\t\t\t\t\t\t\t] as const\n\t\t\t\t\t\t).map(([key, label]) => (\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\tlimits: {\n\t\t\t\t\t\t\t\t\t\t\t\t...form.limits,\n\t\t\t\t\t\t\t\t\t\t\t\t[key]: e.target.value\n\t\t\t\t\t\t\t\t\t\t\t\t\t? Number(e.target.value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t))}\n\t\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t{error && (\n\t\t\t\t\t

\n\t\t\t\t\t\t{error}\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t\t\n\t\t\t\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\n\nimport { useId, useState, type FormEvent } from \"react\";\nimport { PermissionRouteAccess } from \"@btst/stack/client/components\";\nimport { usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { calendarPermissions } from \"../../../permissions\";\nimport { createEventTypeSchema } from \"../../../schemas\";\nimport type { CalendarEventInput } from \"@btst/plugin-calendar/query-keys\";\nimport type { TimeInterval } from \"../../../types\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport {\n\tuseCalendarEvent,\n\tuseCreateCalendarEvent,\n\tuseUpdateCalendarEvent,\n} from \"@btst/plugin-calendar/client/hooks\";\nimport {\n\tCalendarLoading,\n\tCalendarPage,\n\tField,\n\tcalendarSelectClass,\n} from \"../shared\";\n\nconst days = [\n\t\"Sunday\",\n\t\"Monday\",\n\t\"Tuesday\",\n\t\"Wednesday\",\n\t\"Thursday\",\n\t\"Friday\",\n\t\"Saturday\",\n];\nconst emptyEvent: CalendarEventInput = {\n\tname: \"\",\n\tslug: \"\",\n\tdescription: \"\",\n\tlocation: \"\",\n\tduration: 30,\n\tcapacity: 1,\n\ttimezone: \"UTC\",\n\tactive: true,\n\tlimits: {},\n\tdateOverrides: [],\n\tweeklyAvailability: [1, 2, 3, 4, 5].map((dayOfWeek) => ({\n\t\tdayOfWeek,\n\t\tstart: \"09:00\",\n\t\tend: \"17:00\",\n\t})),\n};\n\nexport function CalendarEventEditorPage({ id }: { id?: string }) {\n\treturn id ? (\n\t\t\n\t) : (\n\t\t\n\t);\n}\n\nfunction ExistingEventEditor({ id }: { id: string }) {\n\tconst { data: event } = useCalendarEvent(id);\n\treturn (\n\t\t\n\t\t\t\n\t\t\n\t);\n}\n\nfunction IntervalFields({\n\tvalue,\n\tonChange,\n\tlabel,\n}: {\n\tvalue: TimeInterval;\n\tonChange: (value: TimeInterval) => void;\n\tlabel: string;\n}) {\n\tconst endHintId = useId();\n\treturn (\n\t\t
\n\t\t\t onChange({ ...value, start: e.target.value })}\n\t\t\t/>\n\t\t\t
\n\t\t\t\t onChange({ ...value, end: e.target.value })}\n\t\t\t\t/>\n\t\t\t\t

\n\t\t\t\t\tHH:mm, up to 24:00.\n\t\t\t\t

\n\t\t\t
\n\t\t
\n\t);\n}\n\nfunction EventForm({\n\tid,\n\tinitial,\n}: {\n\tid?: string;\n\tinitial: CalendarEventInput;\n}) {\n\tconst [form, setForm] = useState(initial);\n\tconst [validationError, setValidationError] = useState(\"\");\n\tconst create = useCreateCalendarEvent();\n\tconst update = useUpdateCalendarEvent();\n\tconst { Link, navigate, resolve } =\n\t\tusePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\tconst pending = create.isPending || update.isPending;\n\tconst error =\n\t\tvalidationError || create.error?.message || update.error?.message;\n\tconst submit = async (e: FormEvent) => {\n\t\te.preventDefault();\n\t\tconst parsed = createEventTypeSchema.safeParse(form);\n\t\tif (!parsed.success) {\n\t\t\tsetValidationError(\n\t\t\t\tparsed.error.issues[0]?.message ??\n\t\t\t\t\t\"Check the event details and availability.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tsetValidationError(\"\");\n\t\ttry {\n\t\t\tif (id) await update.mutateAsync({ id, data: parsed.data });\n\t\t\telse await create.mutateAsync(parsed.data);\n\t\t\tvoid navigate(\"calendar\");\n\t\t} catch {\n\t\t\t// The mutation exposes its validation or authorization error in the form.\n\t\t}\n\t};\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\tBack to calendar\n\t\t\t\t\n\t\t\t\t

\n\t\t\t\t\t{id ? \"Edit event type\" : \"New event type\"}\n\t\t\t\t

\n\t\t\t
\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\tEvent details\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, name: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, slug: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tsetForm({ ...form, duration: Number(e.target.value) })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{[15, 30, 45, 60].map((value) => (\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tsetForm({ ...form, capacity: Number(e.target.value) })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, timezone: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\tprice: e.target.value === \"\" ? null : Number(e.target.value),\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\tcurrency:\n\t\t\t\t\t\t\t\t\t\te.target.value === \"\" ? null : e.target.value.toUpperCase(),\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t setForm({ ...form, location: e.target.value })}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\n\t\t\t\t\t
\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({ ...form, description: e.target.value })\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\n\t\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t
\n\t\t\t\t\tWeekly availability\n\t\t\t\t\t

\n\t\t\t\t\t\tAdd time windows in the host timezone. Days without a window are\n\t\t\t\t\t\tunavailable.\n\t\t\t\t\t

\n\t\t\t\t\t{form.weeklyAvailability.map((rule, index) => (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tweeklyAvailability: form.weeklyAvailability.map(\n\t\t\t\t\t\t\t\t\t\t\t(item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t? { ...item, dayOfWeek: Number(e.target.value) }\n\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{days.map((day, value) => (\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tweeklyAvailability: form.weeklyAvailability.map(\n\t\t\t\t\t\t\t\t\t\t\t(item, i) => (i === index ? { ...item, ...value } : item),\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tweeklyAvailability: form.weeklyAvailability.filter(\n\t\t\t\t\t\t\t\t\t\t\t(_, i) => i !== index,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tRemove\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t))}\n\t\t\t\t\t\n\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\tweeklyAvailability: [\n\t\t\t\t\t\t\t\t\t...form.weeklyAvailability,\n\t\t\t\t\t\t\t\t\t{ dayOfWeek: 1, start: \"09:00\", end: \"17:00\" },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\t\t\t\tAdd availability window\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\tDate overrides\n\t\t\t\t\t

\n\t\t\t\t\t\tOverride a date in the host timezone. Leave its time windows empty\n\t\t\t\t\t\tto block the whole day.\n\t\t\t\t\t

\n\t\t\t\t\t{form.dateOverrides.length === 0 && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\tNo date overrides. Weekly availability applies every week.\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t{form.dateOverrides.map((override, index) => (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? { ...item, date: e.target.value }\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.filter(\n\t\t\t\t\t\t\t\t\t\t\t\t(_, i) => i !== index,\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\tRemove date\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t{override.intervals.length === 0 && (\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\tUnavailable all day.\n\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{override.intervals.map((interval, intervalIndex) => (\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tintervals: item.intervals.map((entry, j) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tj === intervalIndex ? value : entry,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tintervals: item.intervals.filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(_, j) => j !== intervalIndex,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tRemove window\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\tdateOverrides: form.dateOverrides.map((item, i) =>\n\t\t\t\t\t\t\t\t\t\t\ti === index\n\t\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tintervals: [\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t...item.intervals,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{ start: \"09:00\", end: \"17:00\" },\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t: item,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tAdd override window\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t))}\n\t\t\t\t\t\n\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\tdateOverrides: [\n\t\t\t\t\t\t\t\t\t...form.dateOverrides,\n\t\t\t\t\t\t\t\t\t{ date: \"\", intervals: [] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t>\n\t\t\t\t\t\tAdd date override\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\tBooking limits\n\t\t\t\t\t

\n\t\t\t\t\t\tLeave a limit empty for no limit.\n\t\t\t\t\t

\n\t\t\t\t\t
\n\t\t\t\t\t\t{(\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t[\"perHour\", \"Max bookings per hour\"],\n\t\t\t\t\t\t\t\t[\"perDay\", \"Max bookings per day\"],\n\t\t\t\t\t\t\t\t[\"perWeek\", \"Max bookings per week\"],\n\t\t\t\t\t\t\t\t[\"total\", \"Max bookings total\"],\n\t\t\t\t\t\t\t] as const\n\t\t\t\t\t\t).map(([key, label]) => (\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tsetForm({\n\t\t\t\t\t\t\t\t\t\t\t...form,\n\t\t\t\t\t\t\t\t\t\t\tlimits: {\n\t\t\t\t\t\t\t\t\t\t\t\t...form.limits,\n\t\t\t\t\t\t\t\t\t\t\t\t[key]: e.target.value\n\t\t\t\t\t\t\t\t\t\t\t\t\t? Number(e.target.value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t))}\n\t\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t{error && (\n\t\t\t\t\t

\n\t\t\t\t\t\t{error}\n\t\t\t\t\t

\n\t\t\t\t)}\n\t\t\t\t\n\t\t\t\n\t\t
\n\t);\n}\n", "target": "src/components/btst/calendar/client/components/pages/event-editor.tsx" }, + { + "path": "btst/calendar/client/components/pages/reschedule.tsx", + "type": "registry:page", + "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { usePluginSiteNavigation } from \"@btst/stack/context\";\nimport { Button } from \"@/components/ui/button\";\nimport type { Booking } from \"../../../types\";\nimport {\n\tuseCalendarBooking,\n\tuseCalendarRescheduleSlots,\n\tuseRescheduleCalendarBooking,\n} from \"@btst/plugin-calendar/client/hooks\";\nimport { CALENDAR_PLUGIN_ID } from \"../../constants\";\nimport { CalendarPage, formatCalendarTime } from \"../shared\";\nimport { CalendarTimePicker } from \"../time-picker\";\nimport { CalendarInviteDownload } from \"../invite-download\";\n\nexport function CalendarReschedulePage({ token }: { token: string }) {\n\tconst { data: booking } = useCalendarBooking(token);\n\treturn booking.status === \"cancelled\" ||\n\t\tDate.parse(booking.start) <= Date.now() ? (\n\t\t\n\t\t\t

Booking cannot be rescheduled

\n\t\t\t

Only upcoming active bookings can be rescheduled.

\n\t\t
\n\t) : (\n\t\t\n\t);\n}\n\nfunction RescheduleForm({\n\ttoken,\n\tbooking,\n}: {\n\ttoken: string;\n\tbooking: Booking;\n}) {\n\tconst [timezone, setTimezone] = useState(booking.timezone);\n\tconst [date, setDate] = useState(() =>\n\t\tnew Intl.DateTimeFormat(\"en-CA\", {\n\t\t\ttimeZone: booking.timezone,\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"2-digit\",\n\t\t\tday: \"2-digit\",\n\t\t}).format(new Date(booking.start)),\n\t);\n\tconst [start, setStart] = useState(\"\");\n\tconst slots = useCalendarRescheduleSlots(token, date, timezone);\n\tconst reschedule = useRescheduleCalendarBooking();\n\tconst { Link, resolve } = usePluginSiteNavigation(CALENDAR_PLUGIN_ID);\n\tconst chosen = slots.data?.slots.find((slot) => slot.start === start);\n\tconst current = reschedule.data ?? booking;\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t

\n\t\t\t\t\t{reschedule.data ? \"Booking rescheduled\" : \"Reschedule booking\"}\n\t\t\t\t

\n\t\t\t\t

{booking.eventName}

\n\t\t\t\t

\n\t\t\t\t\t{formatCalendarTime(current.start, current.timezone)} (\n\t\t\t\t\t{current.timezone})\n\t\t\t\t

\n\t\t\t
\n\t\t\t{reschedule.data ? (\n\t\t\t\t
\n\t\t\t\t\t

\n\t\t\t\t\t\t{reschedule.data.status === \"pending_payment\"\n\t\t\t\t\t\t\t? \"Your time has moved. Payment is still pending.\"\n\t\t\t\t\t\t\t: \"Your booking has moved to the new time.\"}\n\t\t\t\t\t

\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t) : (\n\t\t\t\t
\n\t\t\t\t\t

\n\t\t\t\t\t\tYour current time stays reserved until the new time is confirmed.\n\t\t\t\t\t

\n\t\t\t\t\t\n\t\t\t\t\t{reschedule.error && (\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\t{reschedule.error.message}\n\t\t\t\t\t\t

\n\t\t\t\t\t)}\n\t\t\t\t\t reschedule.mutate({ token, start, timezone })}\n\t\t\t\t\t>\n\t\t\t\t\t\t{reschedule.isPending ? \"Moving booking…\" : \"Confirm new time\"}\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t)}\n\t\t\t\n\t\t\t\tManage booking\n\t\t\t\n\t\t
\n\t);\n}\n", + "target": "src/components/btst/calendar/client/components/pages/reschedule.tsx" + }, { "path": "btst/calendar/client/components/shared.tsx", "type": "registry:component", - "content": "\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { FallbackProps } from \"@btst/stack/client/components\";\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\n\nexport function CalendarPage({ children }: { children: ReactNode }) {\n\treturn (\n\t\t
\n\t\t\t{children}\n\t\t
\n\t);\n}\n\nexport function CalendarLoading() {\n\treturn (\n\t\t\n\t\t\t

Loading calendar…

\n\t\t
\n\t);\n}\n\nexport function CalendarError({ error, resetErrorBoundary }: FallbackProps) {\n\tconst message =\n\t\tprocess.env.NODE_ENV === \"development\" && error instanceof Error\n\t\t\t? error.message\n\t\t\t: \"Calendar information could not be loaded. Check your link or try again.\";\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t

Calendar unavailable

\n\t\t\t\t

{message}

\n\t\t\t\t\n\t\t\t\t\tRetry loading\n\t\t\t\t\n\t\t\t
\n\t\t
\n\t);\n}\n\nexport function CalendarNotFound({ message }: { message: string }) {\n\treturn (\n\t\t\n\t\t\t

Booking page not found

\n\t\t\t

{message}

\n\t\t
\n\t);\n}\n\nexport function Field({\n\tlabel,\n\tid,\n\tchildren,\n\thint,\n}: {\n\tlabel: string;\n\tid: string;\n\tchildren: ReactNode;\n\thint?: string;\n}) {\n\treturn (\n\t\t
\n\t\t\t\n\t\t\t{children}\n\t\t\t{hint &&

{hint}

}\n\t\t
\n\t);\n}\n\nexport const calendarSelectClass =\n\t\"border-input bg-background min-h-11 w-full min-w-0 rounded-md border px-3 text-sm focus-visible:outline-2 focus-visible:outline-ring\";\n\nexport function formatCalendarTime(value: string, timezone: string) {\n\treturn new Intl.DateTimeFormat(undefined, {\n\t\tdateStyle: \"medium\",\n\t\ttimeStyle: \"short\",\n\t\ttimeZone: timezone,\n\t}).format(new Date(value));\n}\n", + "content": "\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { FallbackProps } from \"@btst/stack/client/components\";\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\n\nexport function CalendarPage({ children }: { children: ReactNode }) {\n\treturn (\n\t\t
\n\t\t\t{children}\n\t\t
\n\t);\n}\n\nexport function CalendarLoading() {\n\treturn (\n\t\t\n\t\t\t

Loading calendar…

\n\t\t
\n\t);\n}\n\nexport function CalendarError({ error, resetErrorBoundary }: FallbackProps) {\n\tconst message =\n\t\tprocess.env.NODE_ENV === \"development\" && error instanceof Error\n\t\t\t? error.message\n\t\t\t: \"Calendar information could not be loaded. Check your link or try again.\";\n\treturn (\n\t\t\n\t\t\t
\n\t\t\t\t

Calendar unavailable

\n\t\t\t\t

{message}

\n\t\t\t\t\n\t\t\t\t\tRetry loading\n\t\t\t\t\n\t\t\t
\n\t\t
\n\t);\n}\n\nexport function CalendarNotFound({ message }: { message: string }) {\n\treturn (\n\t\t\n\t\t\t

Booking page not found

\n\t\t\t

{message}

\n\t\t
\n\t);\n}\n\nexport function Field({\n\tlabel,\n\tid,\n\tchildren,\n\thint,\n}: {\n\tlabel: string;\n\tid: string;\n\tchildren: ReactNode;\n\thint?: string;\n}) {\n\treturn (\n\t\t
\n\t\t\t\n\t\t\t{children}\n\t\t\t{hint &&

{hint}

}\n\t\t
\n\t);\n}\n\nexport const calendarSelectClass =\n\t\"border-input bg-background min-h-11 w-full min-w-0 rounded-md border px-3 text-sm focus-visible:outline-2 focus-visible:outline-ring\";\n\nexport function formatCalendarTime(value: string, timezone: string) {\n\treturn new Intl.DateTimeFormat(undefined, {\n\t\tdateStyle: \"medium\",\n\t\ttimeStyle: \"short\",\n\t\ttimeZone: timezone,\n\t}).format(new Date(value));\n}\n\nexport function formatCalendarPrice(price: number, currency: string) {\n\tconst formatter = new Intl.NumberFormat(undefined, {\n\t\tstyle: \"currency\",\n\t\tcurrency,\n\t});\n\treturn formatter.format(\n\t\tprice / 10 ** (formatter.resolvedOptions().maximumFractionDigits ?? 2),\n\t);\n}\n", "target": "src/components/btst/calendar/client/components/shared.tsx" }, + { + "path": "btst/calendar/client/components/time-picker.tsx", + "type": "registry:component", + "content": "\"use client\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport type { useCalendarSlots } from \"@btst/plugin-calendar/client/hooks\";\nimport { Field, calendarSelectClass } from \"./shared\";\n\nexport function calendarToday(timezone: string) {\n\treturn new Intl.DateTimeFormat(\"en-CA\", {\n\t\ttimeZone: timezone,\n\t\tyear: \"numeric\",\n\t\tmonth: \"2-digit\",\n\t\tday: \"2-digit\",\n\t}).format(new Date());\n}\n\nexport function CalendarTimePicker({\n\tdate,\n\ttimezone,\n\tstart,\n\tonDate,\n\tonTimezone,\n\tonStart,\n\tslots,\n\tcapacity = 1,\n}: {\n\tdate: string;\n\ttimezone: string;\n\tstart: string;\n\tonDate: (date: string) => void;\n\tonTimezone: (timezone: string) => void;\n\tonStart: (start: string) => void;\n\tslots: ReturnType;\n\tcapacity?: number;\n}) {\n\tconst zones = Array.from(\n\t\tnew Set([timezone, \"UTC\", ...Intl.supportedValuesOf(\"timeZone\")]),\n\t);\n\treturn (\n\t\t\n\t\t\t

\n\t\t\t\tChoose a time\n\t\t\t

\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\t {\n\t\t\t\t\t\t\tif (e.target.value) {\n\t\t\t\t\t\t\t\tonDate(e.target.value);\n\t\t\t\t\t\t\t\tonStart(\"\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}}\n\t\t\t\t\t/>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t {\n\t\t\t\t\t\t\tonTimezone(e.target.value);\n\t\t\t\t\t\t\tonStart(\"\");\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\t{zones.map((zone) => (\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t))}\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t
\n\t\t\t{slots.isPending || slots.isFetching ? (\n\t\t\t\t

Loading available times…

\n\t\t\t) : slots.error ? (\n\t\t\t\t
\n\t\t\t\t\t

{slots.error.message}

\n\t\t\t\t\t void slots.refetch()}\n\t\t\t\t\t>\n\t\t\t\t\t\tRetry available times\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t) : slots.data?.slots.length === 0 ? (\n\t\t\t\t

\n\t\t\t\t\tNo available times on this date. Choose another date.\n\t\t\t\t

\n\t\t\t) : (\n\t\t\t\t
\n\t\t\t\t\t{slots.data?.slots.map((slot) => (\n\t\t\t\t\t\t onStart(slot.start)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{new Intl.DateTimeFormat(undefined, {\n\t\t\t\t\t\t\t\thour: \"numeric\",\n\t\t\t\t\t\t\t\tminute: \"2-digit\",\n\t\t\t\t\t\t\t\ttimeZoneName: \"short\",\n\t\t\t\t\t\t\t\ttimeZone: timezone,\n\t\t\t\t\t\t\t}).format(new Date(slot.start))}\n\t\t\t\t\t\t\t{capacity > 1 && (\n\t\t\t\t\t\t\t\t({slot.remaining} left)\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\n\t\t\t\t\t))}\n\t\t\t\t
\n\t\t\t)}\n\t\t\n\t);\n}\n", + "target": "src/components/btst/calendar/client/components/time-picker.tsx" + }, { "path": "btst/calendar/client/constants.ts", "type": "registry:lib", diff --git a/scripts/codegen/files/nextjs/lib/authorization.ts b/scripts/codegen/files/nextjs/lib/authorization.ts index b86965b61..8389dedac 100644 --- a/scripts/codegen/files/nextjs/lib/authorization.ts +++ b/scripts/codegen/files/nextjs/lib/authorization.ts @@ -291,6 +291,7 @@ export const authorization = defineAuthorization({ ({ 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, ), diff --git a/scripts/codegen/files/react-router/app/lib/authorization.ts b/scripts/codegen/files/react-router/app/lib/authorization.ts index b86965b61..8389dedac 100644 --- a/scripts/codegen/files/react-router/app/lib/authorization.ts +++ b/scripts/codegen/files/react-router/app/lib/authorization.ts @@ -291,6 +291,7 @@ export const authorization = defineAuthorization({ ({ 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, ), diff --git a/scripts/codegen/files/tanstack/src/lib/authorization.ts b/scripts/codegen/files/tanstack/src/lib/authorization.ts index b86965b61..8389dedac 100644 --- a/scripts/codegen/files/tanstack/src/lib/authorization.ts +++ b/scripts/codegen/files/tanstack/src/lib/authorization.ts @@ -291,6 +291,7 @@ export const authorization = defineAuthorization({ ({ 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, ),