# Deploying

Servers run under **PM2**, not Docker, the same way as `business-mcp`.
TLS and the public hostname are handled by nginx. The API listens on `127.0.0.1`.

**Commands are not environment-specific.** Put `NODE_ENV`, ports, secrets, and PM2 names in
repo-root `.env`, then always run:

```sh
npm run deploy
# same as: sh deploy/deploy.sh
```

That script: `git pull` → `npm ci` → `npm run build` → `npm run db:deploy` → `pm2 startOrReload deploy/ecosystem.config.cjs` → `pm2 save`.

One `.env` per server (dev / staging / production). Do not commit it.

## First time

```sh
ssh -i ~/.ssh/devgroup_id_rsa devgroup@192.168.30.106
cd /var/www/dev.lucos.com
git clone <repo-url> api.internal-crm && cd api.internal-crm

cp .env.example .env          # set NODE_ENV, DATABASE_URL, API_PORT (pick a free port)
                              # with DEV_AUTH_ENABLED=true also set DEV_AUTH_SECRET (16+ chars)
                              # set SECRETS_ENCRYPTION_KEY to a new `openssl rand -base64 32` and
                              # keep a copy: stored Google tokens can't be read without it
                              # optional: PM2_API_NAME / PM2_WORKER_NAME if several envs share a host

npm run deploy
```

Create one database (`utf8mb4`) and one MySQL user for it on the host MySQL 5.7 before the first deploy. All businesses share this database.

Default PM2 names: `crm-api`, `crm-worker` (unchanged from earlier staging).

### Email attachments (HUB-168)

Files uploaded to attach to an email wait on this server's disk until they are sent (at most a
day; the worker deletes the rest every hour).

- `EMAIL_UPLOAD_DIR` in `.env`: a folder outside the web root, writable by the PM2 user, with a few
  GB free (each user may have up to 250 MB waiting). The API and the worker must see the same
  folder, so they must run on the same machine. Default: `var/email-uploads` inside the repo.
- The nginx proxy must accept uploads up to 25 MB: `client_max_body_size 26m;` for this API's
  host (the default 1 MB refuses attachments before they reach the API).

### Google Calendar (HUB-173, HUB-174)

Users connect their Google Calendar with the same Google app as Gmail. Once, in the Google Cloud
project of that app:

- Enable the **Google Calendar API**.
- Add the scopes `https://www.googleapis.com/auth/calendar.readonly` (sync) and
  `https://www.googleapis.com/auth/calendar.events` (meetings created from the CRM, HUB-174) to
  the OAuth consent screen.
- Add `${API_URL}/api/v1/calendars/google/callback` to the app's authorized redirect URIs (next to
  the Gmail one).

