# Tempest Pulse — Developer Handover Guide

**Product:** Tempest Pulse (a Brand Tempest product) — CRM, marketing automation, unified inbox, ads, analytics and AI.
**Goal of this guide:** deploy the app on **your own domain** (e.g. `app.yourdomain.com`) so it is ready for real users.
**Current live copy:** https://tempest-pulse.vercel.app (Vercel + Neon Postgres, Singapore region).

> **Keys are NOT in this zip.** The production keys are delivered separately in a file called
> `TempestPulse-PRODUCTION-KEYS.env`, through a password manager or another secure channel.
> Never commit that file to Git, never paste it in chat/email, and keep it out of screenshots.

---

## 1. What you received

| Item | What it is |
|---|---|
| `src/` | The Next.js 15 app (App Router, TypeScript, Tailwind). API lives in `src/api` and is served at `/api/v1/*` |
| `drizzle/` | SQL migrations (applied automatically on every deploy by `npm run vercel-build`) |
| `scripts/` | `migrate.ts` (DB migrations), `seed.ts`, `set-industry.ts` |
| `tests/` | 58 automated tests (`npm test`, runs on an in-memory database — no setup) |
| `docs/` | BRD, Product Blueprint, `DEPLOYMENT.md` (provider details), `TRACEABILITY.md` (requirement → code) |
| `.env.example` | Every environment variable, with comments |
| `.env.production.template` | The variables production needs, grouped, with the current status of each |
| `vercel.json` | Build command, region and the two daily cron jobs |

**Stack:** Node.js 20+, Next.js 15.5, PostgreSQL 15+ (Neon recommended), Drizzle ORM. No Redis or queue service needed — background work runs through the cron endpoints.

---

## 2. Run it locally first (5 minutes)

```bash
npm install
npm run dev          # http://localhost:3000 — uses an embedded database (./.data), demo data included
npm test             # 58 tests should pass
npm run build        # production build should succeed
```
Local demo login: `admin@brandtempest.com` with the `SEED_DEMO_PASSWORD` from `.env.example`. Local only — production has no demo users.

---

## 3. Decide: keep the current database, or start fresh?

| | **A. Keep the current database (recommended)** | **B. Fresh database** |
|---|---|---|
| Users, workspaces, leads, settings | Kept | Empty — first admin created at `/setup` |
| What you do | Use `DATABASE_URL`, `DATABASE_URL_UNPOOLED` from the keys file | Create a new Postgres (Neon), set its URL |
| `ENCRYPTION_KEY` | **Must be the exact same value** as today | Generate new: `openssl rand -hex 32` |
| `AUTH_SECRET`, `CRON_SECRET` | Same value (or new — new only signs everyone out) | Generate new: `openssl rand -base64 32` |

⚠️ **Never change `ENCRYPTION_KEY` on an existing database.** All connected integration tokens (Meta, Google, WhatsApp, SMS…) and two-factor secrets are encrypted with it; a different key makes them unreadable and every integration must be reconnected.

To move the data into a database you own instead: `pg_dump "$DATABASE_URL_UNPOOLED" -Fc -f tempest.dump` then `pg_restore -d "<new url>" --no-owner tempest.dump`, and keep the same `ENCRYPTION_KEY`.

---

## 4. Deploy — Option 1: Vercel (recommended, ~20 minutes)

Vercel is what the app is built and tested on: zero server work, HTTPS, crons and scaling included.

