# Rules for this repo

Read by developers and by AI coding assistants (Claude Code reads it through `CLAUDE.md`).
Keep it short. If a rule changes, change it here in the same PR.

## Stack (decided, do not re-open)

- Node 20.19, TypeScript (strict), ESM, npm workspaces (the organisation standard; do not add pnpm or yarn files)
- Backend only. The frontend is a separate repo and uses this API through its OpenAPI spec (`/docs/json`).
- Fastify 5 + Zod 4 (`fastify-type-provider-zod`). Swagger is generated from the Zod schemas.
- Prisma 6 on **MySQL 5.7**, the version on staging and production
- PM2 on the company servers. Docker is used only for the local database.

## Layers

| Layer    | Where                                              | Does                                                             | Must not                                      |
| -------- | -------------------------------------------------- | ---------------------------------------------------------------- | --------------------------------------------- |
| Contract | `packages/shared/src/<module>.ts`                  | Zod schemas and types for requests and responses                 | import anything except `zod`                  |
| Route    | `apps/api/src/modules/<module>/`                   | validate input, `businessCtxFrom(request)`, call a service       | import `@crm/db`, contain business rules      |
| Job      | `packages/core/src/<module>/jobs.ts` (`defineJob`) | one piece of background work; calls services                     | assume it runs only once (it may be retried)  |
| Schedule | `apps/worker/src/schedules/`                       | same as a route, but on a timer                                  | import `@crm/db`                              |
| Service  | `packages/core/src/<module>/`                      | business rules, permission checks, database access via `@crm/db` | know about HTTP (no `reply`, no status codes) |

- A service function takes `ctx` first, e.g. `createContact(ctx, input)`. For business data that is a
  `BusinessContext` (`ctx.businessId`, `ctx.user`, `ctx.role`), built in routes by `businessCtxFrom(request)`,
  which also makes the route require sign-in (401 otherwise). Check `ctx.role` in the service.
- Services throw `AppError` subclasses (`NotFoundError`, `ValidationError`, `ConflictError`, …).
  The API turns them into `{ "error": { "code", "message", "details" } }`. Never build error bodies by hand.
- Add new error codes to `ERROR_CODES` in `packages/shared/src/errors.ts`.

## API conventions

- Every route is under `/api/v1`. Resources are plural nouns: `/contacts`, `/contacts/:id`.
- List endpoints use cursor pagination: `?limit=&cursor=` returns `{ data, nextCursor }`.
  Use `cursorPageQuerySchema`, `paginatedSchema` and `encodeCursor`/`decodeCursor`. Never use offset pages.
- Every route declares `schema` with `tags`, `summary` and each response code it can return.
- JSON fields are camelCase. Dates are ISO-8601 UTC strings.

## Database (MySQL 5.7)

**All businesses share one database.** Keeping them apart is the most important rule in this repo:

- Every table holding business data has `businessId String @map("business_id") @db.Char(36)`.
  Only the global tables (`businesses`, `users`, and `sessions`) don't.
- Unique keys and indexes start with it: `@@unique([businessId, emailNormalized])`, `@@index([businessId, createdAt])`.
- Services use `const db = scopedDb(ctx.businessId)` from `@crm/db` for all business data:
  - reads, counts, updates and deletes get the business condition added automatically;
  - creates must set `businessId: ctx.businessId` (TypeScript requires it, `scopedDb` checks it);
  - set foreign keys as plain fields (`ownerId: …`), not nested `connect`/`create`.
- The unscoped `prisma` client is only for platform code on global tables (login, business setup).
  Raw SQL (`$queryRaw`) is never scoped: always filter `business_id` yourself.
