# Deploying Tempest Pulse to Vercel

> **Current deployment:** https://tempest-pulse.vercel.app — Vercel team *Brand Tempest* (Hobby plan), project `tempest-pulse`, Neon Postgres `tempest-pulse-db` in ap-southeast-1 (Singapore) connected through the Vercel Marketplace. Because Hobby only allows daily crons, `vercel.json` runs both crons daily; add an external every-minute ping to `/api/cron/worker` (see §5) or upgrade to Pro and set the worker back to `* * * * *`.

Tempest Pulse is a single Next.js 15 app (UI + REST API + background workers) on PostgreSQL. It runs on Vercel out of the box; any Node 20+ host with Postgres works the same way (`npm run build && npm start`, plus a scheduler hitting the two cron URLs).

## 1. Create the database

Use any managed Postgres 14+ (recommended: **Neon**, region *Singapore* for Bangladesh latency; Supabase or AWS RDS also work).

1. Create a database and copy the **pooled** connection string (Neon: “Pooled connection”).
2. That string becomes `DATABASE_URL`.

Migrations run automatically during the Vercel build (`npm run vercel-build` → `scripts/migrate.ts`). To run them manually: `DATABASE_URL=… npm run db:migrate`.

## 2. Push the code and import into Vercel

1. Put this folder in a Git repository (GitHub/GitLab/Bitbucket) and push.
2. Vercel → **Add New Project** → import the repo. Framework is detected as Next.js; `vercel.json` already sets the build command, the Singapore region (`sin1`) and the two cron jobs.

## 3. Environment variables

Copy every key from `.env.example` into Vercel → Project → Settings → Environment Variables. Minimum for go-live:

| Variable | Value |
|---|---|
| `DATABASE_URL` | pooled Postgres URL |
| `APP_URL` | `https://<your-domain>` (no trailing slash) |
| `AUTH_SECRET` | `openssl rand -base64 32` |
| `ENCRYPTION_KEY` | `openssl rand -hex 32` — **never rotate after go-live** (encrypted tokens depend on it) |
| `CRON_SECRET` | `openssl rand -hex 24` |
| `SEED_DEMO` | `false` in production |

Optional now, required for each live integration: `ANTHROPIC_API_KEY`, `META_APP_ID/SECRET`, `GOOGLE_CLIENT_ID/SECRET`, `GOOGLE_ADS_DEVELOPER_TOKEN`, `STRIPE_WEBHOOK_SECRET`, Turnstile keys.

## 4. First run

Deploy, then open `https://<your-domain>/setup` and create the agency, first client workspace and your admin account (set `SETUP_TOKEN` to require a token on that form). Alternatively set `SEED_ADMIN_EMAIL` / `SEED_ADMIN_PASSWORD` before the first request.

Then in the app: **Settings → Profile & security** → enable MFA; **Settings → Team** → invite people; **Integrations** → connect providers.

## 5. Background jobs (Vercel Cron)

`vercel.json` schedules:

| Path | Schedule | Does |
|---|---|---|
| `/api/cron/worker` | every minute | drains the job queue (webhooks, conversion sync, journeys, broadcasts, calendar), resumes waiting journeys, SLA checks, scheduled publishing, segment counts |
| `/api/cron/daily` | 01:00 UTC (07:00 Dhaka) | ad metric sync, anomaly & pacing alerts, date-based journeys, scheduled report emails, post metrics, weekly scoring retrain, monthly invoices, retention cleanup |

> **Plan note:** Vercel Hobby only allows daily crons. On Hobby, change the worker schedule to daily *and* point a free external scheduler (e.g. cron-job.org, GitHub Actions) at `https://<domain>/api/cron/worker` every minute with header `Authorization: Bearer <CRON_SECRET>`. On Pro, the per-minute cron works as configured. Jobs also run opportunistically right after each API request, so the app stays responsive either way.

## 6. Domains

* **App domain:** Vercel → Domains → add `app.yourdomain.com`; set `APP_URL` to it.
* **White-label login domains** (agencies): add the domain in Vercel and list it in `EXTRA_APP_HOSTS`.
* **Landing-page custom domains (PAGE-004):** in the page’s *Tracking & domain* tab enter the domain, add it in Vercel → Domains, and point a CNAME to `cname.vercel-dns.com`. SSL is issued automatically. Any host that isn’t an app host is served the landing page attached to it.