1. Put the code in a **private** Git repository (GitHub/GitLab). Do **not** commit any `.env*` file other than `.env.example` / `.env.production.template` (`.gitignore` already excludes them).
2. In Vercel → **Add New → Project** → import the repository. Framework: Next.js (auto). Build command is read from `vercel.json` (`npm run vercel-build` = migrate DB, then build).
3. **Settings → Environment Variables** → add every variable from `TempestPulse-PRODUCTION-KEYS.env` for the *Production* environment (you can paste the whole file into Vercel's import box). Set `APP_URL=https://app.yourdomain.com`.
4. **Settings → Functions** → region **Singapore (sin1)** — closest to Bangladesh and to the Neon database.
5. Deploy. The first build runs the migrations automatically.
6. **Settings → Domains** → add `app.yourdomain.com` (see section 6 for DNS).
7. Crons are created from `vercel.json` automatically; Vercel sends `CRON_SECRET` to them. On the Hobby plan crons run once a day; **use Vercel Pro** for production so `/api/cron/worker` can run every few minutes (edit the schedule in `vercel.json` to e.g. `*/5 * * * *`).

## 5. Deploy — Option 2: your own server (VPS / cPanel Node / Docker)

Works on any Linux server with Node.js 20+ (2 vCPU / 2 GB RAM minimum).

```bash
npm ci
cp TempestPulse-PRODUCTION-KEYS.env .env.production.local   # then set APP_URL to your domain
npm run vercel-build        # runs migrations + builds (the name is historical; it works anywhere)
npm start                   # serves on port 3000 — keep it running with PM2:  pm2 start npm --name tempest -- start
```
- Put **Nginx** (or Caddy) in front for HTTPS (Let's Encrypt) and proxy to `localhost:3000`. Forward the `Host` and `X-Forwarded-Proto` headers.
- **Cron jobs** (required — reminders, journeys, social polling, reports, anomaly checks):
  ```cron
  */5 * * * *  curl -fsS -H "Authorization: Bearer $CRON_SECRET" https://app.yourdomain.com/api/cron/worker
  0 1 * * *    curl -fsS -H "Authorization: Bearer $CRON_SECRET" https://app.yourdomain.com/api/cron/daily
  ```
- Shared hosting without a Node.js process (plain PHP cPanel) **cannot** run this app.

---

## 6. Your own domain

1. DNS at your registrar:
   - Vercel: `app` → **CNAME** → `cname.vercel-dns.com` (Vercel shows the exact record). Root domain: **A** → `76.76.21.21`.
   - Own server: `app` → **A** → your server IP.
2. Set `APP_URL=https://app.yourdomain.com` and redeploy. It is used in emails, OAuth redirects, webhooks, form embeds and the tracking snippet.
3. Extra white-label login domains for clients: add them in Vercel Domains and list them in `EXTRA_APP_HOSTS` (comma-separated).
4. Things that are tied to the old domain and must be updated:
   - **Google OAuth** (Google Cloud Console → Credentials → Authorized redirect URIs): `https://app.yourdomain.com/api/auth/google-callback` (Google sign-in) and `https://app.yourdomain.com/api/v1/integrations/oauth/callback` (connecting Google Ads/GA4/YouTube…).
   - **Meta app** (developers.facebook.com): App Domains = your domain; Valid OAuth Redirect URI = `https://app.yourdomain.com/api/v1/integrations/oauth/callback`; Webhooks callback = `https://app.yourdomain.com/api/meta/webhook` (verify token = `META_VERIFY_TOKEN`).
   - **Stripe** webhook endpoint → `https://app.yourdomain.com/api/billing/stripe`.
   - SMS / email provider delivery-report webhooks → new domain (see `DEPLOYMENT.md` §7).
   - **Passkeys** are bound to the domain — users who sign in with a passkey must add a new one on the new domain (they can sign in with password + their other two-factor method first). Everyone signs in again once.
   - Websites that embed forms or the tracking snippet must use the new domain.
5. Point the old `tempest-pulse.vercel.app` to redirect to the new domain once everything is verified.

---

## 7. Environment variables — what production needs

Full list with comments: `.env.example`. Status as of handover is in `.env.production.template`.

| Group | Variables | Status at handover |
|---|---|---|
| **Core (required)** | `DATABASE_URL`, `DATABASE_URL_UNPOOLED`, `APP_URL`, `AUTH_SECRET`, `ENCRYPTION_KEY`, `CRON_SECRET`, `NEXT_PUBLIC_PRODUCT_NAME`, `SEED_DEMO=false` | ✅ Set — in the keys file |
| **Payments** (subscriptions $50 / $100 / $250) | `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` | ❌ Needed — without them users get a 14-day trial but cannot pay |
| **Sign-up & password reset codes** | Email: `RESEND_API_KEY` *or* `SENDGRID_API_KEY` + `SECURITY_EMAIL_FROM`. SMS: `TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, `TWILIO_FROM` *or* `SECURITY_SMS_URL` (local BD gateway) | ❌ Needed — **self-serve sign-up is disabled until at least one is set** |
| **AI assistant & AI features** | `ANTHROPIC_API_KEY` | ❌ Needed — without it "Ask AI" only answers from the built-in guide |
| Meta (Facebook/Instagram/WhatsApp) | `META_APP_ID`, `META_APP_SECRET`, `META_VERIFY_TOKEN` | Optional until you connect Meta |
| Google (SSO, Ads, GA4, YouTube, reviews) | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GOOGLE_ADS_DEVELOPER_TOKEN` | Optional until you connect Google |
| Spam protection | `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | Recommended |

Vercel adds many `POSTGRES_*`, `PG*`, `VERCEL_*`, `TURBO_*` variables automatically — those are **not** needed on a new project.

Where each provider key comes from and which webhooks to register: `docs/DEPLOYMENT.md` §7.

---

## 8. Go-live checklist

- [ ] `npm test` and `npm run build` pass locally
- [ ] All **Core** variables set; `APP_URL` = your domain; `SEED_DEMO=false`
- [ ] Same `ENCRYPTION_KEY` as before (if keeping the database)
- [ ] Domain added, HTTPS certificate issued, `https://app.yourdomain.com/login` loads
- [ ] Crons running (Vercel → Cron Jobs shows runs, or server crontab installed)
- [ ] Stripe keys + webhook set → test a subscription with a Stripe test card in test mode first
- [ ] Email and/or SMS provider set → `/signup` sends both codes; `/forgot-password` works
- [ ] `ANTHROPIC_API_KEY` set → "Ask AI" answers "How am I doing this month?" with real numbers
- [ ] Google / Meta redirect URIs and webhooks updated to the new domain
- [ ] Terms of Service and Privacy Policy text replaced (`src/app/legal/[doc]/page.tsx` — currently placeholders)
- [ ] Admin account has two-factor authentication on (Profile & security)
- [ ] Old domain redirects to the new one

## 9. Security rules for the team

- Keep the keys file in a password manager (1Password, Bitwarden) — not email, WhatsApp, Slack or Google Drive.
- After the handover is finished, **rotate** the shared secrets that can be rotated safely: database password (Neon → Roles → reset, then update `DATABASE_URL*`), `CRON_SECRET`, `AUTH_SECRET` (signs everyone out once), and any provider API keys. **Do not rotate `ENCRYPTION_KEY`.**
- Give developers their own accounts (Vercel team member, Neon member) instead of sharing logins; remove access when the work ends.
- Production database changes only through migrations in `drizzle/` (`npm run db:generate` after editing `src/db/schema.ts`). Migrations must be additive — no dropping or renaming columns that live data uses.

## 10. Where things are in the code

| Area | Path |
|---|---|
| Pages (UI) | `src/app/(app)/…` (signed-in), `src/app/login`, `signup`, `forgot-password`, `pricing` |
| API routes | `src/api/handlers/*.ts` (route table in `src/api/router.ts`), served by `src/app/api/v1/[...path]/route.ts` |
| Database schema | `src/db/schema.ts`, migrations in `drizzle/` |
| Plans & feature gating | `src/lib/plans.ts`, Stripe in `src/lib/services/subscription.ts` |
| Sign-up / reset / 2FA | `src/lib/security/*`, `src/app/api/auth/[action]/route.ts` |
| AI | `src/lib/ai/gateway.ts` (all model calls), `src/lib/ai/assistant.ts` (Ask AI) |
| Industries & dashboards | `src/lib/industry.ts`, `src/lib/dashboard.ts` |
| Theme | `src/app/globals.css`, `tailwind.config.ts`, `src/components/shell.tsx` |

Questions about requirements: every BRD requirement ID is mapped to its code in `docs/TRACEABILITY.md`.
