# RMS — Deployment Runbook

A small single-organisation deployment: one API process, two static SPAs
(admin + tenant portal), one MySQL 8 database, behind one reverse proxy.

```
                    ┌─────────────── reverse proxy (nginx/Caddy) ───────────────┐
                    │  /         → apps/admin/dist    (back office)             │
  rms.example.hk ──▶│  /portal/  → apps/portal/dist   (tenant portal)           │──▶ Nest API (:3000) ──▶ MySQL 8
                    │  /api/*    → API                                          │
                    └───────────────────────────────────────────────────────────┘
```

The SPAs call the API with **relative `/api`** paths, so each must be served on
the **same origin** as its API by the reverse proxy. This is the one hard
requirement — without the `/api` route the apps are non-functional in production.

One hostname serves both apps. The portal is built for this: its Vite `base`,
its router `basename` and its PWA scope are all `/portal/`, and the two apps keep
their tokens under different localStorage keys (`rms-admin-token` /
`rms-portal-token`) so they coexist on one origin. Section 6 covers splitting
them onto separate hostnames instead, and what that buys.

---

## 1. Prerequisites

- Node.js 20+ (dev used v22), npm 10+
- **MySQL 8.0** (production). Note: local dev runs **MariaDB 10.4** — all
  migrations apply cleanly on both, but run step 4 against a **staging MySQL 8**
  once before the first production deploy to be certain.
- A reverse proxy (nginx or Caddy) terminating TLS.
- A process manager for the API (systemd, pm2, or a container).

## 2. Configuration

```bash
cp .env.example .env          # never commit .env
```

Fill in `.env`:

- `NODE_ENV=production`
- `DATABASE_URL="mysql://user:password@host:3306/rms"`
- `JWT_ACCESS_SECRET` / `JWT_REFRESH_SECRET` — strong, ≥32 chars, **different**.
  Generate each: `node -e "console.log(require('crypto').randomBytes(48).toString('base64url'))"`
- `CORS_ORIGIN=https://rms.example.hk` — the origin(s) serving the SPAs. On a
  single hostname that is one value; add the second hostname if you split them.
- `STORAGE_LOCAL_ROOT=/var/lib/rms` — **absolute path outside the repo**, on a
  backed-up volume (uploads land in `<root>/uploads`).

The API **refuses to boot** in production with weak/default secrets or a missing
`CORS_ORIGIN` — this is intentional. Business config (rates, charge types, due
days, approval rules, notification templates) is **not** here; it lives in the
database and is edited at runtime.

## 3. Install & build

```bash
npm ci
npx playwright install --with-deps chromium   # see below — npm ci does NOT do this
npm run build            # turbo builds domain, api, admin, portal
```

Outputs: `apps/api/dist/` (Node server), `apps/admin/dist/` + `apps/portal/dist/`
(static SPAs).

**The user manual rides along in `apps/api/dist/`.** The back office serves it
from `GET /api/manual` — behind login, because its screenshots show the real
landlord companies and their accounting codes, so it must never be a static file
under the SPA root. `npm run build -w @rms/api` runs `scripts/copy-manual.mjs`
after `nest build`, which copies `docs/user-manual.html` to
`apps/api/dist/user-manual.html` and **fails the build if it is not there** —
deploy `apps/api/dist/` as a whole and the manual travels with it.

If the sidebar's **使用手冊 / User manual** entry reports *"The user manual was
not deployed with this server"*:

```bash
ls -l apps/api/dist/user-manual.html      # on the host — ~7.6 MB
node docs/manual-src/build.mjs            # rebuild it from docs/manual-src/
npm run build -w @rms/api                 # then re-run the build and redeploy
```

A 401 instead means the browser sent no valid session; a 403 means the login is
either a tenant account — the portal's, not the back office's — or one still on
a password somebody else chose, the same two lines every back-office procedure
draws. No permission gates it: a read-only role reads the manual like everyone.

Every open transfers the whole 7.6 MB. The response is `private, no-store` on
purpose: a document naming the real landlord companies should not be left in the
disk cache of a shared office PC. On the office LAN that is invisible; from
outside it is a few seconds per click.

**The browser is a separate install.** `playwright` has no postinstall, so
`npm ci` lands the JS wrapper with no browser behind it. The API boots, answers
health, and serves every screen — then the first debit note anybody prints fails
with *"The PDF renderer is not available on this server"*. On Debian/Ubuntu
`--with-deps` also pulls the shared libraries Chromium needs.

Alternatively point at a browser the host already has, and skip the download:
`PDF_BROWSER_CHANNEL=chrome` (or `msedge`), or `PDF_BROWSER_EXECUTABLE=/path/to/chrome`.

`scripts/deploy-uat.sh` does this for you: it installs Chromium unless `.env`
names a browser, and fails the deploy if readiness comes back `pdfRenderer:
missing`.

## 4. Database

