# Spot — architecture plan and work split

Source spec: [`prompt.md`](../prompt.md) (read it in full before working on any part). This file is the
shared contract between the people/agents building the app in parallel. If you must deviate, keep the
contract's names and add a short note under "Deviations" at the bottom.

## Decisions

- Laravel 13 + official Vue starter kit (Inertia 3, Vue 3 `<script setup lang="ts">`, Tailwind 4, shadcn-vue, Fortify, Wayfinder, Pest).
- **Database**: local dev uses MySQL `samigo_spot` on `db.ls` (spec "access" section). Migrations and queries must stay
  portable to PostgreSQL (spec "stack" section): no vendor SQL, no partial indexes, no `ENUM` columns (use strings),
  JSON columns via `$table->json()`. Tests run on SQLite `:memory:` (phpunit.xml) — code must work there too.
- One agency, no tenancy. Roles: `manager`, `comedian` (column `users.role`).
- All timestamps UTC in DB. Venues, shows and users carry an IANA `timezone` (default `Europe/Rome`).
  Backend sends ISO-8601 UTC strings plus the relevant timezone; the frontend formats with `Intl`.
- Italian default UI (`APP_LOCALE=it`), English files present. No hard-coded user-facing strings in Vue or PHP.
- Business rules live in PHP services; controllers are thin (Form Request → service → redirect/Inertia).
- Do not `git commit`. Do not edit files owned by another work package except where stated.

## Domain model

Enums in `App\Enums` (string-backed, each with `label()` using `__()`):
`UserRole{Manager,Comedian}`, `ShowStatus{Draft,Open,Cancelled,Completed}`,
`SlotRole{Host,Opener,Feature,Headliner,Custom}`,
`BookingStatus{Pending,Confirmed,NeedsReconfirmation,Declined,Expired,Withdrawn,Cancelled}` (`isActive()` = first three),
`RevisionStatus{Pending,Accepted,Declined,Expired,Superseded,Withdrawn}`,
`AvailabilityKind{Available,Unavailable}`, `EngagementType{Block,Proposal}`,
`EngagementStatus{Active,Submitted,Revised,Approved,Declined,Withdrawn}`,
`Channel{Web,Whatsapp,System}`, `DeliveryStatus{Queued,Accepted,Failed}`,
`AvailabilityState{Available,Unknown,Tentative,Conflict}` (result of a conflict check).

Tables / models (`App\Models`):

