# ARCHITECTURE.md — HATEM AUTO RENTAL (PROPOSAL, v0.2)

**Status: stack APPROVED by the owner (Next.js + TypeScript + Supabase + Vercel + GitHub + Playwright), 2026-11-30. The final architecture and the database design are still under review. No implementation yet.**
Date: 2026-11-30 · Author: Claude · Reviewer: owner

> ### v0.2 owner corrections: these override anything below
> - Business: an individual business in **Tripoli, Lebanon**. Fleet of 10–30 vehicles. Mostly mobile users. AR + EN. Channels: **website + WhatsApp**.
> - Workflow: **Rental Request** (submit, then optionally continue on WhatsApp with a prepared message, then staff review). **No instant confirmed bookings and no online payments.**
> - Availability and prices are **unverified**: nothing is invented or presented as real.
> - **Superseded below:** §3.1 "create_booking" becomes `submit_rental_request`. §4 double-booking now applies to staff-created *unavailability blocks*, not to requests. §6 server-computed pricing becomes staff-entered quotes plus optional owner-verified rates. Assumptions A1–A11 are replaced by the owner's facts and the **pending business decisions** list.
> - The authoritative data and workflow design is **`DATABASE_AND_WORKFLOW_PROPOSAL.md`** + **`supabase/migrations_draft/`**.

---

## 0. Evidence: confirmed vs assumed vs not inspected

### Confirmed (inspected directly)
| # | Finding | Evidence |
|---|---|---|
| C1 | An artifact titled "HATEM AUTO RENTAL — Prototype" exists in your account: slug `456a74b9-…`, version `1795942458-d3cc`, last updated 2026-11-29 08:54 UTC, one file `index.html` of 47,847 bytes | Artifact API metadata |
| C2 | It is a single-file HTML + vanilla JS app with no backend. State is in memory only. | Source read in full (187 lines) |
| C3 | Screens: public home, fleet with filters, vehicle detail with gallery placeholders, 4-step booking, simulated sign-in/sign-up/reset, customer bookings, admin (overview, bookings, vehicles, calendar month/week/day, customers, settings). EN + AR with RTL. Desktop + mobile layouts. | 15 screenshots rendered from the source in headless Chromium |
| C4 | Byte-exact backup taken: `backup/prototype-2026-11-30_v1795942458-d3cc/index.html`, SHA-256 `39b36112…2d1c`; size matches the server-reported size | `SHA256SUMS`, tarball |
| C5 | Issues L-001 to L-014 in ENGINEERING_LESSONS.md. L-006 (2-hour time shift in Beirut), L-013 (KPI mislabel) and L-014 (reference numbering) were reproduced at runtime. | Playwright runtime checks + screenshots |
| C6 | Local Playwright 1.63 + Chromium works in this workspace | It produced the screenshots |

### Not inspected / cannot inspect
| # | Item | Why |
|---|---|---|
| N1 | The link in your prompt (`…/artifact/XZoGJnvaR81tT3TAnvhZhT`) | Returns "not found" to my tools. It may be another account's, deleted, or a share link I can't resolve. **Whether C1 is that same project is unconfirmed until you say so.** |
| N2 | The artifact as rendered *on claude.ai* | I rendered the identical source locally. Google Fonts (Fraunces/Manrope/Tajawal) were blocked here, so headings show a fallback serif. |
| N3 | Older artifact versions, other chats, or files on your computer | Not reachable from this session (no device link) |
| N4 | Real business data: fleet, prices, branches, policies | None exists in the prototype. Everything is labelled demo. |
| N5 | Supabase, Vercel, GitHub, and Context7 accounts | Not connected (see §8) |