```bash
cd apps/api
npx prisma migrate deploy         # applies all migrations in order (idempotent)
npm run prisma:seed               # first deploy only — creates org, roles, chart of
                                  # accounts, charge types, reference data, sample tenant
```

`migrate deploy` and the seed need dev dependencies (prisma CLI, ts-node), so run
this from a full `npm ci` checkout, not a `--omit=dev` install.

**Upgrading an existing database is `migrate deploy` and nothing else.** A release
that needs new permissions, role grants or reference data ships them in a
migration, precisely so the seed stays first-deploy-only. Never re-run the seed to
pick up a feature: it rewrites the permission grants of ADMIN, STAFF, LEASING and
ACCOUNTING, discarding whatever an administrator has tuned since.

> ⚠️ Never edit an already-applied migration — add a new one. Two migrations in
> history were hand-authored; they apply cleanly from scratch but a re-edit would
> break checksum validation on an environment that already ran them.

> ⚠️ `20261021100000_property_purchases` drops `leases.propertyId`: a lease now
> reaches its property (company, letterhead, standard charges) through its units,
> so a lease with no unit loses the only link it had. Before deploying it, this
> must return 0 — give any lease it finds a unit first:
> `select count(*) from leases l where not exists (select 1 from lease_units lu where lu.leaseId = l.id);`

### Loading the office's master data into a new database

The back office exports its standing records — landlords, properties and units,
tenants, leases with their units and charges, and the option lists and charge
types they use — as one Excel file (Settings → 主檔資料 → 匯出 Excel). A new
database is loaded from that file after the seed:

```bash
cd apps/api
npm run import:master-data -- /path/to/主檔資料.xlsx --check   # checks, writes nothing
npm run import:master-data -- /path/to/主檔資料.xlsx           # loads it
```

It only loads into an organisation with no properties and no leases (the seed's
demo tenant is fine, and is reused), checks the whole file first and writes
nothing while anything in it is wrong — each problem is listed by sheet, row and
column. Each record is then made through the same calls the back office's own
screens use, so codes and numbers are checked and assigned as if keyed in. An
account code the chart lacks is added, named by its code, until the ERP's chart
is imported over it. What the file names but does not carry must exist first:
the collection bank accounts its leases pay into. Debit notes, receipts,
deposits and readings are not in the file. The writes are not one transaction:
if one fails part-way (a database error, not a problem in the file), start again
from a fresh database.

**Set the seeded passwords rather than changing them afterwards.** `seed.ts`
refuses to run in production unless `SEED_ADMIN_PASSWORD` and
`SEED_TENANT_PASSWORD` are given, so pass them:

```bash
SEED_ADMIN_PASSWORD="$(openssl rand -hex 12)" SEED_TENANT_PASSWORD="$(openssl rand -hex 12)" npm run db:seed
```

`scripts/setup-uat-host.sh` already does exactly this and writes both into a
mode-600 credentials file. The old advice — sign in and change them through the
Users screen — was worse than useless: that screen needs `role.update`, which
most logins do not hold.

Everyone can now change their own password from the key icon (admin, top right)
or the key button (portal, beside sign-out). A password an administrator sets
for somebody else is a **one-time credential**: the account is held at a change
screen until it is replaced, because whoever typed it knows it.

There is **no forgotten-password self-service**, deliberately. Nothing in this
system can deliver an email yet (§8), so a "check your inbox" link would go
nowhere. Recovery is: the office resets the password from the Users screen, and
the holder is made to choose their own at the next sign-in. Both login screens
say so.

## 5. Run the API

```bash
cd apps/api && node dist/main.js         # listens on API_PORT (default 3000)
```

Put it under a process manager with restart-on-failure. Health endpoints for
orchestration:

- Liveness: `GET /api/health` → 200
- Readiness: `GET /api/health/ready` → **200** when DB up, **503** when down

Readiness also reports `"pdfRenderer"`. It is `"missing"` when no browser is
installed — the API still serves every screen, and only printing a debit note
fails, so this is the one place a deploy can notice before a tenant does. See
§3 for the install.

The API sets `trust proxy` so per-IP rate limits see the real client IP behind
the proxy.

**Only `POST /api/auth/login` and `/api/auth/refresh` are actually rate-limited**,
at 5/min each in production. ThrottlerGuard is an APP_GUARD, and Nest runs guards
only for controller-resolved requests — tRPC, uploads and documents are mounted
with `app.use` and never reach one. The `THROTTLE_*` env vars configure a guard
those routes bypass. If you need a ceiling on the whole API, put it in the
reverse proxy (nginx `limit_req`), which is where it belongs anyway.

## 6. Reverse proxy (serves the SPAs + routes /api)

Lay the two builds out as one tree, the portal inside the admin root:

```
/var/www/rms/            ← apps/admin/dist
/var/www/rms/portal/     ← apps/portal/dist
```

Then one `root`, one certificate, one server block:

```nginx
server {
  listen 443 ssl;
  server_name rms.example.hk;
  # ... ssl_certificate ... ;

  root /var/www/rms;

  location /api/ {
    proxy_pass http://127.0.0.1:3000;   # keeps the /api prefix
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    client_max_body_size 12m;           # attachment uploads are capped at 10MB
  }

  location /portal/ {
    try_files $uri /portal/index.html;  # tenant portal SPA fallback
  }

  location / {
    try_files $uri /index.html;         # back-office SPA fallback
  }
}
```

nginx picks the **longest** matching prefix, so `/portal/` wins over `/` wherever
it sits in the file — order does not matter here. Nesting the portal under the
admin root is what keeps this to a single `root`; serving it from a directory of
its own needs `alias`, whose interaction with `try_files` is a well-known trap.

### Splitting them onto separate hostnames

Serve `apps/admin/dist` from `admin.example.hk` and `apps/portal/dist` from
`portal.example.hk`, each with the same `/api/` block, and list both in
`CORS_ORIGIN`. No application change is needed — `/portal/` works as a path or as
a document root.

What it buys: separate origins, so a cross-site scripting flaw in the portal
cannot read a back-office token out of localStorage. The portal takes tenant
input (uploads, notes), which makes it the wider attack surface of the two.
What it costs: a second certificate, a second DNS record and a second server
block. The API itself does not care — it already refuses a tenant login every
back-office procedure regardless of where the request came from, so a stolen
tenant token is worth nothing either way; the exposure is a staff token taken
from a browser that had both apps open.

## 7. Storage & backups

- Uploaded attachments live under `STORAGE_LOCAL_ROOT/uploads` on the API host's
  local disk — **single node only**. For multiple API instances, put this on
  shared storage (NFS) or implement the `s3` driver.
- Back up: the **MySQL database** (source of financial truth) and the **uploads
  directory** (attachments are not in the DB).

## 8. Notifications (before going live)

Notification delivery currently uses the **log channel** (writes to the API log)
— the whole event → template → outbox pipeline works, but nothing is actually
emailed/SMSed yet. The outbox records these as **SKIPPED**, not SENT, with the
reason beside them: staff cite that log in payment disputes, so it must not
claim a tenant was told something they were not. A provider returning
`delivered: true` is what turns those rows into SENT. Wire a real provider in
`apps/api/src/notifications/channel.dispatcher.ts` (same `send()` signature) when
ready. Templates and recipients are already editable in the admin **Notifications**
page. `REDIS_*` env vars are reserved for a future async queue and unused today.

## 7a. Scheduled jobs

Three cron jobs run inside the API process. There is no separate worker.

| When | Job | What it does |
|---|---|---|
| 01:00 daily | `daily-lease-transition` | Ends leases past their term, activates renewals that have reached their start date, carries deposits over to the renewal |
| 02:00 on the 1st | `monthly-billing-run` | Creates a DRAFT debit note for every ACTIVE lease with no non-void note for that month. **Drafts only — nothing is issued or posted.** |
| 09:00 daily | `scheduled-invoice-issue` | Issues the notes whose scheduled send date has arrived |

**Pin the host timezone.** Only `scheduled-invoice-issue` names one
(`Asia/Hong_Kong`); the other two fire on the host clock, so a UTC host runs the
monthly job at 10:00 Hong Kong on the 1st and the transition at 09:00. Set
`TZ=Asia/Hong_Kong` in the service environment and all three agree.

The monthly run means **staff usually find the month's drafts already waiting**
rather than pressing "Run drafts". Pressing it anyway is harmless — a lease that
already has a note for the period is skipped.

## 8a. The smoke suite

```bash
npm run smoke                 # all of them, one at a time
npm run smoke -w @rms/api -- deposit    # only files matching "deposit"
```

These are the project's test suite — they carry far more of its behaviour than
the unit tests do, and they run against a **live database**, seeding and purging
their own `ZZ`-prefixed fixtures. `scripts/deploy-uat.sh` runs them after
migrating and fails the deploy if any is not green; set `RMS_DEPLOY_SMOKE=0` to
skip that on a host whose database is shared with anything you care about.

The script builds the admin and portal into `apps/<app>/dist.next` and only
swaps them in for `dist` once the restarted API answers readiness, so a failed
smoke or an API that will not start leaves the screens on the previous build.
The build it replaced is kept as `dist.prev`; to go back to it:

```bash
cd apps/admin && mv dist dist.bad && mv dist.prev dist    # same for apps/portal
```

## 9. Post-deploy smoke check

```bash
curl https://rms.example.hk/api/health             # {"status":"ok",...}
curl -sI https://rms.example.hk/portal/ | head -1  # 200 — the portal's own index, not the admin's
# log in to the admin app, confirm the dashboard loads and a draft invoice can be issued
# log in at /portal/ with a tenant account — a back-office account is refused there,
#   and a tenant account is refused in the back office
# from a phone, add /portal/ to the home screen (PWA icon should be the RMS mark)
```