| Model | Key columns |
|---|---|
| `User` | + `role`, `stage_name?`, `timezone`, `locale`, `phone?`, `whatsapp_number?` (E.164 digits), `whatsapp_verified_at?`, `whatsapp_verification_code?` (hashed), `whatsapp_verification_expires_at?`, `notification_preferences` (json: `email`, `whatsapp`, `deadline_reminder_hours[]`, `show_reminder_hours[]`), `deactivated_at?` |
| `Invitation` | `email`, `name`, `role`, `token_hash` (unique, sha256), `invited_by`, `expires_at`, `accepted_at?`, `revoked_at?`, `accepted_user_id?` |
| `Venue` | `name`, `address`, `city`, `timezone`, `map_url?`, `contact_name?`, `contact_phone?`, `notes?`, `archived_at?` |
| `Show` | `title`, `venue_id?`, `status`, `starts_at?`, `ends_at?`, `timezone`, `logistics?` (shared with assigned comedians), `manager_notes?` (private), `duplicated_from_id?`, `cancelled_at?`, `cancel_reason?`, `completed_at?`, `created_by` |
| `Slot` | `show_id`, `role`, `custom_role_label?`, `position`, `starts_at?` (set time), `duration_minutes`, `arrival_at?` (required arrival), `fee_amount?`, `fee_currency?` (defaults for the next offer) |
| `Booking` | `slot_id`, `show_id`, `comedian_id`, `status`, `active_slot_id?` (**unique**; = `slot_id` while status is active, else NULL → at most one active booking per slot), `current_revision_id?`, `window_start`, `window_end` (attendance window, UTC, from current revision), `instructions?` (visible to comedian), `manager_notes?` (private), `closed_reason?` (`reassigned`, `show_cancelled`, `slot_removed`, …), `previous_booking_id?`, `replaced_by_booking_id?`, `snapshot?` (json frozen terms + show info at close), `closed_at?` |
| `OfferRevision` | `booking_id`, `number`, material terms as columns: `show_starts_at`, `arrival_at?`, `set_starts_at`, `duration_minutes`, `venue_id`, `venue_name`, `venue_address`, `venue_city`, `timezone`, `role`, `role_label?`, `fee_amount?`, `fee_currency?`; `changed_fields?` (json list vs previous revision), `reply_deadline_at`, `status`, `created_by?`, `decided_at?`, `decided_channel?`, `decision_reason?` |
| `ReplyCode` | `offer_revision_id`, `user_id`, `code_hash` (unique), `expires_at`, `consumed_at?` |
| `Availability` | `user_id`, `kind`, `starts_at`, `ends_at`, `all_day`, `timezone`, `note?` |
| `ExternalEngagement` | `user_id`, `type`, `status`, `title`, `venue_name?`, `venue_address?`, `city?`, `timezone`, `starts_at`, `ends_at`, `notes?`, `proposed_terms?` (json, manager's revised terms), `decline_reason?`, `reviewed_by?`, `reviewed_at?`, `resulting_booking_id?` |
| `ActivityLog` | `actor_id?`, `channel`, `action` (dot string e.g. `booking.accepted`), `show_id?`, `booking_id?`, `subject_type/id`, `reason?`, `before?` (json), `after?` (json), `created_at` |
| `Conversation` | `type` (`direct`\|`booking`), `comedian_id`, `booking_id?` (unique). Direct = agency ↔ one comedian (one per comedian, any manager can read/reply). |
| `Message` | `conversation_id`, `sender_id`, `body`, `created_at` |
| `ConversationRead` | `conversation_id`, `user_id`, `last_read_at` (unique pair) |
| `WhatsappDelivery` | `user_id`, `booking_id?`, `offer_revision_id?`, `kind`, `to`, `body` (reply codes masked), `client_message_id` (unique), `status`, `attempts`, `provider_message_id?`, `last_error?`, `accepted_at?`, `failed_at?` |
| `WhatsappInboundEvent` | `provider_event_id` (unique), `sender`, `outcome`, `processed_at` |
| `ReminderLog` | `key` (unique, e.g. `deadline:rev:12:24h:user:5`), `sent_at` |
| Laravel `notifications` table | in-app notification centre |

Attendance window = `[arrival_at ?? set_starts_at, set_starts_at + duration]`.

## Services (owned by WP-A1)

- `App\Support\Actor` — value object (`Actor::user($user, Channel::Web)`, `Actor::system()`).
- `App\Services\Booking\ConflictChecker` — `check(User, start, end, ?ignoreBookingId): ConflictReport` (state +
  explained hard conflicts + tentative holds), `candidatesForSlot(Slot): Collection` (every active comedian with
  their report), `venueOverlaps(Show): Collection`.
  Hard conflict: unavailable entry, external engagement (active block / approved), overlapping Confirmed booking.
  Tentative: overlapping Pending / NeedsReconfirmation booking. Available: fully covered by "available" entries.
  Otherwise Unknown.
- `App\Services\Booking\BookingWorkflow` — the single entry point for web and WhatsApp:
  `sendOffer`, `withdraw`, `accept(OfferRevision, User, Actor, ?reason)`, `decline(...)`, `expire(Booking)`,
  `reviseForMaterialChange`, `reassign(Slot, User incoming, Actor, ?reason)`, `cancel`.
  Every method runs in a DB transaction with `lockForUpdate()` on the booking (and the comedian row when checking
  overlaps), re-checks revision currency + deadline at processing time (expiring on the spot if past), re-runs
  conflict checks on send and accept, writes `ActivityLog`, and dispatches after-commit domain events.
  Failures throw typed exceptions in `App\Exceptions\Booking\*` (`OfferExpired`, `OfferSuperseded`,
  `BookingConflict`, `NotRecipient`, `InvalidTransition`) that controllers/WhatsApp map to messages.
- `App\Services\Shows\ShowService` — create/update/duplicateAsDraft/reschedule/relocate/cancel/complete/reorderSlots,
  slot CRUD, `previewImpact(Show, array $changes): ImpactReport` (which bookings will need reconfirmation), and
  apply (material changes → `BookingWorkflow::reviseForMaterialChange` for every affected booking; logistics,
  instructions, notes, title typos → no new revision).
- `App\Services\Proposals\ProposalService` — comedian submit/withdraw, manager approve / decline / proposeRevision,
  comedian acceptRevision / declineRevision. Approval creates Venue (or reuses), Show, Slot and a Confirmed booking.
- `App\Services\Availability\AvailabilityService` — add/edit/remove entries (single day, multi-day, time range);
  refuses to mark confirmed time unavailable, returning the blocking booking(s).
- `App\Services\ActivityLogger`.
- Domain events (`App\Events\...`, all `ShouldDispatchAfterCommit`): `OfferSent`, `OfferRevised`, `OfferAccepted`,
  `OfferDeclined`, `OfferExpired`, `OfferWithdrawn`, `BookingReassigned` (outgoing + incoming), `BookingCancelled`,
  `ShowCancelled`, `ShowLogisticsUpdated`, `ProposalSubmitted`, `ProposalReviewed`, `ProposalRevisionAnswered`,
  `MessageSent`. WP-B4 listens to these; nobody else sends notifications.
- Console: `spot:expire-offers` (scheduled every minute), config `config/spot.php`
  (`offer_reply_hours` = 48, `invitation_expiry_hours`, default reminder hours, etc., all env-driven).

## HTTP surface

Route files (all required from `routes/web.php`): `routes/accounts.php`, `routes/shows.php`, `routes/comedian.php`,
`routes/comms.php`. Middleware aliases: `role:manager|comedian`, `active` (deactivated users are logged out).
All app routes use `['auth', 'verified', 'active']`.

| URL | Who | Owner | Inertia page |
|---|---|---|---|
| `/dashboard` → redirect by role | all | A2 | — |
| `/manager` | manager | B2 | `manager/Home` |
| `/manager/shows`, `/manager/shows/create`, `/manager/shows/{show}` (+ edit, duplicate, cancel, complete, slots, offers, reassign, impact preview) | manager | B2 | `manager/shows/*` |
| `/manager/calendar` | manager | B2 | `manager/Calendar` |
| `/manager/activity` | manager | B2 | `manager/Activity` |
| `/manager/proposals`, `/manager/proposals/{engagement}` | manager | B3 | `manager/proposals/*` |
| `/manager/roster`, `/manager/roster/{user}`, `/manager/invitations` | manager | B1 | `manager/roster/*` |
| `/manager/venues` (CRUD) | manager | B1 | `manager/venues/*` |
| `/manager/deliveries` | manager | B4 | `manager/Deliveries` |
| `/invitations/{token}` (GET show, POST accept) | guest | B1 | `auth/AcceptInvitation` |
| `/home` | comedian | B3 | `comedian/Home` |
| `/offers/{revision}` (view only; accept/decline are explicit POSTs) | recipient | B3 | `comedian/OfferDetail` |
| `/bookings`, `/bookings/{booking}`, `/bookings/{booking}/show-day` | comedian (own) | B3 | `comedian/bookings/*` |
| `/calendar`, `/availability` (CRUD), `/engagements` (CRUD + proposals) | comedian | B3 | `comedian/Calendar`, … |
| `/inbox`, `/inbox/{conversation}`, `/bookings/{booking}/thread` | both | B4 | `inbox/*` |
| `/notifications` (+ read / read-all) | both | B4 | `notifications/Index` |
| `/settings/contact`, `/settings/notifications` | both | B4 | `settings/*` |
| `POST /webhooks/wuzapi` | WuzAPI | B4 | — |

Shared Inertia props (A2): `auth.user` (id, name, email, role, timezone, locale), `locale`, `translations`,
`counts: { notifications, messages }` from `App\Support\NavCounts::for(User)` (A2 stubs zeros, B4 implements),
`flash`.

Frontend conventions (A2 provides): `useI18n()` → `t('group.key', { param })`; `useDateTime()` → format ISO UTC in
a timezone; `components/spot/*` (StatusBadge with icon+text — never colour alone, EmptyState, ConfirmDialog,
PageHeader, TermsDiff, calendar/AgendaList|WeekGrid|MonthGrid taking
`{ id, title, start, end, timezone, status, kind, href }[]`). Translations: `lang/{it,en}/<group>.php`, one group per
work package (`common`, `accounts`, `shows`, `comedian`, `comms`, `enums`) so parallel work does not collide.
Mobile first: every screen usable at 360 px without horizontal scroll, bottom tab bar on mobile, visible focus rings.

## Work packages

Phase 1 (parallel)
- **A1 — domain core** (opus): migrations, models, factories, enums, policies for all domain models, middleware
  aliases, services above, domain events, `spot:expire-offers`, `config/spot.php`, tests in `tests/Feature/Booking`
  + `tests/Unit`.
- **A2 — frontend shell** (sonnet): i18n plumbing, shared props, role-aware layout + nav, branding from `logo.svg`,
  shared components, route-file stubs, `/dashboard` redirect, Italian auth/settings pages, `lang/*/common.php`,
  `lang/*/enums.php`.

Phase 2 (parallel, after phase 1)
- **B1 — accounts, roster, venues** (sonnet): `spot:create-manager`, invitations, registration disabled, deactivation,
  roster, venue directory. Tests `tests/Feature/Accounts`.
- **B2 — manager shows** (opus): manager home, shows/slots/offers/reassign UI + controllers, impact preview, calendar,
  activity history. Tests `tests/Feature/Shows`.
- **B3 — comedian side + proposals** (sonnet): comedian home, offer detail, bookings, show-day, calendar, availability,
  external engagements, proposal review (manager side). Tests `tests/Feature/Comedian`.
- **B4 — comms** (opus): notifications centre, messages, reminders, contact settings + verification, WuzAPI + fake
  transport, webhook, direct replies, delivery log. Tests `tests/Feature/Comms`.

Phase 3
- **C1** (sonnet): development seeder scenario. **C2** (haiku): English translation pass, `.env.example`.
  **C3** (sonnet): README (setup, migrations, mail, WuzAPI, queue, scheduler), follow-up release plan.
- Orchestrator: full test run, `npm run build`, browser verification at 360 px and desktop, review, handover.

## Deviations

WP-A1 (domain core) — names in this file are kept; these are additions/clarifications:

- **Extra enums**: `ConflictType{Unavailable,ExternalEngagement,ConfirmedBooking,PendingBooking,NeedsReconfirmationBooking,PendingProposal}`,
  `ClosedReason{Declined,Expired,Withdrawn,Cancelled,Reassigned,ShowCancelled,ShowCompleted,SlotRemoved}` (cast of
  `bookings.closed_reason`), `ConversationType{Direct,Booking}`. All enum labels use `__('enums.<snake_enum>.<value>')`,
  e.g. `enums.booking_status.needs_reconfirmation`, `enums.conflict_type.confirmed_booking`.
- **Schema**: `slots.deleted_at` (SoftDeletes, so removed slots keep booking history); `conversations.last_message_at`;
  `users.whatsapp_number` unique; `activity_logs`/`messages` have no `updated_at`. Domain instants (show/slot/booking
  windows/revision times/availability/engagements/reply-code expiry) are `dateTime` columns holding UTC (avoids MySQL
  `TIMESTAMP` 2038 limit and session-time-zone conversion); audit timestamps stay `timestamp`.
- **Reply codes** live in `App\Services\Booking\ReplyCodes` (`issue`, `find`, `consume`, `invalidate`, `mask`), HMAC-SHA256
  keyed with `APP_KEY`, alphabet `23456789ABCDEFGHJKMNPQRSTUVWXYZ`. `BookingWorkflow::accept/decline` take an optional
  `$replyCode` consumed in the decision transaction; `acceptWithCode/declineWithCode(User, code, Actor)` resolve it first.
- **Extra exceptions**: `InvalidReplyCode`, `ConfirmedTimeUnavailable` (carries `bookings`); all extend
  `BookingException` with `errorKey` + `context`.
- **Value objects**: `OfferTerms`, `ConflictReport`, `ConflictItem`, `SlotCandidate` (`App\Services\Booking`),
  `ImpactReport`, `BookingImpact` (`App\Services\Shows`).
- **`changed_fields`** uses the logical keys `date, venue, arrival, set_time, duration, role, fee`
  (`OfferTerms::FIELD_COLUMNS` maps them to revision columns). "date" = local calendar date of the show start.
  A show-start change on the same local date, or venue name/address text changes with the same `venue_id`, are
  corrected in place on the current revision (audit `booking.terms_corrected`), no new revision.
- On a material change the previous current revision becomes `Superseded` even if it had been `Accepted`
  (`decided_at`/`decided_channel` keep the history). Pending bookings stay Pending with a fresh deadline.
- A `NeedsReconfirmation` booking whose new revision passes its deadline becomes `Expired` and frees the slot.
- Reply deadline cap: `config('spot.offer_deadline_buffer_minutes')` (default 60) before arrival (or set) time;
  `sendOffer` throws `InvalidTransition('deadline_in_past')` if the capped deadline is not in the future.
- `sendOffer` refuses hard conflicts (`BookingConflict`) and auto-opens a Draft show (audit `show.published`).
- Reassignment: outgoing booking → `Cancelled` with `closed_reason=reassigned`. Events: `BookingReassigned` (for the
  outgoing notice, no reply code) **and** a regular `OfferSent` for the incoming comedian.
- `ShowService::cancel` dispatches one `ShowCancelled` (not per-booking `BookingCancelled`); `complete` withdraws offers
  still awaiting a reply (`OfferWithdrawn`, `closed_reason=show_completed`). `removeSlot` cancels the slot's booking
  (`BookingCancelled`, `closed_reason=slot_removed`).
- Slot fee changes made through `ShowService::updateSlot/update(['slots'=>…])` propagate to the slot's active booking
  (material `fee`); reschedule/relocate never touch fees.
- Conflict checks also report proposals under review as tentative holds (`PendingProposal`); approved proposals that
  produced a booking are not double-counted.
- Calendar blocks (`ProposalService::createBlock/updateEngagement`) over a Confirmed booking are refused like
  unavailable marks (`ConfirmedTimeUnavailable`). `ProposalService` therefore also owns block CRUD.
- New availability entries carve out (trim/split) overlapping entries of the opposite kind.
- Every workflow event also carries `actorId` and `channel`.
- `EnsureUserIsActive` uses translation key `auth.deactivated` (A2: please add to `lang/{it,en}/auth.php`).