### Assumptions (need your confirmation; marked **[A#]** below)
- **A1** Market: Lebanon. Branches: Beirut, Tripoli, Beirut Airport (from the prototype). Business timezone **Asia/Beirut**.
- **A2** Currency **USD** (the prototype shows `$`). No online payment in v1: pay at pickup.
- **A3** Customers must have an account to book (no guest checkout), with email verification.
- **A4** Booking approval is **manual** by default (the prototype default). Optional auto-confirm is a setting.
- **A5** Rental day = a 24-hour block from pickup time, with a grace period (e.g. 59 min) before an extra day is charged. **Owner must define this.**
- **A6** Notifications in v1: transactional email, plus WhatsApp **click-to-chat** links only. No WhatsApp Business API sending in v1.
- **A7** Admin users: 1–5 staff, with two roles, `admin` and `staff`.
- **A8** Driver licence / ID upload is **not** in v1, unless you want it. It adds sensitive-data storage obligations.

---

## 1. Goals and non-goals

**Goals (v1):** real fleet browsing, real availability, bookings that cannot double-book, secure customer accounts, a secure admin dashboard with real data, EN/AR with correct RTL, mobile-first, auditable admin actions.

**Non-goals (v1):** online payments, a dynamic pricing engine, multi-tenant / franchise support, native mobile apps, loyalty programme. Each can be added later without re-architecting.

---

## 2. Proposed architecture

```
┌──────────────────────── Browser (customer / staff) ────────────────────────┐
│  Next.js app (React + TypeScript), EN/AR, RTL, mobile-first                 │
│  • Public: /[locale]/, /[locale]/fleet, /[locale]/vehicles/[slug]           │
│  • Customer: /[locale]/account, /[locale]/book/...                          │
│  • Admin: /[locale]/admin/... (staff only)                                   │
│  Holds only the Supabase PUBLISHABLE key + the user's session               │
└───────────────┬─────────────────────────────────────────┬───────────────────┘
                │ HTTPS                                   │ HTTPS (reads under RLS)
┌───────────────▼──────────────── Vercel ─────────┐       │
│ Next.js server (route handlers / server actions)│       │
│ • Input validation (schema)                     │       │
│ • Rate limiting on booking + auth routes        │       │
│ • Idempotency keys for booking submit           │       │
│ • Calls DB RPCs *with the user's JWT* (RLS on)  │       │
│ • NO service_role in request paths              │       │
└───────────────┬─────────────────────────────────┘       │
                │                                         │
┌───────────────▼─────────────── Supabase (per environment) ──────────────────┐
│ Auth: email+password, email verification, roles in app_metadata/staff table │
│ Postgres (source of truth):                                                  │
│   tables + FKs + CHECKs + EXCLUSION constraint (no double booking)           │
│   RPCs (SECURITY INVOKER): quote_booking, create_booking, transition_booking │
│   RLS on every exposed table · audit triggers · status-history table         │
│ Storage: vehicle-photos (public read, staff write) · private bucket if A8    │
│ Edge Function (later): notification sender reading an outbox table          │
└──────────────────────────────────────────────────────────────────────────────┘
Environments: local (Supabase CLI/Docker) → dev project + Vercel Preview → prod project + Vercel Production (owner-approved only)
```

