# Scheduling app ## What this builds A complete, self-hosted scheduling web app in the style of the well-known open-source booking tools. A host signs up, sets the hours they can meet, creates kinds of meeting ("event types"), and shares a public booking page. A visitor opens that page in any time zone, picks a day and a free time, fills in a short form and gets a confirmation page from which they can reschedule or cancel. The host sees every booking in a list, accepts or declines the ones that need approval, and can cancel or move them. It is one Cloudflare Worker: the React single-page app is served as the Worker's static assets, the JSON API runs in the Worker, and the data lives in one Cloudflare D1 (SQLite) database. It runs on a laptop with `npm install` and `npm run dev` (which uses `wrangler dev` and a local D1, with no Cloudflare account), deploys with `npm run deploy`, and needs no other service by default: no email, calendar or video provider, no KV, no Durable Object. Email and calendar connections are optional add-ons (R15-R18), each off until configured. Read `spekkr.inputs.json` first. `app_name` is the product name shown in the sidebar, the page titles and the booking page footer. `brand_color` is the accent colour (primary buttons, selected day, focus rings). `seed_demo` turns the demo data in `design.md` ("Demo data") on or off. `design.md` has the data model, the API, the slot maths, every screen and the visual style. `tasks.md` gives the order to build in. `research.md` says what the design was modelled on and why some choices differ. It ships with the spec as provenance and verification notes; read it for context, not for additional build requirements. All build requirements are in the first three files above. ## Names and words - The product is called `app_name` everywhere. The built app never shows the name, logo, icons or wording of any other scheduling product. - Every piece of interface text the spec quotes is the text to use. Text the spec does not quote is the builder's own, short and plain. - No image, font or icon file is copied from anywhere. Icons are inline SVG drawn in the app's own code, or plain text. ## Out of scope - Teams, round-robin, collective or managed events, organisations, routing forms, workflows, webhooks, an app store. - Video services, payments, SMS. Outside calendars and email only through the optional integrations R15-R18, each off unless configured. - Sending email when R15 is not configured. Then, where a real product would email someone, the Worker writes a line to the server log that starts with `[mail]`, with the address masked to its first character and domain (`p***@example.com`) and what happened, and nothing else. Logs never hold a full guest address. - Recurring events and seats (more than one booker per slot). ## Landing page `/` is a small entry route, not a marketing page. It checks the session and redirects a signed-in host to `/event-types`, or a signed-out visitor to `/login`. Show a short loading state while the check runs. The login page links to sign-up. ## Requirements Each requirement has an id. Tests name the id they cover. ### R1. Run and store - Runtime: Cloudflare Workers only. The Worker code uses Web APIs (`fetch` handler, `Request`, `Response`, `crypto.subtle`, `crypto.getRandomValues`, `Intl`) and no Node.js built-in module (`node:*`, `fs`, `Buffer`, `process`), so it needs no `nodejs_compat` flag. Node.js is only the build and test tool on the developer's machine. - `wrangler.jsonc` (exact shape in `design.md`, "Cloudflare config") names the Worker, sets `main` to the Worker entry, serves `dist/` as static assets with single-page-app fallback, routes `/api/*` to the Worker first, binds one D1 database as `DB`, declares the vars `NOW` and `TEST_CLOCK`, and turns on observability (logs and traces). - `npm run build` builds the client into `dist/` with Vite; Wrangler bundles the Worker itself. `npm run dev` builds, applies the D1 migrations to the local database (`wrangler d1 migrations apply DB --local`) and runs `wrangler dev` (default port 8787). `npm run deploy` builds and runs `wrangler deploy`. The README gives the one-time deploy steps from `design.md` ("Deploy"). - Data is kept in D1. The schema lives in `migrations/0001_init.sql` and is applied with `wrangler d1 migrations apply`; the Worker never creates tables. Every time is stored as a UTC ISO 8601 string ending in `Z`, or as minutes from local midnight where `design.md` says so; bookings also keep their start and end as integer epoch milliseconds for the overlap guard. - The clock: the var `NOW` (an ISO time), when not empty, freezes the Worker's clock at that moment for tests and screenshots. When the var `TEST_CLOCK` is `"1"` (tests only, never in production), a `test_now` cookie on a request overrides the clock for that request. Otherwise the real clock is used. The client always asks the server what time it is (`GET /api/now`) rather than trusting the browser's clock, so tests stay in step. Accept when: a fresh clone runs with `npm install` then `npm run dev` without logging in to Cloudflare, `wrangler deploy --dry-run` bundles without errors or Node.js compatibility warnings, and `GET /api/now` returns the `NOW` value when set (`wrangler dev --var NOW:...`). ### R2. Accounts - Sign up with name (up to 80 characters), email, username and password (8–200 characters). Usernames are 3 to 30 characters of `a-z`, `0-9` and `-`, unique, and may not be one of the reserved words in `design.md`. Emails are unique and compared without case. - Each user has exactly one default schedule (enforce at most one with a partial unique index on `schedules(user_id) WHERE is_default=1`; create one at sign-up and never delete or unset it without a replacement). - The new account gets the browser's time zone (sent by the client), a default schedule named "Working hours" with Monday to Friday 09:00 to 17:00 in that zone, and two event types: "Quick chat" (15 minutes, slug `quick-chat`) and "Meeting" (30 minutes, slug `meeting`). - Log in with email and password; log out. A session is a random token in an `HttpOnly`, `SameSite=Lax` cookie named `session` (also `Secure` when the request is HTTPS), valid for 30 days, made from 32 bytes of `crypto.getRandomValues`. Passwords are hashed with Web Crypto PBKDF2 (SHA-256, 100000 iterations, the most Workers allow, 16-byte random salt, 32-byte key), stored as `pbkdf2-sha256$100000$$` and compared with `crypto.subtle.timingSafeEqual`. - Every page under the app (not the public pages) needs a session and sends a visitor without one to `/login`. Accept when: sign-up creates the schedule and both event types, a duplicate email or username is refused with a message on the form, a reserved username is refused, a wrong password says "Email or password is wrong", and logging out then opening `/event-types` lands on `/login`. Owner-only deployments. Two Worker vars, both optional: - `ALLOWED_EMAILS`: a comma-separated list, compared case-insensitively. When it is not empty, only those emails can sign up (403 "This site doesn't accept new accounts for that email"), sign in (403 "This email can't sign in here"), keep a session (a session whose user's email is not on the list counts as signed out), or change their account email to an address off the list ("This site only accepts its owner's email" on the email field). Empty means anyone. Public pages and guest booking, rescheduling and cancelling are never affected. - `ALLOW_SIGNUP`: `"0"` refuses every new account (403 "New accounts are turned off on this site"); existing accounts still sign in. Anything else, or unset, allows sign-up. Accept when: with `ALLOWED_EMAILS` set to one address, signing up or signing in with another address gets 403 and the listed address works; with `ALLOW_SIGNUP` `"0"` sign-up gets 403. ### R3. App layout - A left sidebar 240 px wide on screens 1024 px and wider: `app_name` at the top, then "Event types", "Bookings", "Availability" and "Settings", each with a small inline SVG icon, the current one highlighted. At the bottom, the host's initials in a circle, their name, and a menu with "View public page" (opens `/{username}` in a new tab) and "Sign out". - Under 1024 px the sidebar becomes a bar along the bottom with the same four items, and the user menu moves to the top right. - Every app page has a header: a title, a one-line grey subtitle, and the page's main action button on the right where it has one. - Pages are in `design.md` ("Screens"). Every list has an empty state: an icon, one bold line, one grey line and, where it makes sense, a button. Accept when: at 1280 px the sidebar shows the four items and the user menu, at 390 px the bottom bar shows them, and each item opens its page. ### R4. Event types - `/event-types` lists the host's event types in their saved order. Each row shows the title, the public path `/{username}/{slug}` in grey, a duration badge such as `30m`, a "Needs approval" badge when it requires confirmation, and on the right: a "Hidden" switch, a copy-link button, a preview button (opens the public page in a new tab) and a menu with "Edit", "Duplicate", "Move up", "Move down" and "Delete". - "New" opens a dialog with title, URL slug (filled from the title as it is typed, until the slug is edited by hand), description and duration in minutes. "Continue" creates it and opens its editor. A slug already used by this host is refused on the field. - Delete asks first, in a dialog. Bookings of a deleted event type stay in the bookings list. - Duplicate copies every setting, adds " (copy)" to the title and `-copy` to the slug (then `-copy-2`, and so on, until free), and opens the copy. - The editor at `/event-types/{id}` has a back arrow, the title, the "Hidden" switch and a "Save" button (disabled until something changes) in its header, and four tabs, kept in the address as `?tab=`: - **Setup**: title, description, URL slug (shown after the fixed prefix `{origin}/{username}/`), duration in minutes (5 to 720), and location: one of "Video call" with a link field, "Phone call" (the booker gives their number), "In person" with an address field, or "Custom" with a text field. - **Availability**: which schedule this event uses (a select of the host's schedules, with the default marked) and a read-only weekly summary of it. - **Limits**: buffer before and buffer after (none, 5, 10, 15, 20, 30, 45, 60, 90 or 120 minutes), minimum notice (a number and a unit: minutes, hours or days; default 2 hours), slot step ("Use event length" or 5, 10, 15, 20, 30, 45, 60, 75, 90, 105 or 120 minutes), "Limit bookings per day" (off, or a number), and "Limit how far ahead" (off, or a number of days). - **Advanced**: "Requires approval", "Hide guests field", and an event colour used on the event type row and bookings. Swatches, in order: `#111827`, `#1d4ed8`, `#047857`, `#b45309`, `#be123c`, `#6d28d9`, `#0f766e`, `#c2410c`. Default `#111827`. - Field limits: event title 120 characters, description 2000, location 500; names (profile, booker and schedule) 80; password 8–200 characters; bookings/day 1–100, days ahead 1–730 (both whole numbers, or off); minimum notice 0–365 days (0–525600 minutes inclusive). - Every field is checked on the server too; a bad value comes back as a field error and is shown under the field. Accept when: a Playwright test creates an event type, edits each tab, saves, reloads and sees the values kept; a hidden event type is missing from the public profile but its own page still takes bookings; duplicate and delete behave as above. Meeting link prompt: a video event type with no meeting link shows the badge "Add a meeting link" on its row in the list, and the editor's "Meeting link" field has the help "Guests see this link on their confirmation page. If you leave it empty, they're told you'll share the link." ### R5. Availability - `/availability` lists schedules: name, a "Default" badge on the default one, a summary of its hours such as `Mon - Fri, 9:00am - 5:00pm` (in the host's time format), and its time zone. A menu offers "Set as default", "Duplicate" and "Delete". Duplicate copies the hours, overrides and zone, appends " (copy)" to the name, and is not the default. The default schedule cannot be deleted, and neither can the only one. "New" asks for a name and makes a schedule with the Monday to Friday 09:00 to 17:00 hours in the host's zone. - The schedule editor at `/availability/{id}`: - The name, editable in place, a "Set as default" switch and "Save". - Seven day rows in the host's week order. Each has an on/off switch and, when on, one or more time ranges. Each range is two selects with times in 15-minute steps from 12:00am to 11:45pm for the start, and 12:15am to "12:00am (end of day)" for the end. A "+" adds a range after the last one (one hour after it ends, one hour long, if it fits), a bin icon removes one, and a copy icon opens "Copy times to" with a checkbox per day and an "Apply" button. - A range must end after it starts and ranges on one day may not overlap; the row shows the problem in red and "Save" is disabled. - A time zone select, searchable, of every zone the browser knows (`Intl.supportedValuesOf('timeZone')`), showing each with its current UTC offset, such as `America/New_York (GMT-5)`. - **Date overrides**: a list of upcoming overrides (date, then its ranges or "Unavailable") with a bin icon each, and "Add an override". That opens a dialog with a month calendar where one or more dates are picked, and on the right either time ranges (as in a day row) or the switch "Mark unavailable (all day)". "Add override" adds them to the list. Overrides for dates already past are not shown and are removed on save. - An override replaces the weekly hours for that date completely. Accept when: a test turns a day off, adds a second range, copies a day's times to two others, adds an override with custom hours and an all-day unavailable override, saves, reloads and sees them kept; the booking page then shows exactly the slots the new hours allow (R8). ### R6. Public profile page - `/{username}` shows the host's initials avatar, name and bio, then the heading "Choose a meeting type" and the line "Pick the kind of meeting you'd like with {first name}. Next you'll choose a date and time.", then a list of their event types that are not hidden. Each row shows the title, the description (first two lines), a duration badge (`30 min`), a location badge (`Video call`, `Phone call`, `In person`, `Custom`) and "Choose a time" with a chevron, and links to its booking page. The link's spoken name is "{title}, {n} minutes. Choose a time". - With no visible event types the heading and line are left out and the list shows "Nothing to book right now" and "{first name} has no meeting types open for booking. Check back later." - An unknown username's API request returns 404. The page shows a plain "Nobody here by that name" message; its HTML response is 200 from the SPA fallback, not an HTTP 404. Accept when: the profile shows the heading and line, lists only visible event types in order with description, duration and location, each link opens the right booking page, and a host with every type hidden shows the empty message. ### R7. The booking page At `/{username}/{slug}`. Layout and look are in `design.md` ("The booker"). - **Event details** column: host avatar and name, event title, description, duration, location kind, "Needs approval" when it applies, and the visitor's time zone as a select (same list as R5). The zone starts as the browser's zone, is remembered in `localStorage` under `booker.tz`, and can be changed at any time; every date and time on the page changes with it, and changing it clears the chosen day and time. Browsers may report an old alias for a zone (Chromium says `Asia/Calcutta` for `Asia/Kolkata`); treat aliases as valid zones and show what the browser gives. - **Month calendar**: a month title with previous and next arrows (previous is disabled on the current month), weekday headings in the host's week order, and the days of the month. A day with at least one free slot, in the visitor's zone, is a dark-text button on a light grey tile; any other day is plain grey text and cannot be picked. Today has a small dot under its number. Above the calendar a small heading says "Select a date" ("Select a new date" when rescheduling). The first day with free slots in the shown month is selected when the page opens, if any, replacing the history entry rather than adding one. In reschedule mode the page opens on the month of the booking being moved and selects that booking's day when it has free slots (the moved booking does not block its own slot), otherwise the first free day. "This month is fully booked" with a "View next month" button shows over the grid when the month has no free day. - **Times** column: a small heading "Select a time", the selected day as `Mon 16` (or "No date picked" with "Pick a highlighted date to see open times." under it), a `12h` / `24h` toggle (starts on the host's choice, remembered under `booker.timeFormat`), and a button per free slot showing its start time in the visitor's zone, such as `9:30am` or `09:30`. A day with no slots left says "No times left on this day. Try another highlighted date." - The address holds the state: `?month=YYYY-MM&date=YYYY-MM-DD&slot=`, so reload and back and forward work. - Clicking a time opens the **booking form** in place of the calendar and times: the event details column now also shows the chosen day and time range (for example `Monday, November 16, 2026` and `9:30am - 10:00am`). The form starts with the heading "Enter your details" and the line "Fill these in to book the time shown." (for an event that needs approval: "{host name} confirms requests for this meeting. You'll see the status on the next page."). Fields: "Your name" (required), "Email" (required, checked), "Phone number" (required, only when the location is "Phone call"), "Anything we should know?" (optional, up to 1000 characters), and "+ Add guests" which opens up to 10 more email fields, unless the event hides guests. Buttons: "Back" and "Book it" (or "Request booking" when the event needs approval). While the request runs the button shows a spinner and cannot be pressed again. - If the slot was taken in the meantime the form shows "Someone just took this time. Pick another." and goes back to the times with fresh slots. - On success the page goes to `/booking/{uid}`. Accept when: a test with the browser in `Asia/Kolkata` books a host whose schedule is in `America/New_York`, the times shown are the host's hours converted (09:00 New York shows as 7:30pm in November), the booking is stored at the right UTC instant, and the address state survives a reload. ### R8. Which slots are free The slot rules are in `design.md` ("Slot maths") and must be one pure function, `computeSlots`, used both to list slots and to check a booking. In short: - Slots come from the event's schedule: weekly hours, replaced by a date override on its date, read as wall-clock time in the schedule's zone. - A slot starts on the slot step (or the duration), counted from the start of each available range, and must fit wholly inside the range. - Nothing starts before now plus the minimum notice, or after the "how far ahead" limit. - A slot is not free if it, padded by this event's buffers, overlaps an accepted or pending booking of the same host, padded by that booking's event's buffers. - A day that already has "Limit bookings per day" bookings of this event (accepted or pending) has no free slots. Accept when: the unit tests listed in `design.md` ("Slot tests") pass, including the DST, half-hour-zone, midnight and buffer cases. ### R9. Making a booking - The Worker re-runs `computeSlots` for that day and answers 409 if the start is not a free slot. D1 has no interactive transactions, so the write itself is the guard: the booking is stored by one conditional `INSERT ... SELECT ... WHERE NOT EXISTS (overlapping active booking of the host, buffers included) AND (daily limit not reached)`, given in `design.md` ("Double-booking guard"). D1 runs each statement atomically and one at a time, so if the insert changes no row the answer is 409. Two bookings sent at the same moment for the same or overlapping times, of the same or different event types of one host, give one booking and 409s for the rest. Do not add a unique index on `(host_id, start_ms)`: rescheduling onto the same start is valid and temporarily needs both rows in the atomic batch. The conditional insert is the concurrency guard. No Durable Object or KV is used. - The booking stores the event's title then, the host, start and end in UTC, the booker's name, email, phone, notes, guests and time zone, the location, and status `accepted`, or `pending` when the event needs approval. - The uid is 22 random URL-safe characters. Accept when: a test sends two booking requests for the same slot at once and gets exactly one 201 and one 409; a test sends eight requests at once for one start and the start 30 minutes later across a 30-minute and a 60-minute event type and never gets two overlapping bookings; and a booking with a start that is not a slot (wrong minute, outside hours, past) gets 409. ### R10. Confirmation, reschedule and cancel (visitor side) - `/booking/{uid}` shows a large check mark, a heading and one line that say what happened (exact copy in R14): "You're booked" / "Your meeting with {host} is confirmed."; "Request sent" / "{host} needs to confirm this request. Come back to this page to see if it's confirmed."; "Booking moved" / "Your meeting with {host} is now at the time below. The old time is cancelled.". Then rows "What", "When" (day, time range and zone, in the visitor's zone from `booker.tz`), "Who" (host and booker with their emails, guests), "Where" and "Notes". "Where" is a link when the location is a web address; a video event with no link says "Video call ({host} will share the link)". - For a booking that has not started and is not cancelled, a "What's next" box says "No confirmation email is sent, so keep this page: copy its link, or add the meeting to your calendar. Use this page to reschedule or cancel later." with buttons "Copy link to this page" (copies the address, toast "Link copied") and "Add to calendar" (downloads the `.ics`). When email (R15) is configured the first sentence becomes "We've emailed you the details." Below: "Need a change?" with "Reschedule" and "Cancel". - "Reschedule" opens the booking page of the same event at `/{username}/{slug}?reschedule={uid}`. There, the details column shows a note "Rescheduling your booking" / "Pick a new date and time. The current time stays booked until you confirm the new one.", and "Current time: " with the old time struck through; the form heading is "Confirm your new time" with "Check your details, then move the booking. Your old time is released when you do."; the form is filled with the old answers, there is an optional "Reason for change" field, and the button says "Move booking". The booking being moved does not block its own slot. A reschedule onto the exact same start is allowed: create the new row and cancel the old row in the same guarded D1 batch, just like any other move. On success the old booking becomes `cancelled` with `rescheduled` set, the new one keeps the same answers and points back to the old one (`fromUid`), and the page goes to the new booking's page, which says "Booking moved". - "Cancel" shows, on the same page, "Cancel this booking? {host} will see it's cancelled and the time opens up again. This can't be undone.", a "Reason (optional)" box, "Keep it" and "Cancel booking". After it, the page shows "This booking was cancelled" / "It's cancelled, and {host} can see that in their bookings.", the reason, and a link "Book another time" to the event page. A booking the host cancelled says "{host} cancelled this meeting."; a declined request says "This request was declined" / "{host} can't make this one. You can pick another time." - A cancelled booking cannot be moved or cancelled again: its page says so and shows "Book another time" unless the event type was deleted, but no reschedule or cancel links; `/{username}/{slug}?reschedule={uid}` for it shows "This booking was cancelled, so it can't be moved." with a link to book anew. - A booking that was moved shows "This booking was moved", then "It now has a new time. This old time is released." (or "{host} moved this meeting to a new time." when the host moved it) and a link "See the new time" to the new booking, and no other links. - "Book another time" is left out when the event type has been deleted. - A booking whose start has passed says "This meeting has started or already happened." and shows no "What's next" box and no "Need a change?" links. Accept when: a test books, reschedules from the confirmation page (the page opens on the booking's own day, not the first free day; the old slot comes free again, the new one is taken, the old booking shows as rescheduled with the reason, and its page links to the new one), then cancels the new booking and sees its slot come free; and every heading, line and box above is checked word for word. ### R11. Bookings list (host side) - `/bookings/upcoming`, `/bookings/unconfirmed`, `/bookings/past` and `/bookings/cancelled`, as tabs, each with a count. Definitions are in `design.md`. - Rows are grouped under day headings ("Today", "Tomorrow", or like `Wed, Nov 18`) in the host's zone. Each row shows the time range, the event colour, the title "{event title} with {booker name}", the booker's email and the guests, the location, notes in grey, and badges "Needs approval", "Moved" (a booking made by rescheduling) or "Cancelled by host" / "Cancelled by guest". - Actions: upcoming rows have "Reschedule" and "Cancel" (dialog with a reason); unconfirmed rows have "Accept", "Decline" (dialog with a reason) and "Reschedule". - Host reschedule: "Reschedule" opens `/{username}/{slug}?reschedule={uid}&host=1`. The note says "Moving {booker name}'s booking" and the same instruction as the guest flow. Picking a time does not show the guest form: the step is "Confirm the new time" with "{booker name} ({booker email}) keeps the same details. The old time is released when you move it.", an optional "Reason for change", "Back" and "Move booking". It posts `asHost: true` (see `design.md`); the server requires the signed-in host of that booking (401 without a session, 404 for someone else's booking), copies the guest's name, email, phone, notes, guests and zone from the old booking, stores the new booking as `accepted` even if the event needs approval, and marks the old one `cancelled`, `rescheduled`, `cancelled_by` `host`. The app then goes back to `/bookings/upcoming` with the toast "Booking moved". - The upcoming empty state says "Nothing coming up" / "Share your booking page so people can pick a time. New bookings show up here." with a button "Open your booking page" (opens `/{username}` in a new tab). A declined booking goes to cancelled with status `rejected`. Past and cancelled rows have no actions. - Upcoming and unconfirmed are sorted soonest first; past and cancelled most recent first. Lists load 20 at a time with "Load more". Accept when: the host moves a booking from the list without typing the guest's details and the guest's answers are kept, the old booking says the host moved it, and a pending request can be moved and comes out accepted; a booking made on the public page appears in upcoming with the right time in the host's zone; one needing approval appears in unconfirmed and moves to upcoming on "Accept"; "Decline" and "Cancel" move rows to cancelled; a past booking (seen with the clock moved a month forward by the `test_now` cookie) is in past and has no actions. ### R12. Settings - `/settings/profile`: name, username (with a warning that public links change), email and bio (up to 300 characters). - `/settings/general`: time zone (same select as R5), time format (12 or 24 hour) and week start (Monday or Sunday). These drive every time shown in the app and the booker's starting time format and week layout. - A left sub-menu lists the two pages; "Save" on each; a short "Saved" toast after a save. Accept when: changing the week start to Sunday changes the order of days on the booking page and the schedule editor, and changing the time format changes the bookings list times. ### R13. Quality - Keyboard: every control is reachable with Tab and has a visible focus ring in `brand_color`; dialogs trap focus and close on Escape; calendar days and time buttons have full spoken names such as "Monday, November 16, 2026" and "9:30am, Monday, November 16, 2026". - The booking page is usable at 390 px wide: the columns stack in the order details, calendar, times. - API errors show as a toast with the server's message; nothing fails silently. - The server answers JSON errors as `{ "error": "...", "fields": {...} }`. Accept when: a test tabs through the booking page from the time zone select to a time button and books with the keyboard alone. ### R14. Guidance on every page Every public step says what it is and what to do next, the way well-known booking tools do. The exact copy is in R6, R7, R10 and R11; in one place: | Where | Copy | |---|---| | Profile, list heading | "Choose a meeting type" | | Profile, line | "Pick the kind of meeting you'd like with {first name}. Next you'll choose a date and time." | | Profile, row action | "Choose a time" | | Profile, nothing to book | "Nothing to book right now" / "{first name} has no meeting types open for booking. Check back later." | | Booker, calendar | "Select a date" (reschedule: "Select a new date") | | Booker, times | "Select a time"; no day yet: "Pick a highlighted date to see open times."; day full: "No times left on this day. Try another highlighted date." | | Booker, form | "Enter your details" / "Fill these in to book the time shown." | | Booker, reschedule note | "Rescheduling your booking" / "Pick a new date and time. The current time stays booked until you confirm the new one." | | Booker, reschedule form | "Confirm your new time" / "Check your details, then move the booking. Your old time is released when you do." | | Booker, host reschedule | "Moving {booker}'s booking"; form "Confirm the new time" | | Booking page, next steps | "What's next" box with "Copy link to this page" and "Add to calendar" | | Booking page, cancel | "Cancel this booking? {host} will see it's cancelled and the time opens up again. This can't be undone." | | Bookings, nothing upcoming | "Share your booking page so people can pick a time. New bookings show up here." + "Open your booking page" | | Event types, empty | "Make one, like a 30-minute call, then share its link so people can book you." | | Event types, subtitle | "Kinds of meeting people can book with you. Share a link, or your whole page, so people can pick a time." | The footer under public pages is "Booked with **{app_name}**" as plain text; it does not link to `/`, which would send guests to the host sign-in page. Accept when: a test checks each row of the table on the page it names, on a desktop and a 390 px wide viewport. ## Optional integrations R15-R18 are each off unless configured, and the app must build, run and pass R1-R14 with none of them set. Configuration lives in Worker vars, secrets and bindings (names in `design.md`, "Integrations"). Secrets are set with `wrangler secret put` and are never written to `wrangler.jsonc`, the database in clear text, logs or API responses. A settings page, `/settings/integrations`, shows each integration as "Off", "On" or "Needs attention" with a one-line reason, and the last error, if any. ### R15. Email (optional) - A pluggable sender with one interface, `sendEmail({ to, replyTo, subject, text, html, attachments })`, and three implementations chosen by `EMAIL_PROVIDER`: - `cloudflare`: Cloudflare Email Sending through a `send_email` binding named `EMAIL`. The message is built as raw MIME (see R16) and sent with `env.EMAIL.send(new EmailMessage(fromAddress, to, raw))` from `cloudflare:email`, because the structured `env.EMAIL.send({...})` form can only add the invite as a file attachment, and Gmail needs an inline `text/calendar` part. `From` is `EMAIL_FROM` (for example `"Scheduler" `, split into address and display name), which must be on a domain onboarded to Email Sending and listed in the binding's `allowed_sender_addresses`. `Reply-To` is the host's email for guests (a guest's reply goes to the host) and the booker's email for the host. - `resend`: Resend's HTTP API (`POST https://api.resend.com/emails`) with the secret `RESEND_API_KEY`, the same `From` and `Reply-To` rules, and attachments as base64. - empty or unset: the `[mail]` log line from "Out of scope", nothing sent. - Emails, each to the guest (and guests listed on the booking) and, separately, to the host: - booking confirmed (or request received / request accepted / declined for events that need approval), - booking rescheduled (to the new time; says the old time is cancelled), - booking cancelled (by whom, and the reason), - reminders before the start. Each email has a plain-text and an HTML part with: what, when (in the recipient's zone: the guest's `booker_tz`, the host's zone for the host), where (the link when there is one), and links to `/booking/{uid}` with "Reschedule" and "Cancel" for the guest. Subjects: "Confirmed: {title} with {host} on {day, time}", "Moved: ...", "Cancelled: ...", "Reminder: ... starts in {offset}". - Reminders: a Cron Trigger (`*/5 * * * *`) scans D1 for accepted bookings whose start minus a reminder offset falls in the window since the last run. Offsets are per event type, default `[1440, 60]` minutes, editable on the event's "Limits" tab as checkboxes 1 week / 1 day / 1 hour / 15 minutes. Each send (booking uid, kind, offset, recipient) is recorded in `email_log` with a unique key before sending, so a retry, an overlapping cron run or a second Worker instance never sends the same email twice; a failed send is marked `failed` with the error and retried on the next run up to 3 times. A booking moved or cancelled before its reminder gets no reminder for the old time. - Sending never blocks or fails a booking: the booking is stored first, the email goes out through `ctx.waitUntil`, and a send error is logged and shown under `/settings/integrations`. - Setup, written into the README and shown on `/settings/integrations`: - Cloudflare: Email Sending needs the Workers Paid plan to send to arbitrary recipients (Workers Free can only send to verified addresses in your own account); Paid includes 3,000 emails a month, then $0.35 per 1,000. The domain must use Cloudflare DNS. In the dashboard, Compute > Email Service > Email Sending > Onboard Domain, pick the domain; it adds the SPF and DKIM TXT records, a DMARC TXT record on `_dmarc.` and `cf-bounce` MX records. Wait for the domain to show as verified (usually 5-15 minutes), add `"send_email": [{ "name": "EMAIL" }]` to `wrangler.jsonc`, set `EMAIL_PROVIDER=cloudflare` and `EMAIL_FROM`. - Resend: verify the domain in Resend (it gives SPF, DKIM and an optional DMARC record to add in Cloudflare DNS), then `wrangler secret put RESEND_API_KEY`, set `EMAIL_PROVIDER=resend` and `EMAIL_FROM`. - With email on, the booking page's "What's next" says "We've emailed you the details." instead of "No confirmation email is sent". Accept when: with a fake sender bound in tests, booking, moving and cancelling each produce one guest email and one host email with the right subject, zone and links; the cron handler run twice over the same window sends each reminder once; a moved booking gets reminders only for its new time; and a sender that throws leaves the booking stored and the error shown. ### R16. Calendar invites (.ics, optional, with R15) Every booking email from R15 carries the invite built by one pure function, `buildInvite(booking, kind, sequence, { audience, organizer? })`, following RFC 5545. The email is a MIME message shaped the way Google Calendar and Outlook send invites (one pure function, `buildMime`, CRLF line ends, base64 bodies wrapped at 76 characters): ``` multipart/mixed multipart/alternative text/plain; charset=UTF-8 text/html; charset=UTF-8 text/calendar; charset=UTF-8; method=REQUEST (or CANCEL) application/ics; name="invite.ics" (Content-Disposition: attachment) ``` Headers: `From`, `To`, `Reply-To`, `Subject` (RFC 2047 encoded when not ASCII), `Date`, `Message-ID` on the sending domain, `MIME-Version: 1.0`. Gmail shows its event card and adds the event from the inline `text/calendar` part; the attachment is for other clients. Emails without an invite (reminders, pending requests) are a plain `multipart/alternative`. The Resend sender sends the same `.ics` as an attachment with `content_type: text/calendar; method=...`. - `VCALENDAR` with `VERSION:2.0`, `PRODID:-//{app_name}//Scheduler//EN`, `CALSCALE:GREGORIAN`, and `METHOD:REQUEST` for confirmed and moved bookings, `METHOD:CANCEL` for cancellations. - One `VEVENT`: - `UID:{first booking uid in the chain}@{host name of the site}`. A reschedule keeps the UID of the booking it came from (follow `from_uid` to the first booking), so calendars update the existing event instead of adding a second one. - `SEQUENCE`: 0 for the first invite, plus one on every reschedule and on the cancel, stored in `bookings.ics_sequence`. - `DTSTAMP` (now), `DTSTART` and `DTEND` in UTC (`YYYYMMDDTHHMMSSZ`). - `SUMMARY:{title} with {booker name}` for the host, `{title} with {host name}` for guests. - Organizer depends on who the email is for: - Guest copies and the download: `ORGANIZER;CN={host name}:mailto:{host email}` and the host `ATTENDEE;CN={host name};ROLE=CHAIR;PARTSTAT=ACCEPTED;RSVP=FALSE:mailto:{host email}`. - The host's copy: `ORGANIZER;CN={app_name}:mailto:{EMAIL_FROM address}` and the host `ATTENDEE;CN={host name};ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=FALSE:mailto:{host email}`. Gmail will not load an invite whose `ORGANIZER` is the recipient: it looks for the event in the recipient's own calendar, finds nothing and shows "Unable to load event", and nothing is added. With the sending address as organizer, the host gets a normal invite that is added as accepted. Every host email for a booking (confirm, move, cancel) uses the same organizer, so updates and cancels match the event. - For the booker and each guest `ATTENDEE;CN=...;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=FALSE:mailto:...`. - `STATUS:CONFIRMED` for accepted bookings and `STATUS:CANCELLED` with `METHOD:CANCEL`. A pending request gets no invite; the invite goes out when the host accepts it. - `TRANSP:OPAQUE`, `LOCATION:` the link or address, `URL:` the booking page, and `DESCRIPTION:` the notes, the meeting link and the lines "Reschedule: {origin}/booking/{uid}" and "Cancel: {origin}/booking/{uid}". - Text escaped per RFC 5545 (backslash, semicolon, comma, newline), lines folded at 75 octets with CRLF + space, CRLF line ends. - Requirement: the event a guest or the host adds from the invite shows as confirmed and accepted in the calendar, not tentative and not "needs action" for the host. That is why the host attendee is `PARTSTAT=ACCEPTED` with `RSVP=FALSE` and the event is `STATUS:CONFIRMED`. - The "Add to calendar" download (`/api/public/bookings/:uid/ics`) uses the same function with `METHOD:PUBLISH`, the same UID and sequence. Accept when: unit tests parse the generated `.ics` (a small RFC 5545 parser in the tests: unfold lines, split properties and parameters) and check, for a booking, its reschedule and its cancel: the same UID across all three; `SEQUENCE` 0, 1, 2; `METHOD` REQUEST, REQUEST, CANCEL; `STATUS` CONFIRMED, CONFIRMED, CANCELLED; `DTSTART`/`DTEND` in UTC matching the stored times; `ORGANIZER` is the host for guests and the sending address for the host; the host `ATTENDEE` has `PARTSTAT=ACCEPTED`; the description holds the reschedule and cancel links; no unfolded line is over 75 octets; and every line ends with CRLF. A MIME test parses the message (headers, boundaries, base64 parts) and checks the `multipart/mixed` > `multipart/alternative` tree, the `text/calendar; method=REQUEST` part equal to the `.ics`, the `invite.ics` attachment, CRLF only, and encoded non-ASCII headers. End-to-end tests read the stored MIME from the test outbox and check the organizer per recipient. ### R17. Busy times from a secret iCal address (optional) - `/settings/calendars` has a field "Secret iCal address" with instructions: "In Google Calendar on the web, open Settings (the gear), choose your calendar under 'Settings for my calendars', open 'Integrate calendar', and copy 'Secret address in iCal format'. It ends in `basic.ics`. Anyone with this address can see your events, so it is stored encrypted and never shown again." Any `https://` iCal URL works (Outlook and iCloud publish them too). - The address is stored encrypted in D1 (AES-GCM with the secret `ENCRYPTION_KEY`, a fresh random IV per value). After saving, the page shows only the host and the last 6 characters (`calendar.google.com/...basic.ics` ending `…a1b2c3`), with "Replace" and "Remove". The API never returns it. - A Cron Trigger polls each feed every `ICAL_POLL_MINUTES` (5-15, default 10) with `If-None-Match` / `If-Modified-Since`. It parses `VEVENT`s: `DTSTART`/`DTEND` (or `DURATION`) with `TZID` (IANA names and Windows names mapped), all-day `VALUE=DATE` events (busy for the whole day in the host's zone), `RRULE` (DAILY, WEEKLY with BYDAY, MONTHLY with BYMONTHDAY or BYDAY+BYSETPOS, YEARLY; COUNT, UNTIL, INTERVAL), `EXDATE`, and overriding instances (`RECURRENCE-ID`). Events with `TRANSP:TRANSPARENT` or `STATUS:CANCELLED` are skipped. It expands instances from now to the booking horizon (max 60 days) and replaces the host's rows in `busy_blocks` (start_ms, end_ms, source) in one batch. - `computeSlots` treats each busy block like an accepted booking with no buffers, so a busy event removes the slots it overlaps. The booking guard (R9) checks busy blocks too. - The page shows "Last synced {time ago}" and the last error in plain words ("The address returned 404. It may have been reset in Google Calendar."). After 3 failed polls in a row the status is "Needs attention" and slots stop using stale blocks older than 24 hours. Accept when: unit tests expand a fixture `.ics` with a weekly `RRULE`, an `EXDATE`, a moved instance, an all-day event, a `TZID` event across a DST change and a transparent event, and get exactly the expected busy ranges; a slot test shows busy blocks removing slots; an e2e test serves a fixture feed from a local route, saves its address, runs the scheduled handler and sees the slots disappear and "Last synced" appear; and the saved address is not in any API response. ### R18. Google Calendar, two-way (optional) - Off unless `GOOGLE_CLIENT_ID` (var) and `GOOGLE_CLIENT_SECRET` (secret) are set. `/settings/calendars` then shows "Connect Google Calendar". - OAuth 2.0 authorization code flow with PKCE and a `state` bound to the session: scopes `https://www.googleapis.com/auth/calendar.freebusy` and `https://www.googleapis.com/auth/calendar.events.owned`, `access_type=offline`, `prompt=consent`, redirect URI `{origin}/oauth/google/callback`. The refresh token is stored encrypted in D1 (as in R17); access tokens are kept only in memory for their lifetime. - On book, reschedule and cancel the Worker creates, updates (same event id, stored on the booking) or deletes the event in the host's primary calendar with the guest as attendee, `sendUpdates=none` (R15 sends the email), and the event `status: confirmed`. Free/busy from `freeBusy.query` blocks slots like R17; results are cached in `busy_blocks` with source `google` and refreshed by the cron (every 10 minutes) as a fallback when a live query fails. - Errors (revoked access, expired consent) set "Needs attention" with "Reconnect"; a booking never fails because Google is unreachable, and a failed calendar write is retried by the cron. - A setup walkthrough on `/settings/calendars` (and in the README): create a Google Cloud project; enable the Google Calendar API; OAuth consent screen with user type External; add the two scopes; add yourself as a test user while testing; create an OAuth client of type "Web application" with the redirect URI above; then publish the app to "In production", because refresh tokens for apps left in "Testing" expire after 7 days. An unverified app shows Google's "unverified app" warning, which is fine for the owner's own account; verification is needed only for other users. Then `wrangler secret put GOOGLE_CLIENT_SECRET` and set `GOOGLE_CLIENT_ID`. Accept when: with Google's endpoints replaced by a local fake in tests, connecting stores an encrypted refresh token, booking creates an event, moving updates the same event id, cancelling deletes it, and a busy range from the fake free/busy removes slots; disconnecting deletes the token. ## Definition of done - `npm test` runs the unit tests (Vitest), including every slot test. - `npm run e2e` runs the Playwright tests against the real Worker under `wrangler dev` with a fresh local D1 (`--persist-to .e2e`, migrations applied first), and they cover every "Accept when" a browser can check. They pass. - `npx tsc` passes for the client and, with the types from `wrangler types`, for the Worker. - A README says how to install, run locally, seed, test and deploy. - Searching the built `dist/` for the names of other scheduling products finds nothing. - With none of R15-R18 configured, the app behaves exactly as in R1-R14 and the integration tests that need no network (`.ics` building and parsing, iCal expansion, reminder selection, encryption round trip) still pass.