- Never take the business from request input on its own. It comes from the session (checked against
  the user's memberships) or, for public links, from the link's own record.
- **User-private data** (a person's connected Gmail mailbox and its synced emails) has `user_id` instead of
  `business_id`, because one person can work in several businesses. A person's own mailbox is only ever theirs:
  no role or permission opens it to someone else. When an email is logged to a CRM record it becomes a business
  activity (with `business_id`).
  `scopedDb` refuses these models (and sessions / OAuth states), directly or through a relation such as `user.mailboxes`.
- **Shared team inboxes** (HUB-366; needs the CRM admin's approval before release) are the one exception, and
  only for mailboxes an admin set up as one (`shared_inboxes`). Each is owned by its own "inbox account", a
  `users` row that cannot sign in and has no membership, so code about a person's mailbox or businesses never
  includes it. It belongs to one business. Its members, and people with "Manage inboxes", may read it while
  working in that business; without "Manage inboxes" or "Reassign conversations" a member sees conversations
  assigned to them or to a team they are in, plus unassigned ones (no person and no team) with
  "View unassigned conversations". A conversation is given only to a team with a member of that inbox.
- **Inbox channels** (HUB-366): live chat, website forms and logged calls are stored like email conversations, with
  `email_threads.channel` set, and only in team inboxes. Their messages are not email: never linked to records by
  address (a chat visitor's address is only what they typed) and never sent through Gmail. The one exception
  (HUB-715): chat replies a visitor's window never got are emailed to the address they gave, from the inbox's own
  Gmail, in the same conversation. That email holds only the team's words, never the visitor's text or name, and
  is not logged to a record by itself. A team inbox without
  Gmail has a placeholder mailbox that stays `disconnected`; connecting or switching Gmail never deletes channel
  conversations. The public chat (`/api/v1/chat`) gives a visitor only their own chat, proven by its token.
- **Every inbox function gets its mailbox from `packages/core/src/inbox/access.ts`** (`scopeOfInbox`,
  `scopeOfThread`, `scopesOfThreads`), which applies those rules; do not look a conversation up by id without it.
  What a user may not see is a 404, never a 403.
- Jira tickets under HUB-65 follow these rules. If a ticket and this file ever disagree, this file wins.
- Every module adds an isolation test with `createTestBusinesses()` from `@crm/db/testing`: data from business A
  is invisible to, and can't be changed by, business B (see `packages/db/src/scoped.test.ts`).
- Links between records (contact ↔ company, etc.) must stay within one business.

- Conventions are at the top of `packages/db/prisma/schema.prisma`: UUIDv7 ids via `newId()`,
  `created_at`/`updated_at`/`deleted_at`, snake_case tables, `VarChar(191)` for indexed strings.
- No MySQL 8 features: no CTEs, window functions, `SKIP LOCKED` or JSON table functions.
  Compute totals in code when needed.
- Every schema change is a Prisma migration (`npm run db:migrate`). Commit the migration folder.
  Never edit a migration that has already been merged.
- Raw SQL only through `Prisma.sql` / `$queryRaw` with tagged templates. Never concatenate strings.
- Times come from the app clock: pass a JS `Date` as a parameter (stored as UTC). Don't mix it with the database
  clock in the same comparison. If you ever need the database clock, use `UTC_TIMESTAMP(3)`, never `NOW()`
  (the server's timezone may not be UTC).
- Soft-deleted rows (`deleted_at` set) are excluded in every query unless the feature says otherwise.
- Custom fields live in a `customProperties Json` column. Always write them through
  `customPropertiesService.prepareCustomProperties`, which checks them against `property_definitions`.
  Standard fields (name, email, owner, stage…) are real columns.
- A user id stored on a record (`ownerId`, `assigneeId`, …) must belong to the business: call
  `authService.assertBusinessMember(ctx, userId)` before saving it.
- Updates that read a row, change it and save it (e.g. merging custom fields) must not silently overwrite
  someone else's change: update with `where: { id, updatedAt: row.updatedAt }` and return a `ConflictError`
  (409) when nothing was updated.
- Records from HubSpot keep their HubSpot id in `hubspotId` (unique per business), so the migration can be re-run safely.

## Config and secrets

- All env vars are validated with Zod at startup (`packages/core/src/config/env.ts` and each `apps/*/src/env.ts`).
  Add a new variable to the schema and to `.env.example` in the same PR.
- Never commit `.env`, tokens or customer data. The logger redacts passwords and tokens. Do not log request bodies.

## Style

- Prettier and ESLint are the source of truth. Run `npm run check` before pushing.
- Names: files `kebab-case.ts`, types `PascalCase`, functions and variables `camelCase`.
- Tests sit next to the code as `*.test.ts`. API tests use `app.inject` (see `me/routes.test.ts`).
- Comments explain _why_. Reference the Jira ticket (e.g. `HUB-87`) when a rule comes from a ticket.
