# Architecture

## In one picture

```
 browser / Swagger / other services
            │  HTTPS
            ▼
   nginx proxy (TLS)              ← separate machine
            │  http://127.0.0.1:<API_PORT>
            ▼
 ┌──────────────────────┐      ┌───────────────────────┐
 │ crm-api  (PM2)       │      │ crm-worker  (PM2)     │
 │ apps/api             │      │ apps/worker           │
 │ routes → services    │      │ jobs  → services      │
 └──────────┬───────────┘      └──────────┬────────────┘
            │  @crm/core services + @crm/db (Prisma)   │
            └──────────────┬───────────────────────────┘
                           ▼
     MySQL 5.7: one shared database, every row tagged with business_id
```

- **API** (`apps/api`) answers HTTP requests. It stays fast, so anything slow or external
  (Gmail sync, sending sequences, running workflows, CSV import) is handed to the worker.
- **Worker** (`apps/worker`) runs background jobs. It uses the same services as the API.
- **core** (`packages/core`) holds every business rule, so the API and the worker behave the same.
- **db** (`packages/db`) is the only place that knows about Prisma and the schema.
- **shared** (`packages/shared`) holds the request and response contracts. Swagger/OpenAPI is generated from them.
- **Frontend** is a separate repo. It calls this API over HTTP and can generate its types from `/docs/json`.

## A request, step by step

1. nginx forwards `POST /api/v1/contacts`. Fastify gives it a request id, or reuses `x-request-id`.
2. The Zod schema on the route validates the body. Bad input returns `400 VALIDATION_ERROR` with field details.
3. The route builds `ctx` (request id, logger, and after login the signed-in user and their current business) and calls `contactsService.create(ctx, body)`.
4. The service checks permissions and rules, writes through Prisma and returns plain data.
5. Fastify serializes the response against the response schema, so extra fields never leak.
6. Any thrown `AppError` becomes the standard error body. Unknown errors are logged and returned as `500 INTERNAL_ERROR`.

## Multiple businesses (HUB-64)

All businesses share **one deployment and one database**. HubSpot already works this way for AdMedia today:
one account, split by a "Business Unit" field.

- Every table that holds business data has a `business_id` column.
- `scopedDb(ctx.businessId)` in `@crm/db` adds the business to every read, update and delete, and checks it on
  every create, so a service cannot forget it.
- Users can belong to several businesses (`memberships`: user, business, role) and switch between them.
  The API checks the current business against the user's memberships on every request (`authService.resolveIdentity`).
  It never trusts a business id sent by the browser on its own. Until Google login (HUB-81), local and staging
  use dev login headers (`x-dev-user`, `x-dev-business`), which are refused in production.
- Public links (forms, booking pages, email tracking, Google callbacks) find their business from the link's own record.
- Background jobs carry `business_id`. The worker runs each job scoped to that business and skips jobs of a
  suspended business.
- Automated isolation tests try to read and write another business's data, and they run with every change.
- Adding a business is one command: create the business, seed default pipelines and properties, invite the admin.
  Suspending a business blocks its logins and jobs. Retiring it means exporting its rows, then deleting them.

If a business ever needs physical separation, the same code can run as its own copy with its own database.

## Key decisions

| Decision                    | Why                                                                                                                          |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| MySQL 5.7                   | Staging and production run it, and changing it will not be approved                                                          |
| Prisma 6                    | Typed queries and migrations. Raw SQL via `$queryRaw` where needed                                                           |
| Fastify + Zod               | Fast, with validation and Swagger from one schema                                                                            |
| npm workspaces monorepo     | npm is the organisation standard. API and worker share code without publishing packages                                      |
| PM2, not Docker, on servers | Matches how the company already runs Node apps (`business-mcp`)                                                              |
| UUIDv7 ids                  | Safe to generate anywhere, sortable by time, no id guessing                                                                  |
| Cursor pagination           | Stable pages on large tables (~55k contacts)                                                                                 |
| One shared DB + business_id | One deploy and migration for all businesses; users can work across businesses                                                |
| Custom fields as JSON       | A `custom_properties` JSON column plus a definitions table. Simpler than a value table per type, and fast enough at our size |
