# Spot: follow-up release plan

Step 4 of the spec asks for a plan, not an implementation. This document plans the next release: private revocable
iCalendar subscriptions, reusable recurring-show templates, and ranked replacements for a slot. It then lists the known
limitations found during the first build. Nothing below exists in the code yet unless it says so.

Existing building blocks referenced here: `App\Models\Booking` (`comedian_id`, `slot_id`, `show_id`, `status`,
`current_revision_id`, `window_start`, `window_end`, `closed_reason`, `snapshot`, `closed_at`),
`App\Models\OfferRevision` (`number`, `show_starts_at`, `arrival_at`, `set_starts_at`, `duration_minutes`, venue
columns, `timezone`), `Booking::scopeVisibleTo(User)`, `Booking::redactFor(User)`, `App\Services\Booking\BookingWorkflow`,
`App\Services\Shows\ShowService`, `App\Services\Booking\ConflictChecker`, and the events in `App\Events\*`.

## 1. Private, revocable iCalendar subscriptions

### Goal

Let a user subscribe their phone or desktop calendar to a URL that lists their confirmed gigs and updates itself.
The URL is the credential (calendar clients cannot log in), so it must be unguessable, revocable and scoped by the same
visibility rules as the web app.

### Token design

- One active token per user (a second device uses the same URL; revoke and rotate if it leaks).
- Generate 32 random bytes, show the URL once at creation in plain form, and store only a hash:
  `hash('sha256', $token)` in `calendar_tokens.token_hash` (unique). Same pattern as `Invitation::hashToken`.
  The user can always rotate to get a new URL; Spot cannot re-display an old one.
- URL: `GET {APP_URL}/calendar/feed/{token}.ics` (token is URL-safe base64, 43 characters).
- Lookup: hash the path token, find a non-revoked row for an active user, `hash_equals` is implicit in the unique
  indexed lookup; on miss return `404` with no detail. Update `last_used_at` at most once a minute.
- Revoke: set `revoked_at`. Rotate: revoke the current row and create a new one in one transaction. Deactivating a user
  (`deactivated_at`) makes the feed return `404` immediately; reactivation restores the same URL unless it was revoked.
- Throttle the feed route (for example `throttle:60,1` by IP) and send `Cache-Control: private, max-age=300` plus an
  `ETag` so clients that poll are cheap. Never log the token; log only its row id.

### What each role sees

The feed is built through the same visibility scope as the app, not a separate query:

- **Comedian**: their own bookings with status `Confirmed` or `NeedsReconfirmation` of non-cancelled shows (a
  reconfirmation booking is shown as `STATUS:TENTATIVE` with the revised time and "needs reconfirmation" in the
  summary). Pending offers are optionally included as `TENTATIVE`, behind a per-token option `include_pending`
  (default off, because offers can still be declined). Content uses `Booking::redactFor` rules: title, venue name and
  address, map link, arrival and set times, shared show logistics and the booking's `instructions`. Never the fee,
  manager notes or other comedians' names or contacts. The fee is omitted even for the comedian by default; add it
  later only as an explicit opt-in.
- **Manager**: all confirmed bookings across the agency, one event per booking, with the comedian name in the summary
  ("Show title: Comedian"), venue, and manager-visible details. Managers may alternatively choose a per-comedian
  or per-venue filtered token (`scope` JSON column) so a venue owner calendar does not leak the whole agency; this
  filter is out of scope for the first iteration and should only be added with tests.
- A comedian token can never return another comedian's event, even if the row's `user_id` is tampered with, because the
  query is `Booking::visibleTo($user)` evaluated for the token's current owner and role.

### Event model and stable UIDs

- One `VEVENT` per booking. `UID` is derived from the booking, never from the revision or the show date, so a
  reschedule, relocation or fee change updates the same event in the client instead of creating a duplicate:
  `UID:booking-{booking_id}@spot.samigo.com` (host part from `APP_URL`'s host, fixed once at first release and never
  changed afterwards).