No new `.env` setting: it uses `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `API_URL` and `APP_URL`.

### Import CSV files (HUB-178/179/180)

Uploaded import CSV files are kept on disk until they expire (30 days), then removed by the worker.

- `IMPORT_UPLOAD_DIR` in `.env`: a folder outside the web root, writable by the PM2 user, with
  enough free space for pending imports. The API and the worker must point at the same folder.
  Default: `var/import-uploads` inside the repo.

### CSV exports (HUB-219)

The worker writes each export to disk; users download it through the API for 7 days, then the
worker deletes the file (hourly) and keeps the history row.

- `EXPORT_DIR` in `.env`: a folder outside the web root, writable by the PM2 user. An export has
  at most 200,000 rows (usually well under 100 MB). The API and the worker must point at the same
  folder, so they must run on the same machine. Default: `var/exports` inside the repo.

### Forms and booking pages on the company website (HUB-82)

A form or booking page embedded on another site calls this API from the visitor's browser, which
needs CORS. Only the public endpoints get it (`GET /api/v1/forms/:id/public`,
`POST /api/v1/forms/:id/submit` and `/api/v1/book/*`), never with cookies.

- `PUBLIC_CORS_ORIGINS` in `.env`: the website origins allowed to call them, comma-separated, e.g.
  `https://www.admedia.com,https://admedia.com` (scheme and host, no path or trailing slash).
  Unset means no CORS, so only same-origin pages (or server-side calls) can use them.
- If nginx adds its own `Access-Control-*` headers for this host, remove them: the API sends them.

### Email open and click tracking (HUB-170)

Each business that wants tracking gets its own tracking host, e.g. `t.acme.com`. Per host, IT:

- adds a DNS CNAME from the host to the API's public host name;
- adds a TLS certificate for the host on the nginx proxy (the pixel and links are `https://`);
- forwards `https://<host>/o/*` and `https://<host>/c/*` to the API, keeping the path.

Then an admin sets the host and switches tracking on in the business settings
(`PATCH /api/v1/business/settings` with `trackingDomain` and `trackingEnabled`).

`TRACKING_COUNTRY_HEADER` in `.env` (optional): the header the proxy puts the visitor's country in,
e.g. `cf-ipcountry` behind Cloudflare. Without it, opens and clicks are stored without a country.
No IP address is stored. Tokens are signed with a key derived from `SECRETS_ENCRYPTION_KEY`.

### Unsubscribe links (HUB-171)

Emails with an unsubscribe link point at `https://<API_URL host>/u/<token>`, from the email footer
and from the `List-Unsubscribe` header Gmail's own "Unsubscribe" button uses. On the proxy:

- forward `https://<API_URL host>/u/*` to the API, keeping the path, for anyone (no sign-in, no
  IP allow-list): the people receiving the email and Google's servers call it;
- allow `POST` with a form body there (Gmail's one-click sends `List-Unsubscribe=One-Click`).

`API_URL` must be the public `https://` address. Tokens are signed with a key derived from
`SECRETS_ENCRYPTION_KEY`; changing that key stops older unsubscribe links from working. The
footer shows the business's postal address from the business settings (left out until it is set).

### Workflow notifications: internal email and Slack (HUB-209)

Internal emails from workflows go out through the CRM's own SMTP sender (any provider, e.g.
ZeptoMail), never through a person's Gmail. In the worker's `.env`:

- `SYSTEM_EMAIL_SMTP_URL`: e.g. `smtps://<user>:<password>@smtp.zeptomail.com:465` (a secret);
- `SYSTEM_EMAIL_FROM`: e.g. `AdMedia CRM <crm@admedia.com>` (a verified sender domain);
- `APP_URL`: the frontend address, for the link to the record in emails and Slack messages.

Without the SMTP settings, internal email steps fail with a clear error (the rest works).

Slack: create a Slack app for the workspace with the bot scopes `chat:write`, `channels:read`,
`groups:read`, `users:read` and `users:read.email`, install it, and have an admin send its Bot
User OAuth Token to `PUT /api/v1/integrations/slack` (it is stored encrypted with
`SECRETS_ENCRYPTION_KEY`, never shown again). Invite the app to private channels it should post
in. `POST /api/v1/integrations/slack/test` posts a test message.

## Every deploy

```sh
cd /var/www/dev.lucos.com/api.internal-crm && npm run deploy
```

This pulls, installs, builds, runs `prisma migrate deploy` and reloads PM2 (`crm-api` / `crm-worker` by default; names from `.env` if set).

After deploying the phone-normalized search migration for the first time (HUB-110), run one
backfill to populate existing rows:

```sh
cd /var/www/dev.lucos.com/api.internal-crm && npm run db:backfill:phone-normalized
```

After deploying the owner-field access migration for the first time (P2b,
`20261222100000_record_owner_field_users`), run one backfill so contacts and companies whose
owner-type custom fields already name someone count as theirs. Until it runs, those fields give no
access (nothing is widened early). It is safe to run again:

```sh
cd /var/www/dev.lucos.com/api.internal-crm && npm run db:backfill:owner-field-users
```

## Checking it

```sh
pm2 status
pm2 logs crm-api --lines 100
curl http://127.0.0.1:<API_PORT>/healthz   # process is up, shows the deployed commit
curl http://127.0.0.1:<API_PORT>/readyz    # database is reachable
```

## Adding a business (HUB-64)

No new deployment is needed. A business is data inside the same database. On the server, in the repo folder:

```sh
npm run business:create -- --name "AdMedia" --slug admedia --timezone America/Los_Angeles   --admin-email first.admin@admedia.com [--admin-name "First Admin"] [--currency USD]
```

It creates the business with its default permission sets, dropdowns and pipelines, and makes the email its
admin (Super Admin). The admin then signs in with Google; their email domain must be in `ALLOWED_GOOGLE_DOMAINS`
(the command warns when it isn't). Safe to run again: an existing business is never changed, and an admin is
only added while the business has none. Use this for the first business on staging and production too
(`npm run db:seed` is for local dev data only).

To suspend a business (its people can no longer sign in or use it, its background jobs are skipped, and its
open sessions end; the data is kept) and to make it active again:

```sh
npm run business:suspend -- --slug admedia
npm run business:resume -- --slug admedia
```

Both are safe to run again and write an entry to the business's audit log.

## DEV / STG / PRD

Same command everywhere: `npm run deploy`. Only the server's `.env` changes
(`NODE_ENV`, `API_PORT`, secrets, optional `PM2_API_NAME` / `PM2_WORKER_NAME`).
