# corp.leisure.com

**leisure.com · Business mode** — the corporate travel tool.

Employees request work flights and hotels, one admin approves them against
travel policy, and approved trips are booked automatically on the company card.
Personal mode on [`leisure-ui.com`](../leisure-ui.com) stays exactly as it is
today.

The **employee** side of Business mode lives here: work-email sign-in, the
traveller profile, the flights search results page, the request-approval overlay
and My requests. The **admin** side (approval queue, workforce management, the
Travel Policy page) is being built separately — see
[What is built](#what-is-built). The backend for all of it lives in
`monorepo.leisure.com`'s **user-service**, under `/business/*`.

---

## Table of contents

- [Product context](#product-context)
- [What is built](#what-is-built)
- [The Business API](#the-business-api)
- [Booking for a colleague, in the browser](#booking-for-a-colleague-in-the-browser)
- [Building from the designs](#building-from-the-designs)
- [Stack](#stack)
- [Requirements](#requirements)
- [Getting started](#getting-started)
- [Running the app](#running-the-app)
- [Ports](#ports)
- [Environment variables](#environment-variables)
- [Project layout](#project-layout)
- [Styling and UI](#styling-and-ui)
- [Adding shadcn/ui components](#adding-shadcnui-components)
- [Code quality](#code-quality)
- [Local test account](#local-test-account)
- [Deployment (PM2)](#deployment-pm2)
- [Git workflow](#git-workflow)
- [Troubleshooting](#troubleshooting)

---

## Product context

Source of truth is the PRD — _Corporate Travel Tool_, v1.0 (Draft for review),
Parminder Singh, 30 September 2026. It is **not** committed here; ask the author
for the current revision. This section is a summary, so where it disagrees with
the PRD, the PRD wins.

### Roles

| Role     | How many                                               | Needs approval?                                    |
| -------- | ------------------------------------------------------ | -------------------------------------------------- |
| Admin    | Exactly **one** account per company                    | No — books own travel directly on the company card |
| Employee | Any number, **invited** by the admin (no self sign-up) | Yes — every request goes to the admin              |

Everyone signs in with a work email and a one-time password. There is no
password and no multi-level approval chain.

### The flow

1. Employee searches flights or hotels — the same search as the leisure site —
   and hits **Request approval** instead of Book.
2. The request (`FR-xxxx` for flights, `HR-xxxx` for hotels) is checked against
   travel policy and lands in the admin's queue.
3. The admin **approves**, **rejects** (reason required) or **requests more
   info** (message required).
4. On approval the trip is re-priced and **auto-booked on the company card** at
   the current price. There is no manual booking step.
5. The e-ticket or hotel confirmation is emailed to the employee.

Changes and cancellations go back through the same admin decision as a new
request linked to the original.

### Things that are easy to get wrong

- **Policy flags, it does not block.** A request that fails a policy rule is
  still submittable and still approvable. The flags travel with it to the admin.
  Never build a hard gate on a policy check.
- **Cost centres, multi-level approval and routing by department are explicit
  non-goals** for this version, as are guest travellers from outside the company
  and combined flight + hotel requests. Department, office location and employee
  ID exist as optional profile fields only.
- **A party of up to 9 travellers is supported**, which is a deliberate
  departure from the PRD's "traveller count is fixed at 1". The fare an Amadeus
  offer is priced for decides the party size; travellers 2..N are companions
  typed into the request overlay and have no account of their own. See
  [Where this repo diverges from the PRD](#where-this-repo-diverges-from-the-prd).
- **Profile edits apply to new requests only.** A submitted request keeps a
  snapshot of the profile it was sent with.
- **All notifications are email.** No in-app or push notifications.
- **Money is USD.**

### Where this repo diverges from the PRD

Each of these was decided deliberately. Do not "fix" one back towards the PRD
without raising it first.

| Divergence                                                                                | Why                                                                         |
| ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| **Up to 9 travellers per request**, not 1                                                 | An Amadeus offer is priced for the exact party searched for                 |
| Companions are **typed into the overlay**, not picked from a list                         | They have no account; their passports are stored as last 4 only             |
| **Domestic = both airports in the same country**, not the PRD's literal "within the U.S." | The product is not US-only                                                  |
| `POST /business/requests/preview` exists                                                  | The overlay shows a real policy verdict before submit instead of faking one |
| No department filter in the admin queue; no bulk checkboxes; no "L3 · Manager" grade      | PRD over design; the grade has no backing field anywhere in the API         |

### Still open in the PRD

Unresolved upstream and affecting implementation. Do not design around a guess:

| #   | Question                                                                             |
| --- | ------------------------------------------------------------------------------------ |
| 3   | Meeting type dropdown options (the API serves six defaults until an admin saves any) |
| 4   | Which flight and hotel booking provider / APIs auto-booking uses                     |
| 5   | OTP length, expiry and resend limits                                                 |
| 6   | What happens to an employee's pending or booked trips when they are deactivated      |
| 7   | Whether there is a backup approver when the single admin is unavailable              |
| 8   | Whether a large price rise after approval blocks auto-booking                        |
| 9   | Whether `corp.leisure.com` hosts the whole Business side or only sign-up + admin     |
| 10  | Whether one admin per company is enforced by name or email domain                    |
| 11  | Whether a company is verified before its admin can book, and where the card is added |
| 13  | Gender options for the invite form and CSV                                           |
| 14  | Whether invites can be resent or cancelled, and whether they expire                  |

PRD v1.0 resolved three that earlier revisions left open: the admin **can** edit
policy rules (§8.5), hotel policy values are **per group** on that same page, and
**groups** are what a travel policy attaches to — every employee belongs to
exactly one, and invites pick from the existing groups.

**Open question 9 is still open**, but it no longer blocks: §4.2 puts admin
sign-up at `corp.leisure.com` while §4.1 puts the Personal / Business toggle in
the `leisure.com` header. In practice the whole employee experience has been
built here, and `leisure-ui.com` has no Business-mode code at all.

---

## What is built

Flights only. The hotels SRP is ported and reachable, but no hotel request can
be submitted — `POST /business/requests` accepts `type: "FLIGHT"` and nothing
else.

| Route                          | What it is                                                                                                                                        |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/`                            | Placeholder marketing page. **Not** the PRD's §6.1 search landing — that is unbuilt                                                               |
| `/employee-signup`             | Account setup from an invite link: Your details → Verify email → Done                                                                             |
| `/employee-login`              | Work-email + OTP sign-in                                                                                                                          |
| `/employee-profile`            | Traveller profile, **read-only today** (the API can update it; the UI cannot)                                                                     |
| `/srp/flights`                 | Flights SRP — one-way, round trip, multi-city, date-strip prices, filters, sorts, compare tray, layover drawer, AI smart filters, **Booking for** |
| `/srp/hotels`                  | Hotels SRP — parked                                                                                                                               |
| `/employee-requests`           | My requests — All / Open / Closed, status tracker, request detail                                                                                 |
| `/employee-requests/submitted` | The §6.6 confirmation screen                                                                                                                      |
| `app/api/*`                    | 19 route handlers: AI, geolocation, places, presence, flight helpers                                                                              |

Every "pick this flight" surface — the result card, the fares modal, the
round-trip pair bar and the multi-city bar — ends at
`services/flights/approvalRequest.ts`, which opens the **E4 request-approval
overlay** (`components/employee-requests/`) rather than a booking funnel.

### Not built here

- **The admin side** — dashboard, approval queue, review overlay, workforce
  management, the Travel Policy page. Owned by another developer; do not start
  it here without checking.
- **Request mutations** — edit, withdraw, reply to an info request, resubmit,
  change, cancellation. The INFO_REQUESTED card shows the admin's question
  read-only with a "coming soon" note. (A traveller viewing a trip somebody
  arranged for them is told who _can_ answer it — only the requester ever may.)
- **Auto-booking, re-pricing, payment and e-tickets** (PRD §9).
- **Hotel requests**, the §6.1 search landing with the Hotels | Flights toggle,
  the "Business travel · needs approval" label, per-result policy badges, and
  profile editing.

---

## The Business API

The backend is **not** in this repo. It lives in `monorepo.leisure.com` under
`apps/user-service`, and every route sits beneath `/business`:

```
POST /business/auth/otp/send          POST /business/auth/otp/verify
POST /business/companies/signup       POST /business/auth/signout
GET  /business/me                     GET|POST /business/profile
POST /business/employees/invite       GET  /business/employees/invite
POST /business/employees/accept-invite
GET  /business/travellers             GET  /business/travellers/:businessUserId
POST /business/requests               POST /business/requests/preview
GET  /business/requests               GET  /business/meeting-types
GET  /business/admin/requests         GET  /business/admin/requests/summary
```

Three things to know before calling any of them:

1. **There is no `/api/user` prefix.** `API_USER_PREFIX` is `''` in
   user-service's route index, commented out pending a gateway. `lib/env.ts`'s
   `userApiUrl` points at the service directly.
2. **The contract doc is the Postman collection**, not this README:
   `monorepo.leisure.com/docs/Leisure Business Corp API.postman_collection.json`.
   Every example in it was executed against the live code.
3. **Business sessions are separate from Personal ones.** The JWT lives in
   `localStorage` (`lib/business-session.ts`), and
   `services/employee-requests/employee-requests.client.ts` and
   `services/employee-login/employee-login.client.ts` are **dedicated fetch
   clients** rather than the shared `services/http.client.ts` — that one calls
   `logoutAndRedirect()` on a 401, which would clear the Personal-mode cookies
   and bounce to a `/sign-in` route corp does not have.

There is no `GET /business/requests/:id`, so the submitted screen renders from
the POST response stashed in `sessionStorage` and degrades to the list endpoint
on a cold load.

### Booking for a colleague

`GET /business/travellers` is the **Booking for** dropdown (PRD §6.1): the
employee first, then the active employees of their own policy group. Pass
`airports` — every IATA code on the itinerary — and the response resolves the
Domestic/International tab and applies that tab's **Colleague booking** toggle to
each row's `selectable`. Both tabs' allowances come back either way, so changing
the destination re-gates the list client-side without another call. Rows that
cannot be picked are still listed, with a `reason`
(`COLLEAGUE_BOOKING_OFF`, `PROFILE_INCOMPLETE`, `PASSPORT_REQUIRED`) — explain,
do not hide.

`POST /business/requests` and `/requests/preview` then take **`travelerId`** (a
string: these ids are BigInts). The traveller's profile is snapshotted and their
group's policy applied; the caller stays the requester and is the only person who
can act on the request afterwards. The list endpoint is a convenience, never the
authority — the submit re-checks every condition, because a dropdown can be
minutes stale by the time someone presses Submit.

Two rules worth not rediscovering:

- **A requester never writes to a colleague's profile.** Sending a `passport`
  block for someone else is refused with `PASSPORT_NOT_YOURS`, and a colleague
  with no passport on file simply cannot be sent abroad
  (`COLLEAGUE_PASSPORT_REQUIRED`) until they add one themselves.
- **The overlay must not offer a passport field for a colleague.** The preview's
  `trip.passportRequired` is true only on a self-request, for that reason.

---

## Booking for a colleague, in the browser

The feature spans four files worth knowing about before touching any of them.

| File                                                  | What it owns                                                 |
| ----------------------------------------------------- | ------------------------------------------------------------ |
| `services/employee-requests/booking-for.ts`           | The `bookingFor` URL param and the itinerary → airports list |
| `components/booking-for/BookingForField.tsx`          | The control on the search bar                                |
| `components/booking-for/BookingForBanner.tsx`         | "You are booking for ‹name›" above the results               |
| `components/employee-requests/useRequestTraveller.ts` | One traveller shape for the overlay, self or colleague       |

### The selection lives in the URL

`bookingFor=<businessUserId>` is read, never mirrored into state. Every other
field on that bar derives from the query string and is re-derived when it
changes; a second copy would need the same treatment, and the `setState` in that
effect is exactly what the React Compiler rejects in corp's own code. Deriving
it gives the Back button and a pasted link the right answer for free.

Picking somebody writes the param with `router.replace` and **does not re-run
the search**: `searchCacheKey()` is built from the search input — route, dates,
party, cabin — so this param is not part of it and the results on screen stay.
The fares are identical whoever flies; what changes is whose policy the request
is judged against, which happens in the overlay.

**Anything that rebuilds a search URL from scratch has to carry it.**
`dateStripHref` does; `buildCompareUrl` copies the whole query string, so it
gets it free. Without that, clicking a cheaper date silently re-points the
request at whoever clicked.

### Three rules the UI must not break

1. **A requester never writes to a colleague's profile.** The overlay shows no
   passport block for a colleague, and the API refuses one with
   `PASSPORT_NOT_YOURS`.
2. **Ineligible colleagues are shown, not hidden** — `aria-disabled` with the
   server's reason, and still reachable by keyboard. "Esha is missing" and
   "Esha cannot be picked because colleague booking is off for international
   trips" are the same screen to someone who cannot see the second one.
3. **Actions come from `canAct`, never from comparing ids.** My requests is the
   union of trips you are taking and trips you arranged; the server says which
   you are (`viewerRole`) and whether you may act. Only the requester ever may.

The banner exists for one reason: the selection sits in a narrow cell on a bar
that scrolls away, survives a whole session in the URL, and changes nothing
about the results — so without it there is no signal at all that the next
"Request approval" is not for you.

### Divergence from leisure-ui

`components/flights/v3/FlightSearchFormV3.tsx` and `FlightTravelersV3.tsx` are
the **first ported files to diverge deliberately**. Travellers and Cabin Class
are merged into one "Travellers & Class" field (the cabin chips live inside the
travellers panel) to free the column Booking For occupies. Every change is
marked `CORP-ONLY`; leisure-ui is not getting the merge.

---

## Production logging

Logs are JSON lines on stdout/stderr, captured by pm2 into `logs/pm2-*.log`. No third-party
tool is involved (that is a separate decision). Every line has `service: "corp-leisure"`.

| What | Where | Line |
|---|---|---|
| Every `app/api/*` request | `withApiLogging` (`lib/api-route-logging.ts`) | exactly one: route, method, status, `durationMs`, `requestId` |
| A failed backend call in the browser | `http.client.ts` and the business fetch clients, via `loggedFetch` → `POST /api/log` | `msg: "client error"`, `clientType: "http_error"`, endpoint (path only), status, error `code`, `clientRequestId`, `companyId`/`employeeId`/`role` |
| A page crash | `app/error.tsx`, `app/global-error.tsx` → `POST /api/log` | `clientType: "render_error"`, error name, `digest`, scrubbed message |
| A server render error | `instrumentation.ts` (`onRequestError`) | `msg: "server render error"`, route, `digest` |

**Tracing one incident.** The browser sends `x-request-id` on every backend call. user-service,
booking-service and search-service adopt it, so `grep <id>` finds the app's report (`clientRequestId`)
and the backend's own lines. A crash's "Reference: …" on the error screen is the `digest`, present on both
the browser report and the server line.

**What is never logged:** request/response bodies, emails, names, dates of birth, passport or card
numbers, tokens. Business context is **ids and role only**, via `lib/log-context.ts` (the one place
that reads the business token for logging). `POST /api/log` accepts a fixed set of fields, each validated;
anything else is discarded; it is size-limited (4 KB) and rate-limited (30/min per IP).
`lib/logger.ts` is unchanged: silent in the browser in production.

**Log rotation** is configured on the server, not in the repo: run `bash scripts/setup-pm2-logrotate.sh`
once on production (rotate at 50 MB or daily, keep 14 rotated files). Rotated files are not compressed: pm2-logrotate 3.0.0 ignores its `compress` setting (see the comment in the script).

## Building from the designs

The design team's mockups live on an internal PHP server:

```
https://design.admedia.com/leisure-new/lesiure-biz/
```

(`lesiure-biz` is misspelled in the real path.) HTTP basic auth, user `design`
— ask Bhupesh for the password. Directory listing is on, so fetch the index to
see what exists. As of 30 September 2026 there are **seven flight-only pages**
and no hotel designs:

`employee-signup` · `employee-login` · `employee-request-flight` ·
`employee-request-review` · `employee-request-submitted` ·
`flight-booking-approval` · `corporate-wallet`

`travel-policy.css` exists but `travel-policies.php` does not, and there is no
workforce/invite page or admin sign-up page yet.

### Reaching it

The VPN alone is not enough. `design.admedia.com` resolves via public DNS to
`192.168.31.170`, and a typical home LAN is the same `192.168.31.0/24` range,
so the directly-connected route wins and the request never enters the tunnel.
Bind it to the tunnel interface instead:

```bash
ifconfig | grep -E "^utun[0-9]+:"        # find the live tunnel, not always utun6
curl --interface utun6 --user 'design:<pass>' "<url>"
```

A browser cannot bind an interface, so it will likely fail where curl succeeds.

### Translate, do not transplant

**The mockups are Bootstrap 5.3.6 plus the jQuery ecosystem** (select2, Owl
Carousel, bootstrap-datepicker, daterangepicker, intl-tel-input, Swiper,
LightGallery), and they load `leisure-ui.com`'s own stylesheets. **This repo is
Tailwind v4 + shadcn/ui and stays that way.**

So rebuilding a mockup means:

| Take from the mockup                                                             | Replace                                             |
| -------------------------------------------------------------------------------- | --------------------------------------------------- |
| Layout, spacing, hierarchy, states                                               | Bootstrap grid/utility classes → Tailwind utilities |
| **Copy, verbatim** — labels, helper text, warnings, the passport acknowledgement | —                                                   |
| Component behaviour                                                              | jQuery widgets → shadcn/ui components               |
| Iconography                                                                      | Font Awesome / Bootstrap Icons → `lucide-react`     |

Never add Bootstrap, jQuery or any mockup widget library to this repo. The
microcopy is deliberate — copy it word for word rather than paraphrasing.

### Design-system deltas

Diffing the mockups' `:root` against `leisure-ui.com` (33 shared tokens):

- **One colour differs.** `--color-first` is `#0F2733` in the designs and
  `#2f6271` in leisure-ui. The other 23 colour tokens match exactly, dark-mode
  values included.
- **Fonts differ more.** The designs use **Barlow** for content and **Barlow
  Condensed** for sub-headings where leisure-ui uses Lato, plus **Work Sans**,
  which leisure-ui aliases away. Gilda Display for headings matches. Barlow,
  Barlow Condensed and Work Sans are new to the codebase.

Partly ported now. `app/globals.css` carries shadcn's token block **plus** two
bespoke sets: `--color-lx-*` for the ported header/footer chrome, and
`--fra-*` for the request-approval screens (navy `#0f2733`, coral `#f45d6b`,
and the pending / approved / rejected / info palettes the mockups use). Barlow,
Barlow Condensed and Work Sans are still not installed — `lib/fonts.ts` ships
Lato, Gilda Display and Inter.

### When the designs and the PRD disagree

They disagree in at least seven places — employee self-sign-up, departments and
employee IDs, the department filter in the queue, manager-vs-single-admin
approval, multi-traveller search, the entire corporate wallet, and bulk approve.

**Do not pick a side.** Surface the specific conflict when the work starts and
wait for an explicit decision.

---

## Stack

| Concern         | Choice                                            | Version    |
| --------------- | ------------------------------------------------- | ---------- |
| Framework       | Next.js (App Router, Turbopack)                   | `16.1.3`   |
| UI runtime      | React                                             | `19.2.3`   |
| Language        | TypeScript                                        | `^5`       |
| Styling         | Tailwind CSS                                      | `^4`       |
| Components      | shadcn/ui (`new-york`, `neutral` base)            | registry   |
| Primitives      | `radix-ui` (unified package)                      | `^1.6.7`   |
| Class merging   | `cn`                                              | `^0.4.0`   |
| Icons           | `lucide-react`                                    | `^0.562.0` |
| Variants        | `class-variance-authority`                        | `^0.7.1`   |
| Client state    | Redux Toolkit + `redux-persist`                   | `^2.13.0`  |
| Server state    | TanStack Query                                    | `^5.104.0` |
| Forms           | `react-hook-form` + `zod` + `@hookform/resolvers` | `^7.89.0`  |
| Toasts          | `sonner`                                          | `^2.0.8`   |
| Linting         | ESLint 9 (flat config) + `eslint-config-next`     | `^9`       |
| Formatting      | Prettier + `prettier-plugin-tailwindcss`          | `^3.6.2`   |
| Process manager | PM2                                               | (global)   |

Next.js and React are **pinned to exact versions** deliberately — they match
`leisure-ui.com` so the two frontends stay on one toolchain and code moves
between them without a version negotiation. Bump them together, not separately.

> **Note on Tailwind:** this repo genuinely uses Tailwind. Do not copy styling
> conventions from `leisure-ui.com` — that app is Bootstrap 5 and its Tailwind
> install is inert. The two repos share a toolchain, not a design system.

---

## Requirements

- **Node.js 24.22.1** — pinned in [`.nvmrc`](.nvmrc), the same version as
  `admin.leisure.com` and the monorepo's `admin-service`. `leisure-ui.com`,
  `search-service.leisure.com` and the other monorepo services are still on 22,
  so run `nvm use` when you switch repos.
- **npm 11+** (ships with Node 24). npm 10 writes a slightly different
  `package-lock.json`, so install with npm 11 to keep the lockfile stable.
- **PM2**, only if you are running a production-style process locally:
  `npm i -g pm2`.

`nvm` is not sourced by default in every shell here. If `node -v` does not print
`v24.22.1`, run:

```bash
export NVM_DIR="$HOME/.nvm" && . "$NVM_DIR/nvm.sh" && nvm use
```

`nvm use` with no argument reads `.nvmrc`. If the version is not installed yet:

```bash
nvm install 24.22.1
```

Building on Node 18 will fail — Next.js 16 requires Node 20.9+.

---

## Getting started

```bash
# 1. clone
git clone https://bit.admedia.com/scm/ad/corp.leisure.com.git
cd corp.leisure.com

# 2. use the pinned Node version
export NVM_DIR="$HOME/.nvm" && . "$NVM_DIR/nvm.sh" && nvm use

# 3. install dependencies
npm install

# 4. create your local environment file
cp .env.example .env.local

# 5. run
npm run dev
```

Open <http://localhost:7005>.

---

## Running the app

| Command                | What it does                                                         |
| ---------------------- | -------------------------------------------------------------------- |
| `npm run dev`          | Dev server with Turbopack and hot reload on **port 7005**            |
| `npm run build`        | Production build into `.next/`                                       |
| `npm start`            | Serve the production build on **port 7005** (requires `build` first) |
| `npm run lint`         | ESLint over the project                                              |
| `npm run lint:fix`     | ESLint with autofix                                                  |
| `npm run typecheck`    | `tsc --noEmit` — type errors without a build                         |
| `npm run format`       | Prettier write over the project                                      |
| `npm run format:check` | Prettier check — use this in CI                                      |

The port lives in the `-p` flag of the `dev` and `start` scripts. To override it
for a one-off run:

```bash
npx next dev -p 7010
```

---

## Ports

The workspace shares a machine, so ports are allocated rather than defaulted:

| Port      | Owner                                                                                                |
| --------- | ---------------------------------------------------------------------------------------------------- |
| 7001      | (in use, unidentified)                                                                               |
| 7002      | `leisure-ui.com`                                                                                     |
| 7003      | `search-service.leisure.com` — per its `ecosystem.config.js` and `.env.example`                      |
| 7004      | `search-service.leisure.com` — **actual**, via a local `.env` override                               |
| **7005**  | **`corp.leisure.com`** (this app)                                                                    |
| 3010–3016 | `monorepo.leisure.com` services (admin, user, booking, payment, notification, analytics, automation) |

`corp` took 7005 rather than 7004 because `search-service`'s local `.env` sets
`PORT=7004`, contradicting its own committed config. macOS will happily let two
processes bind the same port on different address families (IPv4 vs IPv6), so a
collision here does **not** fail loudly — it fails intermittently. Check before
assuming a port is free:

```bash
lsof -iTCP:7005 -sTCP:LISTEN -P -n
```

---

## Environment variables

[`.env.example`](.env.example) is the committed template. Copy it to
`.env.local` — which is gitignored — and fill in the values.

```bash
cp .env.example .env.local
```

| Variable                         | Purpose                                                                                   |
| -------------------------------- | ----------------------------------------------------------------------------------------- |
| `PORT`                           | Port the app listens on. Must stay in sync with `package.json` and `ecosystem.config.js`. |
| `NEXT_PUBLIC_APP_URL`            | Public origin of this app. Used for `metadataBase`, absolute URLs and OG tags.            |
| `NEXT_PUBLIC_ASSET_PREFIX`       | Optional CDN prefix for static assets. Empty locally.                                     |
| `NEXT_PUBLIC_API_GATEWAY_URL`    | `monorepo.leisure.com` API gateway — user, booking, payment, notification services.       |
| `NEXT_PUBLIC_SEARCH_SERVICE_URL` | `search-service.leisure.com` — flight and hotel search.                                   |
| `NEXT_PUBLIC_API_BASE_URL`       | This app's own route handlers under `/api`.                                               |

The two upstream URLs are **provisional**: they point at the services that run
locally today, but the PRD leaves the booking provider open (open question 4).

Read them through [`lib/env.ts`](lib/env.ts) rather than touching
`process.env` directly:

```ts
import { env } from "@/lib/env";

const res = await fetch(`${env.searchServiceUrl}/flights`);
```

Two rules that are easy to get wrong:

1. **Only `NEXT_PUBLIC_*` variables reach the browser.** Anything without that
   prefix is server-only. Never put a secret behind a `NEXT_PUBLIC_` name.
2. **Next.js inlines these at build time by literal name.** You cannot write
   `process.env[someVariable]` and expect a value in the client bundle — which
   is exactly why `lib/env.ts` lists each one explicitly.

Call `assertUpstreamEnv()` from a server component or route handler to fail fast
on a missing upstream URL instead of firing an empty-string `fetch`.

---

## Project layout

App Router with everything at the repository root — **no `src/` directory**.
This matches `leisure-ui.com`, so files move between the two repos without
rewriting import paths.

```
corp.leisure.com/
├── app/                     # App Router: routes, layouts, route handlers
│   ├── globals.css          # Tailwind entry, cascade layers, design tokens
│   ├── layout.tsx           # Root layout: fonts, chrome, providers
│   ├── api/                 # 19 route handlers (AI, places, presence, geo)
│   ├── employee-login/      # work-email + OTP sign-in
│   ├── employee-signup/     # account setup from an invite link
│   ├── employee-profile/    # traveller profile
│   ├── employee-requests/   # My requests + /submitted
│   └── srp/                 # search results; layout.tsx scopes the vendor CSS
├── components/
│   ├── employee-requests/   # the E4 overlay, request cards, trackers
│   ├── employee-login|signup|profile/
│   ├── flights/             # SRP, ported from leisure-ui (v3/ = the search form)
│   ├── search/              # hotels SRP, ported
│   ├── layout/              # SiteHeader / SiteFooter, rebuilt in Tailwind
│   └── ui/                  # shadcn/ui + a few ported primitives
├── features/                # per-feature zod schemas, hooks and types
├── services/                # API clients and pure domain logic
│   ├── employee-requests/   # Business API client, offer mapper, approval bus
│   └── flights/             # ported flight logic (mapper, filters, URL state)
├── store/                   # Redux Toolkit slices + redux-persist
├── lib/                     # env, fonts, business-session
├── constants/ hooks/ utils/ types/ context/
├── scripts/                 # verify-*.ts, run with `npx tsx`
├── public/assets/           # leisure-ui's vendored CSS/JS, for /srp only
├── components.json          # shadcn/ui CLI configuration
├── ecosystem.config.js      # PM2 process definition
└── .env.example
```

The `@/*` path alias resolves to the repository root, so `@/lib/env` is
`lib/env.ts` and `@/components/ui/button` is `components/ui/button.tsx`.

---

## Styling and UI

Tailwind v4 is configured **entirely in CSS** — there is no `tailwind.config.js`
and there should not be one. `app/globals.css` holds:

- `@import "tailwindcss"` — the framework entry.
- A `:root` / `.dark` block of design tokens in `oklch` (`--background`,
  `--primary`, `--muted-foreground`, …).
- An `@theme inline` block that maps those tokens onto Tailwind utilities, so
  `bg-background` and `text-muted-foreground` resolve to the variables.

Restyle the app by editing the tokens in `globals.css`, not by hardcoding colors
in components. Dark mode comes free from the `.dark` class because every
component reads a token.

### Bootstrap lives under `/srp` — and it bites

The SRP is ported verbatim from `leisure-ui.com`, which is a Bootstrap 5 app, so
`app/srp/layout.tsx` loads Bootstrap plus leisure-ui's vendored stylesheets
(`public/assets/css/srp-vendor.css`) and Bootstrap's JS bundle. Every other route
is pure Tailwind. Three consequences, all of which have already cost a day each:

1. **Cascade order is declared, not accidental.** `app/globals.css` opens with
   `@layer theme, base, leisure-vendor, components, utilities, bootstrap-compat;`
   and the vendor sheets are imported into `leisure-vendor`. Below `base` the
   ported SRP loses its styling to Tailwind's Preflight; unlayered (the default)
   the vendor sheets outrank every Tailwind utility, including the header and
   footer rendered above that route. Both failures were observed.
2. **Bootstrap and Tailwind share class names with different scales**, and
   Bootstrap's carry `!important`, which no layer can beat. `.py-5` is 48px in
   Bootstrap and 20px in Tailwind; `-3` is 16 vs 12 and `-4` is 24 vs 16, while
   `0`, `1` and `2` happen to agree. Anything rendered **into** that document —
   the request overlay is portalled to `document.body` — must use arbitrary
   values (`py-[20px]`, `gap-[12px]`) instead of the colliding names. Responsive
   variants are safe: Bootstrap spells those `p-sm-4`.
3. **Colour does not inherit there.** Bootstrap's reboot sets a body colour, so
   anything that does not state its own ends up `#474646` — including every
   `lucide-react` icon, which strokes with `currentColor`. `globals.css` rescues
   icons inside `[data-corp-modal]`; elsewhere, state the colour.

**Test anything that renders over the SRP at a route under `app/srp/`.** A
harness on a clean Tailwind page proves nothing — the overlay looked perfect in
one and was badly broken in the real document.

### Fonts

Self-hosted via `next/font/google` in [`lib/fonts.ts`](lib/fonts.ts) and exposed
as `--font-lato`, `--font-gilda` and `--font-inter`. `fontVariables` is spread
onto `<html>` in the root layout; `@theme inline` binds Inter to `--font-sans`.
Lato and Gilda exist because the ported chrome and SRP name them directly.

**Never add a Google Fonts `<link>` or `@import`** — it reintroduces a
render-blocking request that `next/font` exists to remove.

### Icons

`lucide-react`. Do not add a second icon library, and do not use emoji as icons.

---

## Adding shadcn/ui components

Components are **generated into the repo**, not installed as a dependency. You
own the code after it lands and are free to edit it.

```bash
npx shadcn@latest add dialog
npx shadcn@latest add form input select     # several at once
```

They land in `components/ui/` and are wired up by
[`components.json`](components.json).

### Why components import `cn` from `"cn"`

Generated components start with:

```ts
import { cn } from "cn";
```

not the `@/lib/utils` you may remember from older shadcn projects. The shadcn
CLI now emits this and installs [`cn`](https://github.com/shadcn-ui/cn) — an
official, compiled drop-in replacement for `clsx` + `tailwind-merge`. This repo
adopted it deliberately so `npx shadcn@latest add …` works with **zero manual
patching**.

Consequences:

- There is **no `lib/utils.ts`** in this repo, and `clsx` / `tailwind-merge` are
  not direct dependencies. That is intentional, not an oversight.
- When you copy a snippet from the shadcn docs or an older project that imports
  `cn` from `@/lib/utils`, change the import to `"cn"`.

### Primitives

The CLI installs the unified [`radix-ui`](https://www.npmjs.com/package/radix-ui)
package rather than per-primitive `@radix-ui/react-*` packages, so components
import like `import { Slot } from "radix-ui"`. Keep to that — mixing both styles
pulls two copies of Radix into the bundle.

---

## Code quality

```bash
npm run typecheck     # tsc --noEmit
npm run lint          # ESLint 9 flat config
npm run format:check  # Prettier, non-mutating
```

ESLint uses the flat config in [`eslint.config.mjs`](eslint.config.mjs):
`eslint-config-next` core-web-vitals + TypeScript rules, with
`eslint-config-prettier` last so ESLint does not fight Prettier over formatting.

**Ported code is linted at warn, corp's own code at error.** `eslint.config.mjs`
lists the directories copied verbatim from `leisure-ui.com` and downgrades
`no-explicit-any`, `no-unused-vars` and the React Compiler rules inside them, so
the findings stay visible without anyone "fixing" a file into a shape that no
longer diffs against upstream. **The baseline is 0 errors and ~83 warnings** —
all in ported code. That is not a regression; a new _error_ is.

Everything corp writes itself is fully strict, and the React Compiler rules bite
hardest there. Four patterns it rejects outright, with what to use instead:

| Rejected                           | Use                                                                  |
| ---------------------------------- | -------------------------------------------------------------------- |
| `setState` inside an effect        | TanStack Query for fetches; `useSyncExternalStore` for storage reads |
| Resetting state when a modal opens | a `key` on the modal, so it remounts clean                           |
| `watch()` from react-hook-form     | `useWatch` — `watch` makes the compiler skip the whole component     |
| `Date.now()` in a `useMemo`        | nothing; let the server decide, it re-checks every call              |

### Verify scripts

`scripts/` holds standalone checks run with `npx tsx` — there is no test runner
in this repo:

```bash
npx tsx scripts/verify-flight-offer-mapper.ts    # 63 checks on buildFlightOffer
```

The equivalents for the API live in `monorepo.leisure.com` as
`apps/user-service/src/scripts/verify-business-*.ts`.

Prettier is configured in [`.prettierrc`](.prettierrc) with
`prettier-plugin-tailwindcss`, which sorts Tailwind class names into the
canonical order automatically. Do not hand-sort classes.

Run all three before opening a pull request.

---

## Local test account

Business sign-in sends a real OTP by email (ZeptoMail is configured in
user-service), so a local account needs a real inbox.

```
bhupesh.yadav@admedia.com — company 157 "Admedia (local dev)", group 71,
EMPLOYEE / ACTIVE, traveller profile complete
```

Sign in at `/employee-login`. Two things that waste an afternoon otherwise:

- **A hand-seeded row must have `email_verified = true`.** An ACTIVE user with
  it false reads as a half-finished company signup, and `verifyOtp` refuses with
  the same deliberately vague _"We couldn't sign you in. Contact your company
  admin."_ it gives an unknown email — nothing in the response points at the
  real cause. Only the signup-verify and invite-accept paths ever set it.
- **The OTP is consumed before that check**, so a refused sign-in burns the
  code. Request a fresh one after fixing the cause rather than retrying the
  same digits.

`POST /business/employees/invite` requires `requireBusinessAdmin`, and there is
no admin account locally, so invites cannot be sent from a developer machine
without seeding one.

---

## Deployment (PM2)

[`ecosystem.config.js`](ecosystem.config.js) mirrors the pattern used by
`leisure-ui.com` and `search-service.leisure.com`.

```bash
npm run build          # required — PM2 runs `npm start`, which serves .next/
npm run pm2:start
```

| Command               | What it does                     |
| --------------------- | -------------------------------- |
| `npm run pm2:start`   | Start the `corp-leisure` process |
| `npm run pm2:status`  | Show process status              |
| `npm run pm2:logs`    | Tail this app's logs             |
| `npm run pm2:restart` | Restart after a rebuild          |
| `npm run pm2:stop`    | Stop the process                 |
| `npm run pm2:delete`  | Remove it from PM2               |

Logs are written to `logs/` (gitignored). The process is named `corp-leisure`,
restarts automatically, and recycles above 1 GB of memory.

After deploying a new build, `npm run build && npm run pm2:restart` — PM2 will
keep serving the stale `.next/` output otherwise.

---

## Git workflow

- **Remote:** `https://bit.admedia.com/scm/ad/corp.leisure.com.git` (Bitbucket,
  same host as the other Leisure repos).
- **Base branch:** `master`.

Branch off `master`, and prefix the branch with the kind of change:

```bash
git checkout master
git pull origin master
git checkout -b feat/rfp-approval-flow
```

Use `feat/`, `fix/`, `chore/` or `refactor/`. Commit messages follow the same
convention, with the ticket id where one exists:

```
feat: corporate policy engine for domestic flights (CORP-12)
```

Never commit `.env.local` — `.gitignore` covers `.env*` and whitelists only
`.env.example`. When you add a new variable, add it to `.env.example` **and**
`lib/env.ts` in the same commit, or the next person's checkout breaks.

---

## Troubleshooting

**`npm run dev` fails with a Node version or syntax error**
Your shell is on the wrong Node. Run
`export NVM_DIR="$HOME/.nvm" && . "$NVM_DIR/nvm.sh" && nvm use`. Next.js 16
needs Node 20.9+; this repo pins 24.22.1.

**Port 7005 is already in use**

```bash
lsof -iTCP:7005 -sTCP:LISTEN -P -n
kill <pid>
```

Note that macOS allows two processes to bind the same port on different address
families, so the app may appear to start while another service quietly answers
some requests. If behaviour is inconsistent, check for a second listener before
suspecting the code.

**A copied shadcn snippet fails with "Cannot find module '@/lib/utils'"**
Expected. Change the import to `import { cn } from "cn"` — see
[Adding shadcn/ui components](#adding-shadcnui-components).

**Tailwind classes have no effect**
There is no `tailwind.config.js` in Tailwind v4. Check that the utility's token
exists in the `@theme inline` block in `app/globals.css`, and that the file you
edited is reachable from `app/globals.css`'s import graph.

**Styles look wrong after adding a component**
Run `npm run format` — `prettier-plugin-tailwindcss` reorders classes, and
manually written order can mask a conflict that the plugin's ordering exposes.