### Why this shape
| Decision | Choice | Reason | Alternative considered |
|---|---|---|---|
| Framework | **Next.js (App Router) + TypeScript** | Public vehicle pages need SEO in two languages (server rendering, `hreflang`). Server-side code is needed for rate limiting and idempotency. First-class on Vercel. | Vite SPA: simpler, but weak SEO, and every rule would sit only in RPCs plus client code |
| Business rules | **In Postgres** (constraints + RPCs), not in JS | One source of truth that holds for every client, and race-safe | Rules in Next.js only: bypassable through the Data API, and race-prone |
| Authorization | **RLS + role checks in the DB** | Defense even if the UI or API code has a bug | UI-only guards (the prototype's model): rejected |
| Privileged key | `service_role`/secret key **only** in a future Edge Function for notifications | Least privilege | Using it in Next.js server code: rejected, because it bypasses RLS |
| i18n | Locale in the URL (`/en`, `/ar`), namespaced message files, `dir` set on `<html>` | SEO, shareable links, fixes L-013 | Toggle in memory (prototype): not indexable |
| Styling | Design tokens as CSS variables; logical properties only | Already proven in the prototype; RTL-safe | — |
| Testing | Vitest, SQL tests (pgTAP), Playwright | See TESTING_STRATEGY.md | — |

**Versions are deliberately not pinned in this document.** They will be checked against official docs (via Context7, once connected) when the project is scaffolded, and recorded in the lockfile.

---

## 3. Core flows

### 3.1 Create booking (the critical path)
1. The browser asks for a **quote**: `quote_booking(vehicle, pickup_at, return_at, location, extras)`. The DB computes days and price from DB rates. The quote is for display only.
2. On submit, the browser calls the server route with an **idempotency key** (a UUID generated once per checkout).
3. The server validates the input shape, rate-limits, and calls `create_booking(...)` with the user's JWT.
4. Inside `create_booking` (one transaction):
   - checks that `pickup_at > now()`, that `return_at > pickup_at`, the min/max rental length from settings, and that the vehicle is active and the location valid
   - **recomputes the price** from DB rates, ignoring any client price
   - inserts the booking with status `pending` (or `confirmed` if auto-approve is on) and the customer = `auth.uid()`
   - the **exclusion constraint** rejects any overlap atomically, returned to the client as a clean `BOOKING_CONFLICT`
   - writes the status-history row and an outbox row (for the future notification sender)
5. The UI shows success **only** on a returned booking row. On conflict or error it shows a specific message in EN or AR. A retry with the same idempotency key returns the same booking and never creates a duplicate.

### 3.2 Staff status change
`transition_booking(booking_id, to_status, note)` checks the caller's staff role and checks the transition against an allowed-transitions table (`pending→confirmed|rejected|cancelled`, `confirmed→active|cancelled`, `active→completed`). It writes history and the audit log. Direct `UPDATE` of `status` is blocked by RLS and privileges.

### 3.3 Customer cancellation
Allowed only for the customer's own `pending`/`confirmed` booking, before a cut-off set by the owner **[A9: cut-off hours?]**, through the same RPC path.

---

## 4. Double-booking prevention (summary; full DDL in the DB design)
- `bookings.period tstzrange` generated from `[pickup_at, return_at)` (half-open, so a return at 10:00 and the next pickup at 10:00 don't conflict).
- `EXCLUDE USING gist (vehicle_id WITH =, period WITH &&) WHERE (status IN ('pending','confirmed','active'))`, which needs the `btree_gist` extension (**to verify that it is enabled or can be enabled on the dev project**).
- An optional **turnaround buffer** (cleaning/inspection, e.g. 2 h) built into the stored range **[A10: buffer length?]**.
- Maintenance blocks are stored as rows in a `vehicle_blocks` table with the same constraint pattern, so a car in maintenance can't be booked.
- Verified with a concurrency test: N parallel `create_booking` calls for the same slot must give exactly 1 success.

## 5. Permission model (summary)
| Actor | Can |
|---|---|
| Anonymous | Read active vehicles, photos, public rates, locations, and extras. Call `quote_booking`. Nothing else. |
| Customer | Everything anonymous can do, plus read and update **own** profile, create bookings for **self**, read **own** bookings, and cancel **own** booking within the rules. |
| Staff | Read all bookings, customers, and vehicles; transition bookings; edit vehicles and photos; manage blocks. Cannot change roles or settings. |
| Admin | Everything staff can do, plus settings, rates, extras, staff management, and the audit log. |

Roles live in a `staff_members` table (or `app_metadata`), **never** `user_metadata`. Every policy is `TO authenticated` + a row predicate. UPDATE policies have both `USING` and `WITH CHECK`.

## 6. Pricing and date/time strategy (summary)
- Money is stored as **integer cents**, with a currency column (USD). No floats.
- Price = `days × vehicle daily rate` + `Σ extras (per day or per rental)` + fees. It is computed **only** in the DB and stored on the booking as a snapshot (`price_breakdown jsonb` + `total_cents`), so later rate changes don't alter past bookings.
- Days rule **[A5]** is implemented once in SQL and unit-tested at the boundaries (exact 24 h, 24 h + grace, 24 h + grace + 1 min, DST change dates).
- Times are stored as `timestamptz` (UTC instant). They are entered and displayed in **Asia/Beirut** regardless of the browser's timezone, which fixes L-006. "Now" comes from the server (`now()`), never a hard-coded date (fixes L-005).
- Pickup and return times are on a 30-minute grid within branch opening hours **[A11: opening hours per branch?]**.

## 7. Threat assessment (top risks for this system)
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| BOLA: customer reads or edits another's booking or PII | High if RLS is wrong | High (PII leak, legal) | RLS ownership predicates; RLS test matrix in CI |
| Admin takeover / privilege escalation | Medium | Critical | Roles in DB, not `user_metadata`; MFA for staff accounts **(recommended)**; audit log |
| Double booking through race or API bypass | Medium | High (operational, reputation) | Exclusion constraint + concurrency test |
| Price or status tampering | Medium | High | Server-side pricing; transition RPC; no direct status updates |
| Stored XSS in the admin UI | Medium | High (staff session theft) | React escaping; no `dangerouslySetInnerHTML`; payload E2E test |
| Secret leakage (service_role in the bundle, keys in chat or git) | Medium | Critical | Publishable key only on the client; bundle grep in CI; push protection |
| Booking spam / bot sign-ups | Medium | Medium | Email verification, rate limits, optional CAPTCHA on sign-up |
| Prompt injection through MCP reading DB content | Low–Med | High | MCP on dev only, read-only, project-scoped |
| Supply-chain compromise | Low–Med | High | Minimal dependencies, pinned versions, lockfile, audit |
| Data loss | Low | High | Supabase backups (check the plan's retention), migrations in git, no destructive SQL without approval |

## 8. Integration status (verified 2026-11-30)
| Integration | Installed | Connected | Tested | Notes |
|---|---|---|---|---|
| Supabase plugin | ✅ | ❌ | ❌ | Skills active. MCP tools not present in session: needs OAuth and a dev project. Configure the scope as `project_ref` + `read_only`. |
| Superpowers plugin | ✅ | n/a | ✅ skills load | Added on 2026-11-30 (not in your priority list; keep or remove at your discretion) |
| GitHub | ❌ | ❌ | ❌ | Account not linked; `gh` token in workspace invalid |
| Vercel | ❌ | ❌ | ❌ | Plugin not added |
| Context7 | ❌ | ❌ | ❌ | Plugin not added |
| Playwright (local library) | ✅ preinstalled | n/a | ✅ | Produced the screenshots. This covers E2E testing in the workspace. |
| Playwright MCP plugin | ✅ (added 2026-11-30) | ❌ in this session | ❌ | Enabled on the account, but no tools appeared after a refresh. Re-test in a new chat. The local library already covers tests. |
| Package installs (npm) | — | ❌ | ❌ | Blocked by the account network setting; needed to scaffold |

## 9. Open questions for the owner
A1–A11 above, plus:
- Q1. Is artifact `9aAR5Qh2L94Uw3zpaWRjhC` the right prototype? Are there other versions?
- Q2. Custom domain? Do you want separate admin and public domains?
- Q3. Do you have existing customer or booking data to import?
- Q4. Who else will have admin access?

## 10. Next deliverables (after you approve this)
1. **Database design**: full schema DDL, relationships diagram, constraints, indexes.
2. **RLS policy set** (SQL) + the RLS test matrix.
3. **Prioritised issue list** (L-001 to L-014) by security severity × business impact.
4. Repository scaffold plan (no feature code) once GitHub is connected.