- Reschedules and other material changes create a new `OfferRevision` on the **same** booking (see
  `BookingWorkflow::reviseForMaterialChange`), so the booking id is stable across them. `SEQUENCE` is the current
  revision's `number` minus 1 (revision 1 is `SEQUENCE:0`), so it increases with each approved revision. Logistics and
  typo corrections that do not create a revision do not change the time, but should still bump the event so clients
  refresh: use `LAST-MODIFIED` and `DTSTAMP` from `bookings.updated_at` / `shows.updated_at` / the revision, whichever
  is greatest. Where `SEQUENCE` must also grow for logistics-only edits, store a `calendar_sequence` counter on
  `bookings` and increment it on any change affecting the feed (revision, logistics, instructions, status).
- A reassignment ends the outgoing booking (`Cancelled`, `closed_reason=reassigned`) and creates a **new** booking for the
  incoming comedian with a different id. That is correct: the two comedians have different feeds, and the outgoing
  comedian's event becomes cancelled (below) while the incoming one appears.

### Cancelled and removed events

- When a booking leaves the confirmed set (withdrawn, cancelled, show cancelled, reassigned away, slot removed, declined
  after reconfirmation), keep emitting the same `UID` with `STATUS:CANCELLED` and an incremented `SEQUENCE` for a
  retention window (default 30 days after `closed_at`, configurable, for example `SPOT_CALENDAR_CANCELLED_DAYS=30`).
  Calendar clients then remove or strike the event. After the window the event simply disappears from the feed.
- Expired or declined offers that were never confirmed are not emitted, except pending offers that were included and
  then declined, which are cancelled the same way.
- A completed show stays in the feed as a normal past event.
- The outgoing comedian after reassignment must not see current show details: the cancelled event carries only the
  booking snapshot already stored in `bookings.snapshot` (title, date, venue name), consistent with the historical-snapshot
  rule in the spec.

### Time zones

- Emit instants in UTC (`DTSTART:20261204T193000Z`) taken from `window_start`/`set_starts_at` as stored, so every
  client renders them correctly regardless of its own zone and DST rules. Using UTC avoids needing `VTIMEZONE` blocks.
- For events whose local time matters to a human, also write the venue zone into the description ("20:30 Europe/Rome")
  and `X-WR-TIMEZONE` (calendar level) with the user's zone. If a client later needs floating local times, emit
  `DTSTART;TZID=Europe/Rome` with a generated `VTIMEZONE`; this is a deliberate non-goal for the first iteration.
- `DTSTART` is the attendance window start (`arrival_at` when present, else set start); `DTEND` is the window end; the set
  time and duration go in `DESCRIPTION`. Shows that cross midnight need no special handling with UTC instants.
- Line folding at 75 octets, CRLF line endings, `PRODID:-//Spot//Booking//IT`, `METHOD` omitted (subscription feeds are
  not scheduling messages), `X-WR-CALNAME:Spot` and `REFRESH-INTERVAL`/`X-PUBLISHED-TTL:PT1H`.

### Proposed schema

```
calendar_tokens
  id
  user_id            fk users, cascade delete, index
  token_hash         string(64), unique
  label              string, nullable      (e.g. "iPhone")
  include_pending    boolean, default false
  last_used_at       dateTime, nullable
  revoked_at         dateTime, nullable
  created_at / updated_at

bookings (addition)
  calendar_sequence  unsignedInteger, default 0
```

Portable to PostgreSQL: plain columns only, no partial unique index (enforce "one active token per user" in the service,
inside a transaction, as `bookings.active_slot_id` does for slots).

### Proposed routes