## 7. Provider setup (start these on day 1 — BRD §15 risk)

### Meta (Lead Ads, Insights, CAPI, WhatsApp, Messenger, publishing)
1. developers.facebook.com → create a **Business** app; add products *Facebook Login for Business*, *Webhooks*, *Marketing API*, *WhatsApp*.
2. OAuth redirect URI: `https://<domain>/api/v1/integrations/oauth/callback`.
3. Request advanced access / App Review for: `ads_read`, `ads_management`, `leads_retrieval`, `pages_manage_metadata`, `pages_read_engagement`, `pages_manage_posts`, `instagram_basic`, `instagram_content_publish`, `business_management`, `whatsapp_business_messaging`.
4. Webhooks: callback `https://<domain>/api/v1/hooks/<workspace key>/meta` (WhatsApp: `/whatsapp`), verify token = workspace key (Settings → General) or `META_VERIFY_TOKEN`. Subscribe Page → `leadgen`, WhatsApp → `messages`.
5. Set `META_APP_ID`, `META_APP_SECRET`. While testing CAPI set `META_TEST_EVENT_CODE`.
6. **Social inbox (Module 11)** — one app-level webhook for every workspace: callback `https://<domain>/api/meta/webhook`, verify token = `META_VERIFY_TOKEN` (required), signatures checked with `META_APP_SECRET` (required in production). Subscribe **Page** → `feed`, `messages`, `messaging_postbacks`, `leadgen`; **Instagram** → `comments`, `mentions`, `messages`; **WhatsApp Business Account** → `messages`. Events are routed to the workspace(s) that activated the page / IG account in *Settings → Social inbox*. Extra App Review permissions (VERIFY current names in Meta's docs): `pages_read_user_content`, `pages_manage_engagement`, `pages_messaging`, `instagram_manage_comments`, `instagram_manage_messages`. Private replies: one per comment within `META_PRIVATE_REPLY_DAYS` (default 7).

### YouTube & Google Business Profile (social inbox)
* Enable **YouTube Data API v3** (scope `youtube.force-ssl`) and the **Business Profile APIs** (Account Management, Business Information and the v4 reviews endpoint — scope `business.manage`; access is granted by Google on request). Both reuse `GOOGLE_CLIENT_ID/SECRET`. They have no webhooks: comments and reviews are polled every `SOCIAL_POLL_MINUTES` (default 5) by the worker cron. On the Vercel Hobby plan crons run once a day, so use Pro (or an external scheduler calling `/api/cron/worker` with `Authorization: Bearer $CRON_SECRET`) for near-real-time polling and SLA checks.
* TikTok and LinkedIn comments are behind feature flags (*Settings → Social inbox → Accounts*) until their partner APIs are approved.
* Add the social demo to an existing workspace: `npx tsx scripts/seed-social.ts` (idempotent; set `SEED_WORKSPACE_SLUG` to pick one).

### Google (SSO, Ads, GA4, Search Console, Calendar)
1. Google Cloud console → OAuth client (Web). Redirect URIs: `https://<domain>/api/auth/google-callback` and `https://<domain>/api/v1/integrations/oauth/callback`.
2. Enable APIs: Google Ads API, Analytics Data API, Search Console API, Calendar API.
3. Apply for a **Google Ads developer token** (Basic access) → `GOOGLE_ADS_DEVELOPER_TOKEN`.
4. Create conversion actions (Qualified, Site visit, Won) of type *Import → CRM / offline* and paste their IDs into the Google Ads integration settings.
5. Lead form assets → webhook URL `https://<domain>/api/v1/hooks/<workspace key>/google` with the key set on the integration.

### Messaging & payments
* **WhatsApp:** phone number ID, WABA ID and a permanent system-user token in the WhatsApp integration.
* **Email:** SES (configuration set → SNS → `/hooks/<key>/ses`) or SendGrid (Event Webhook → `/hooks/<key>/sendgrid`). Verify your sending domain (SPF/DKIM/DMARC).
* **SMS (Bangladesh):** any HTTP gateway — set the send URL template with `{to} {message} {sender} {apiKey} {type}`; delivery reports → `/hooks/<key>/sms`. Twilio for US/AU.
* **Payments:** Stripe (webhook → `/hooks/<agency workspace key>/stripe`), SSLCommerz (IPN → `/sslcommerz`), bKash (callback → `/bkash`). Connect them on the agency’s first workspace.

Until approvals land, connect each provider in **Sandbox** mode to test the full flow.

### Subscriptions, sign-up and the AI assistant
* **Subscriptions (Stripe):** set `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET`; add a webhook endpoint at `https://<app domain>/api/billing/stripe` for `checkout.session.completed`, `customer.subscription.created/updated/deleted`, `invoice.paid`, `invoice.payment_failed`. Prices are sent inline (Starter $50, Growth $100, Enterprise $250 / month), so nothing needs creating in Stripe. Enable the Customer Portal in Stripe for "Manage billing". Without the keys, new workspaces still get the 14-day trial and Plan & billing shows "payments not switched on".
* **Self-serve sign-up** (`/signup`) verifies the email *and* the mobile number with one-time codes. In production it needs the email and/or SMS provider from "Security codes" below — with neither configured, sign-up returns "temporarily unavailable". Forgot-password (`/forgot-password`) uses the same providers.
* **AI assistant** ("Ask AI", text on every plan, voice from Growth) uses `ANTHROPIC_API_KEY` and the workspace's AI credits. Without a key it answers from the built-in product guide only. Voice uses the browser's speech recognition (Chrome, Edge, Safari) — no extra service.
* After migrating an existing database, set your own workspace to Enterprise: `UPDATE workspaces SET plan='enterprise', subscription_status='active' WHERE id='<id>';`

### Security codes (two-factor by email/SMS, sign-in alerts)
* Email: set `RESEND_API_KEY` or `SENDGRID_API_KEY` and `SECURITY_EMAIL_FROM` (a verified sender). SMS: `TWILIO_ACCOUNT_SID/AUTH_TOKEN/FROM`, or `SECURITY_SMS_URL` for a local gateway (`{to}`, `{message}`). Without these, email/SMS two-factor falls back to a live email/SMS integration in the user's workspace; if there is none, those two methods are unavailable and users choose a passkey or authenticator app.
* Passkeys need HTTPS and must be used on the same domain they were created on (custom white-label domains each get their own passkeys).

## 8. Go-live checklist

- [ ] Stripe keys + webhook set, email/SMS provider set (sign-up), `ANTHROPIC_API_KEY` set (assistant)
- [ ] `SEED_DEMO=false`, strong `AUTH_SECRET`, `ENCRYPTION_KEY`, `CRON_SECRET` set
- [ ] `/setup` completed (or seed admin) and MFA enforced for admins
- [ ] Cron jobs visible in Vercel → Settings → Cron Jobs and returning 200
- [ ] Meta & Google connected in **live** mode; a test lead from each source lands in Contacts with attribution
- [ ] Move a test deal to Qualified/Won → events visible in Meta Events Manager (Test Events) and Google Ads conversions
- [ ] WhatsApp template approved and sends; inbound replies appear in Inbox
- [ ] Email domain authenticated; bounce webhook connected
- [ ] Quiet hours / frequency caps reviewed in Settings → General
- [ ] Backups: enable PITR on your Postgres (Neon: history retention ≥ 7 days) — BRD NFR-009
- [ ] Status/uptime monitor on `/api/v1/openapi.json` and `/login`

## 9. Operations

* **Logs:** Vercel → Logs. Integration calls are also logged per connection (Integrations → Manage → Health log).
* **Dead-letter queue:** Settings → Privacy & data → replay jobs after fixing the cause.
* **Database migrations:** edit `src/db/schema.ts` → `npm run db:generate` → commit the new SQL in `/drizzle` → deploy.
* **Hardening option (NFR-001):** in addition to the application-level workspace scoping and isolation tests, you can enable Postgres row-level security by connecting as a non-owner role and setting `app.workspace_id` per transaction; the schema already carries `workspace_id` on every tenant table.
