# Build a CRM

::: info What you'll learn
Build a small CRM from an empty config: companies, contacts and deals that move through a
pipeline, a board for it, salespeople who see their own numbers, and a manager who sees them all.
No code outside the config, about 30 minutes.

**Before this page:** [Getting started](./getting-started), or nothing if you follow along in
[Studio](./studio), where the finished CRM is the [CRM template](https://studio.easycms.dev/?template=crm).
:::

Each step adds to `easy-cms.config.ts`; save it and the admin follows (in Studio, as you type).
The whole config is [at the end](#the-whole-config).

## 1. Companies, contacts and deals

Three collections, linked by relationships:

```ts [easy-cms.config.ts]
import { defineConfig } from '@easy-cms/core'
import { sqlite } from '@easy-cms/db-sqlite'

export default defineConfig({
  secret: process.env.EASY_CMS_SECRET ?? '',
  db: sqlite({ url: 'file:./cms.db' }),
  collections: [
    {
      slug: 'companies',
      useAsTitle: 'name',
      fields: [
        { name: 'name', type: 'text', required: true },
        { name: 'website', type: 'text' },
        { name: 'industry', type: 'select', options: ['retail', 'software', 'health', 'education'] },
      ],
    },
    {
      slug: 'contacts',
      useAsTitle: 'name',
      fields: [
        { name: 'name', type: 'text', required: true },
        { name: 'email', type: 'email' },
        { name: 'company', type: 'relationship', to: 'companies' },
        { name: 'title', type: 'text' },
      ],
    },
    {
      slug: 'deals',
      useAsTitle: 'name',
      fields: [
        { name: 'name', type: 'text', required: true },
        { name: 'company', type: 'relationship', to: 'companies', required: true },
        { name: 'contact', type: 'relationship', to: 'contacts' },
        { name: 'value', type: 'number', min: 0 },
        { name: 'closeDate', type: 'date' },
      ],
    },
  ],
})
```

The admin has a list and a form for each, and picking a company on a deal searches the companies.

## 2. A pipeline that can't skip a step

A deal goes lead → qualified → proposal → won, or lost on the way. A [state machine](./state-machines)
adds the `stage` field and one button per transition; nothing else changes the stage:

```ts
{
  slug: 'deals',
  // …fields
  stateMachine: {
    field: 'stage',
    initial: 'lead',
    states: {
      lead: {},
      qualified: {},
      proposal: { lock: ['value'] }, // the quoted value stays as quoted
      won: { lock: true, final: true },
      lost: {},
    },
    transitions: {
      qualify: { from: 'lead', to: 'qualified' },
      propose: { from: 'qualified', to: 'proposal', requires: ['value', 'contact'] },
      win: { from: 'proposal', to: 'won', confirm: true },
      lose: { from: ['lead', 'qualified', 'proposal'], to: 'lost', confirm: { danger: true } },
      reopen: { from: 'lost', to: 'lead' },
    },
  },
}
```

A deal's page now has **Qualify** and **Lose**; **Propose** is greyed out until the deal has a value
and a contact. The side panel draws the pipeline, with where the deal is.

## 3. The pipeline on a board

```ts
admin: { board: { groupBy: 'stage', fields: ['company', 'value'] } },
```

The deals list gets **Board**: a column per stage. Dragging a card makes the transition, and a card
won't drop where no transition leads. See [Board](./admin#board).

## 4. A menu by work, and your brand

A CRM's admin shouldn't say "Content". Name the groups after the work, put the media library
under Settings, and give the admin your name and colour:

```ts
admin: {
  brand: { name: 'Northwind CRM', color: '#1d4ed8' },
  nav: [
    { id: 'sales', label: { en: 'Sales', th: 'งานขาย' }, icon: 'briefcase', order: 0 },
    { id: 'customers', label: { en: 'Customers', th: 'ลูกค้า' }, icon: 'building', order: 1 },
  ],
},
collections: [
  { slug: 'companies', admin: { group: 'customers' }, /* … */ },
  { slug: 'contacts', admin: { group: 'customers' }, /* … */ },
  { slug: 'deals', admin: { group: 'sales', /* board */ }, /* … */ },
  { slug: 'media', admin: { group: 'settings' }, fields: [] },
],
```

The dashboard's numbers are headed **Sales** and **Customers**, and the browser tab says
"Northwind CRM". [Words on the screen](./admin#words) has the rest.

## 5. Salespeople and their deals

Two roles besides admin, and an owner on each deal, set to whoever makes it:

```ts
auth: { roles: ['admin', 'manager', 'sales'] },
// on deals:
fields: [
  // …
  { name: 'owner', type: 'relationship', to: 'users', admin: { position: 'sidebar' } },
],
hooks: {
  beforeChange: [
    ({ data, operation, user }) =>
      operation === 'create' && !data.owner && user ? { ...data, owner: user.id } : data,
  ],
},
admin: {
  // …
  views: [{ id: 'mine', label: 'Mine', where: { owner: { equals: '$me' } }, board: true }],
},
```

`'$me'` is the user looking, so one **Mine** view shows each salesperson their own board
([Me, now and today](./local-api#where-values)).

## 6. A dashboard for each role

The dashboard says what each person needs first. Entries with `roles` are for those roles only:

```ts
admin: {
  dashboard: [
    { type: 'stat', label: 'My open deals', collection: 'deals',
      where: { owner: { equals: '$me' }, stage: { not_in: ['won', 'lost'] } } },
    { type: 'stat', label: 'Pipeline value', collection: 'deals', sum: 'value',
      where: { stage: { not_in: ['won', 'lost'] } }, roles: ['admin', 'manager'] },
    { type: 'stat', label: 'Won this month', collection: 'deals',
      where: { stage: { equals: 'won' }, updatedAt: { gte: '$startOfMonth' } }, roles: ['admin', 'manager'] },
    { type: 'list', label: 'My deals, closing next', collection: 'deals',
      where: { owner: { equals: '$me' }, closeDate: { gte: '$today' } }, sort: 'closeDate',
      fields: ['company', 'closeDate', 'stage'], roles: ['sales'] },
    { panel: 'recent', roles: ['admin', 'manager'] },
    'collections',
  ],
},
```

A salesperson sees their open deals and what closes next; a manager, the pipeline's value (added
up by the database) and what was won this month. A number opens its deals. See
[The dashboard](./admin#dashboard).

## 7. Salespeople start on the board

```ts
admin: {
  home: ({ user }) => (user.role === 'sales' ? '/collections/deals?board=1' : undefined),
},
```

After signing in, salespeople land on the pipeline; the menu's Home still opens the dashboard.
In Studio, **View as** shows the admin as each role.

## The whole config {#the-whole-config}

::: details easy-cms.config.ts

<!-- template: crm -->
```ts
import { defineConfig } from '@easy-cms/core'
import { sqlite } from '@easy-cms/db-sqlite'

// A small CRM: companies, the people in them, and deals moving through a pipeline (a state
// machine, on a board). Salespeople open on the board and see their own numbers; managers see
// the whole pipeline. View the admin as each role with "View as".
export default defineConfig({
  secret: process.env.EASY_CMS_SECRET ?? '',
  db: sqlite({ url: 'file:./cms.db' }),
  auth: { roles: ['admin', 'manager', 'sales'] },
  admin: {
    brand: { name: 'Northwind CRM', color: '#1d4ed8' },
    // The menu by work, not "Content"; the media library under Settings.
    nav: [
      { id: 'sales', label: { en: 'Sales', th: 'งานขาย' }, icon: 'briefcase', order: 0 },
      { id: 'customers', label: { en: 'Customers', th: 'ลูกค้า' }, icon: 'building', order: 1 },
    ],
    dashboard: [
      {
        type: 'stat',
        label: { en: 'My open deals', th: 'ดีลของฉันที่ยังเปิด' },
        collection: 'deals',
        where: { owner: { equals: '$me' }, stage: { not_in: ['won', 'lost'] } },
      },
      {
        type: 'stat',
        label: { en: 'Pipeline value', th: 'มูลค่า pipeline' },
        collection: 'deals',
        sum: 'value',
        where: { stage: { not_in: ['won', 'lost'] } },
        roles: ['admin', 'manager'],
      },
      {
        type: 'stat',
        label: { en: 'Won this month', th: 'ปิดได้เดือนนี้' },
        collection: 'deals',
        where: { stage: { equals: 'won' }, updatedAt: { gte: '$startOfMonth' } },
        roles: ['admin', 'manager'],
      },
      {
        type: 'list',
        label: { en: 'My deals, closing next', th: 'ดีลของฉันที่ใกล้ปิด' },
        collection: 'deals',
        where: { owner: { equals: '$me' }, closeDate: { gte: '$today' } },
        sort: 'closeDate',
        fields: ['company', 'closeDate', 'stage'],
        roles: ['sales'],
      },
      {
        type: 'list',
        label: { en: 'Closing next', th: 'ใกล้ปิด' },
        collection: 'deals',
        where: { closeDate: { gte: '$today' } },
        sort: 'closeDate',
        fields: ['company', 'owner', 'closeDate', 'stage'],
        roles: ['admin', 'manager'],
      },
      { panel: 'recent', roles: ['admin', 'manager'] },
      'collections',
    ],
    // Salespeople start on the pipeline itself.
    home: ({ user }) => (user.role === 'sales' ? '/collections/deals?board=1' : undefined),
  },
  collections: [
    {
      slug: 'companies',
      useAsTitle: 'name',
      admin: { group: 'customers', icon: 'building' },
      fields: [
        { name: 'name', type: 'text', required: true },
        { name: 'website', type: 'text' },
        {
          name: 'industry',
          type: 'select',
          options: ['retail', 'software', 'health', 'education'],
        },
      ],
    },
    {
      slug: 'contacts',
      useAsTitle: 'name',
      admin: { group: 'customers', icon: 'users' },
      fields: [
        { name: 'name', type: 'text', required: true },
        { name: 'email', type: 'email' },
        { name: 'company', type: 'relationship', to: 'companies' },
        { name: 'title', type: 'text' },
      ],
    },
    {
      slug: 'deals',
      useAsTitle: 'name',
      fields: [
        { name: 'name', type: 'text', required: true },
        { name: 'company', type: 'relationship', to: 'companies', required: true },
        { name: 'contact', type: 'relationship', to: 'contacts' },
        { name: 'value', type: 'number', min: 0 },
        { name: 'closeDate', type: 'date' },
        { name: 'owner', type: 'relationship', to: 'users', admin: { position: 'sidebar' } },
      ],
      hooks: {
        // A new deal is its maker's unless they pick someone.
        beforeChange: [
          ({ data, operation, user }) =>
            operation === 'create' && !data.owner && user ? { ...data, owner: user.id } : data,
        ],
      },
      // The pipeline: a stage changes only by these transitions (a button each in the admin).
      stateMachine: {
        field: 'stage',
        initial: 'lead',
        states: {
          lead: {},
          qualified: {},
          proposal: { lock: ['value'] },
          won: { lock: true, final: true },
          lost: {},
        },
        transitions: {
          qualify: { from: 'lead', to: 'qualified' },
          propose: { from: 'qualified', to: 'proposal', requires: ['value', 'contact'] },
          win: { from: 'proposal', to: 'won', confirm: true },
          lose: { from: ['lead', 'qualified', 'proposal'], to: 'lost', confirm: { danger: true } },
          reopen: { from: 'lost', to: 'lead' },
        },
      },
      admin: {
        group: 'sales',
        icon: 'briefcase',
        board: { groupBy: 'stage', fields: ['company', 'value', 'owner'] },
        views: [
          {
            id: 'mine',
            label: { en: 'Mine', th: 'ของฉัน' },
            where: { owner: { equals: '$me' } },
            board: true,
          },
        ],
      },
    },
    // The media library: under Settings, where a CRM keeps it.
    { slug: 'media', admin: { group: 'settings' }, fields: [] },
  ],
})
```

:::

## Next steps

- Start a project from it: `npm create easy-cms@latest -- my-crm --template crm`, then `npm run seed`
  for the sample data and a user per role ([Getting started](./getting-started#from-a-template)).
  After changing it in [Studio](https://studio.easycms.dev/?template=crm), **Use in a project** gives
  `npm create easy-cms@latest -- --from "…"` with your changes.
- Email the team when a deal is won: an `effect` on the `win` transition ([State machines](./state-machines#effects)).
- A longer process (charge, wait for payment, ship): [Workflows](./workflows).
- The other system of this section: [Build a booking system](./build-a-booking-system).