| Method and URL | Who | Purpose |
|---|---|---|
| `GET /settings/calendar` | any signed-in user | Show whether a feed exists, last used, the create/rotate/revoke controls |
| `POST /settings/calendar/token` | any signed-in user | Create or rotate; flashes the full URL once |
| `DELETE /settings/calendar/token` | any signed-in user | Revoke |
| `GET /calendar/feed/{token}.ics` | public, token-authenticated, no session | The feed (`text/calendar; charset=utf-8`) |

The feed route is excluded from session, cookie and CSRF middleware the same way `webhooks/wuzapi` is in
`routes/comms.php`.

### Implementation sketch

- `App\Services\Calendar\IcsFeedBuilder::forUser(User, CalendarToken): string` using the visibility scope above; keep a
  small hand-written RFC 5545 writer (escaping, folding) rather than a dependency, unless a maintained package is
  preferred.
- `App\Models\CalendarToken` with `hashToken()` and `issue(User): array{0: CalendarToken, 1: string}`.
- A listener on the existing events that touch bookings (`OfferAccepted`, `OfferRevised`, `BookingCancelled`,
  `ShowCancelled`, `ShowLogisticsUpdated`, `BookingReassigned`) increments `calendar_sequence`, so no feed code runs at
  write time and the feed is rendered on request.
- Activity log entries `calendar.token_created`, `calendar.token_rotated`, `calendar.token_revoked`.

### Tests to write

- Token: only a hash is stored; the plain token is shown once; a wrong, revoked, rotated or unknown token returns 404;
  a deactivated user's feed returns 404; rotation invalidates the old URL.
- Isolation: a comedian's feed never contains another comedian's booking, fee, manager notes or contacts; manager
  feed contains all confirmed bookings; reassigned-away comedian sees only the snapshot as a cancelled event.
- Content: Pending is excluded by default and included as `TENTATIVE` with `include_pending`; `NeedsReconfirmation`
  is `TENTATIVE` with the new time; confirmed is `CONFIRMED`.
- Stability: after `ShowService::reschedule` and `relocate` the `UID` is unchanged, `SEQUENCE` increases and `DTSTART`
  moves; a logistics-only change bumps `SEQUENCE` / `LAST-MODIFIED` without a new revision.
- Cancellation: cancelled, withdrawn, show-cancelled and slot-removed bookings emit `STATUS:CANCELLED` inside the
  retention window and disappear after it.
- Format: CRLF endings, 75-octet folding, escaped commas, semicolons and newlines in titles and addresses, UTC `DTSTART`,
  an event crossing midnight, `Europe/Rome` DST changeover dates.
- Throttling and caching headers (`ETag`, `304` on `If-None-Match`).

## 2. Reusable recurring-show templates

### Goal

Managers repeat the same format (a weekly night at one venue with the same lineup roles). Today they use
`ShowService::duplicateAsDraft`, one show at a time. A template stores the shape and generates draft shows on a
schedule that the manager reviews before any offer is sent.

### Model

- A template holds show defaults (title, venue, time zone, logistics, local start time, arrival offset, default
  duration) and an ordered list of slot definitions (role, custom label, position, set offset from show start, duration,
  default fee and currency). It never holds comedians: offers are still manager decisions.
- A recurrence rule (weekly, every N weeks, a weekday, monthly on the nth weekday) plus a horizon (for example the next
  8 occurrences) is evaluated in the template's IANA zone so "Thursday 21:00" stays 21:00 across DST, then converted
  to UTC for `shows.starts_at`.
- Generation always creates `Draft` shows through `ShowService::create`, setting `shows.template_id` and
  `shows.occurrence_date`. A unique pair `(template_id, occurrence_date)` makes generation idempotent. Editing the
  template affects only future, untouched drafts; edited or published shows are left alone.

### Proposed schema

