# Adding a module

A "module" is one feature area: contacts, companies, deals, tasks, and so on.
The `custom-properties` module is a complete working example (contract, service, routes, tests).
Copy its files and rename.
This guide uses `contacts`.

## 1. Table: `packages/db/prisma/schema.prisma`

```prisma
model Contact {
  id               String    @id @db.Char(36)
  businessId       String    @map("business_id") @db.Char(36)
  email            String?   @db.VarChar(191)
  firstName        String?   @map("first_name") @db.VarChar(100)
  customProperties Json?     @map("custom_properties")
  hubspotId        String?   @map("hubspot_id") @db.VarChar(32)
  createdAt        DateTime  @default(now()) @map("created_at") @db.DateTime(3)
  updatedAt        DateTime  @updatedAt @map("updated_at") @db.DateTime(3)
  deletedAt        DateTime? @map("deleted_at") @db.DateTime(3)

  business Business @relation(fields: [businessId], references: [id])

  @@unique([businessId, hubspotId])
  @@index([businessId, email])
  @@map("contacts")
}
```

Then run `npm run db:migrate -- --name add_contacts` and commit the new folder in `prisma/migrations/`.

## 2. Contract: `packages/shared/src/contacts.ts`

Zod schemas for what goes in and out. Add `export * from './contacts';` to `packages/shared/src/index.ts`.

```ts
export const contactSchema = z.object({ id: z.string(), email: z.string().nullable(), … });
export const createContactBodySchema = z.object({ email: z.email().optional(), … });
export type Contact = z.infer<typeof contactSchema>;
```

## 3. Service: `packages/core/src/contacts/service.ts`

All logic lives here. Add `export * as contactsService from './contacts/service';` to `packages/core/src/index.ts`.

```ts
import { newId, scopedDb } from '@crm/db';
import type { BusinessContext } from '../context';

export async function create(ctx: BusinessContext, input: CreateContactBody): Promise<Contact> {
  // business rules and permission checks (ctx.role) go here; throw ConflictError / ValidationError etc.
  const db = scopedDb(ctx.businessId); // reads/updates/deletes are limited to this business
  const row = await db.contact.create({
    data: { id: newId(), businessId: ctx.businessId, ...input }, // creates must set it; it is checked
  });
  ctx.log.info({ contactId: row.id }, 'contact created');
  return toContact(row); // map DB row -> API shape (never return the raw row)
}
```

**Custom fields** (contacts, companies, deals): accept `customProperties` in the body
(`customPropertiesInputSchema`) and run it through the service before saving, so every value is checked
against the admin's field definitions:

```ts
const { prepareCustomProperties } = customPropertiesService;
// create
customProperties: await prepareCustomProperties(ctx, 'contact', input.customProperties, { mode: 'create' }),
// update (row = the record as loaded)
customProperties: await prepareCustomProperties(ctx, 'contact', input.customProperties, {
  mode: 'update',
  existing: row.customProperties,
}),
```

In responses, load the definitions once (`loadFieldDefinitions`) and return
`visibleCustomProperties(defs, row.customProperties)` for each row.

For lists, use cursor pagination: sort by `(sortField, id)`, fetch `limit + 1` rows, and return the extra
row's key as the next cursor:

```ts
const after = query.cursor ? decodeCursor(query.cursor, z.object({ id: z.string() })) : undefined;
const rows = await db.contact.findMany({
  where: { deletedAt: null, ...(after && { id: { lt: after.id } }) },
  orderBy: { id: 'desc' }, // UUIDv7 ids sort by creation time
  take: query.limit + 1,
});
const page = rows.slice(0, query.limit);
return {
  data: page.map(toContact),
  nextCursor: rows.length > query.limit ? encodeCursor({ id: page.at(-1)!.id }) : null,
};
```

## 4. Routes: `apps/api/src/modules/contacts/routes.ts`

Copy `custom-properties/routes.ts`. Build the context with `businessCtxFrom(request)`, which
makes the route require sign-in. Each handler is one line:
`contactsService.create(businessCtxFrom(request), request.body)`. Add `401` and `403` to the documented responses.
Register the module in `apps/api/src/modules/index.ts`:

```ts
await app.register(contactsRoutes, { prefix: '/contacts' });
```

## 5. Test: `apps/api/src/modules/contacts/routes.test.ts`

Copy `me/routes.test.ts` (it signs in with the dev headers). Cover the success path, validation errors and
not-found, **plus isolation**: start with `createTestBusinesses()` from `@crm/db/testing`; a record created in
business A must return 404 when read, updated or deleted as business B, and must not appear in B's lists or search.
Tests run against the `crm_test` database, so the local MySQL must be up.

## 6. Check

- `npm run check` passes
- The endpoints show in Swagger (http://127.0.0.1:3340/docs) and work from there

## Background jobs

Anything slow or external (sending email, syncing Gmail, running a workflow step) is a **queued job**:

1. Define it in `packages/core/src/<module>/jobs.ts` and export that file from `packages/core/src/index.ts`:

   ```ts
   export const sendEmailJob = defineJob({
     type: 'email.send', // never rename once live
     payload: z.object({ messageId: z.string() }),
     run: (ctx, { messageId }) => emailService.send(ctx, messageId), // ctx.businessId is set
   });
   ```

2. Enqueue it in the same transaction as the change that caused it, with an idempotency key for anything
   that must never happen twice:

   ```ts
   await scopedDb(ctx.businessId).$transaction(async (tx) => {
     // ...save the message with tx...
     await enqueue(
       tx,
       sendEmailJob,
       { messageId },
       {
         businessId: ctx.businessId,
         idempotencyKey: `email.send:${messageId}`,
       },
     );
   });
   ```

The worker retries a failing job after 1 min, 5 min, 30 min and 2 h, then marks it `dead` with the last
error. Throw `PermanentError` when retrying cannot help. A job may run twice (a crash after the work but
before it is marked done), so make handlers safe to repeat. Long handlers should check `ctx.signal.aborted`
between steps: it is set if the worker lost the job to another worker.

Work that simply repeats on a timer (e.g. "every minute") is a **schedule**: add
`apps/worker/src/schedules/<name>.ts` (copy `heartbeat.ts`), list it in `schedules/index.ts`, and call a service.