```
show_templates
  id, name, venue_id (nullable fk), timezone, title, logistics (text, nullable),
  starts_local_time (string HH:MM), arrival_offset_minutes (nullable), default_show_minutes (nullable),
  recurrence (json: {freq, interval, weekday, nth}), horizon_occurrences (unsignedSmallInteger),
  active (boolean), last_generated_through (date, nullable), created_by (fk users), timestamps

show_template_slots
  id, show_template_id (fk, cascade), role (string), custom_role_label (nullable), position,
  set_offset_minutes, duration_minutes, fee_amount (nullable), fee_currency (nullable)

shows (additions)
  template_id (nullable fk), occurrence_date (date, nullable), unique (template_id, occurrence_date)
```

(`unique` with nullable columns is portable: MySQL and PostgreSQL both allow several NULLs.)

### Routes and services

| Method and URL | Purpose |
|---|---|
| `GET /manager/templates`, `/create`, `/{template}/edit` | Manage templates |
| `POST /manager/templates`, `PUT /manager/templates/{template}` | Save |
| `POST /manager/templates/{template}/generate` | Preview then create the next drafts |
| `POST /manager/templates/{template}/archive` | Stop generating |
| `POST /manager/shows/{show}/save-as-template` | Create a template from an existing show |

- `App\Services\Shows\TemplateService`: `fromShow`, `occurrences(template, from, to)`, `generate(template, count)`.
- Optionally schedule `spot:generate-template-shows` daily to keep the horizon filled; it only creates drafts and
  notifies managers in-app (`Notifier`), never sends offers.
- Policy `ShowTemplatePolicy`: managers only.

### Tests

- Occurrence expansion for weekly, biweekly and monthly-nth rules across both DST changes in `Europe/Rome`.
- Generation is idempotent (running twice creates no duplicates) and creates drafts with the correct slots, roles,
  offsets, durations, fees and UTC times.
- Editing a template does not rewrite already generated or edited shows; archiving stops generation.
- A venue archived after template creation is reported, not silently used.
- Authorization: comedians receive 403 on every route; `save-as-template` copies no bookings or manager notes.
- Slot offsets that cross midnight produce correct `starts_at`.

## 3. Ranked replacements for a slot

### Goal

When a booking is declined, expired, withdrawn or cancelled, or when a manager reassigns, show the best replacement
candidates first, with the reasons visible.

### What exists

`ConflictChecker::candidatesForSlot(Slot)` already returns every active comedian with a `ConflictReport`
(`state`: `Available`, `Unknown`, `Tentative`, `Conflict`; `conflicts` and `holds` with types such as unavailable,
external engagement, confirmed booking, pending booking, pending proposal), exposed as JSON at
`GET /manager/shows/{show}/slots/{slot}/candidates` (`OfferController::candidates`). It sorts by: the currently
assigned comedian first, then availability state (`Available` < `Unknown` < `Tentative` < `Conflict`), then name. The
manager UI already labels each state.

### Ranking inputs available today (no new data needed)

1. Availability state of the attendance window (`ConflictReport::state`), the primary key.
2. Number and type of holds: pending offers and proposals under review make a comedian `Tentative`; more holds is worse.
3. Conflict detail: which hard conflict (unavailable entry versus external engagement versus confirmed booking), so a
   soft "unavailable" marker can rank above a hard confirmed booking.
4. Whether the window is unknown (slot without a time) and the comedian's reported availability coverage.
5. Venue overlap warning on the show (`venueOverlaps`), which is a show-level flag, not a per-comedian input.
6. The booking history the app already stores: `bookings` (status, `closed_reason`, `comedian_id`, `slot_id`),
   `slots.role`, `show_id`, `offer_revisions.decided_at` and `decision_reason`.

### Proposed scoring (new service)

Add `App\Services\Booking\ReplacementRanker`, which consumes `candidatesForSlot` and returns candidates with a score and
human-readable reasons. Keep the conflict-state ordering authoritative (never rank a hard conflict above an available
comedian); use secondary signals only to order inside a state:

- Role fit: count of past `Confirmed`/completed bookings in the same `slots.role` (more is better).
- Reliability: ratio of past offers accepted versus declined or expired (`offer_revisions.status`).
- Workload fairness: confirmed bookings in the surrounding 14 days (fewer is better) so work is spread.
- Venue familiarity: past bookings at the same `venue_id`.
- Responsiveness: median time between sending an offer and `decided_at`.
- Exclusions with an explanation, not removal: the comedian who just declined or whose booking was just cancelled for
  this slot stays visible but last, labelled "already declined".

Weights live in `config/spot.php` (`spot.ranking.*`) so the agency can tune them, and every candidate returns its
reasons so the UI can show why one is higher. Queries must be batched for all comedians at once (as `checkMany` does)
to avoid N+1.

### Routes and UI

- Extend the existing candidates JSON with `score` and `reasons[]`; no new route is required. Optionally add
  `GET /manager/shows/{show}/slots/{slot}/replacements` for the post-decline view and a "Find a replacement" action on
  the notification a manager receives when a booking closes.
- A manager can send an offer to several ranked candidates sequentially: a "next" prompt after expiry or decline. An
  automatic cascade (auto-offer to the next candidate) is a separate product decision and should be opt-in per show.

### Tests

- Ordering inside a state follows the secondary signals; state ordering is never violated.
- Past declines, expiries and role history change the score as documented; reasons are returned.
- The comedian who just declined is listed last with the explanation.
- A candidate with a hold or hard conflict is explained and still labelled correctly.
- Performance: a constant number of queries for N comedians.
- Authorization: only managers can call the endpoint; comedians receive 403; no private notes in the payload.

## 4. Suggested order and release notes

1. Calendar feeds first: self-contained, no change to booking rules, high daily value for comedians.
2. Ranked replacements second: builds only on existing data and services.
3. Templates last: they touch show creation and need a scheduler job and more UI.

New migrations must stay portable to PostgreSQL like the existing ones (strings instead of enums, no partial indexes, no
vendor SQL). New tunables go in `config/spot.php`, read only through `config()`, and `.env.example` and the README table
must be updated with them.

## Known limitations

Found during the first build; none blocks the spec's workflows.

- **Slot reordering is buttons only.** The manager show detail reorders slots with move up and move down controls
  (`POST /manager/shows/{show}/slots/reorder`); there is no drag-and-drop.
- **WuzAPI ambiguous timeouts are marked Failed with manual retry.** The pinned WuzAPI release (v1.1.1) documents no
  idempotency for message ids, so after a timeout Spot cannot know whether the text was sent and does not resend
  automatically. The delivery is marked `Failed` (`unconfirmed: timeout`) and a manager can retry deliberately from
  `/manager/deliveries`; the recipient may receive a duplicate.
- **Agency-session pinning is opt-in.** Webhooks are only restricted to the agency session when
  `WUZAPI_SESSION_USER_ID` and/or `WUZAPI_INSTANCE_NAME` are set. Without them any correctly signed webhook is
  accepted, which is still protected by the HMAC secret.
- **Only JSON-mode webhooks are parsed.** WuzAPI must run with `WEBHOOK_FORMAT=json`; form-encoded webhooks are not
  supported.
- **An unverified WhatsApp number held by one user blocks another from claiming it.** `users.whatsapp_number` is unique
  and the contact form rejects a number already stored on another account, even if that user never verified it. Resolving
  it requires a manager to clear the number, or a future rule that lets a verified claim take over an unverified one.
- **Message read state has one-second precision.** `conversation_reads.last_read_at` is compared with
  `messages.created_at` on the timestamp columns, so a message created in the same second as the read marker can be
  treated as read.
- **Chat messages are not relayed over WhatsApp.** WhatsApp carries offers, reminders, verification codes and command
  replies only; direct and booking-thread messages stay in the app (and email to comedians).
- **No iCalendar export yet.** The spec mentions calendar exports for access control; the feed is planned above.
