# Sync customers and contacts from a CRM

Use this recipe when your customers live in a CRM first and you want each
one in Omono as a company, with its contacts and addresses. You match each
CRM record to an Omono record by a key you control, create what's missing,
and change what's different.

Every request in this recipe sends your API key in an
`Authorization: Bearer <key>` header, and every `POST` and `PATCH` also sends
an `Idempotency-Key`, so a prompt retry doesn't do the work twice. Paths are
relative to `https://<host>/api/v1`, and the examples show the full path.

> **Note:** The company write operations are in beta. Learn more about
> [beta operations](/docs/compatibility#stable-and-beta-operations).

You need the scopes `companies:read`, `companies:write` and
`reference:read`.

## Choose the key you match on

Store the CRM's ID for each company in `externalRef`, and the CRM's ID
for each contact and address in theirs. It's unique among your
organisation's companies (and contacts, and addresses), archived ones
included, Omono doesn't show it to staff, and Omono compares it exactly.
Learn more about [external references](/docs/writing#external-references).

Use `accountNo` for the company's account number in your accounts, as
staff know it, because it prints on paperwork. Company names and account
numbers are unique too, but a match on them ignores capital letters, and
they change more often.

## Before your first sync

Look up the IDs that every new company needs, and cache them:

- an industry from `GET /industries`, and a company type from
  `GET /company-types`;
- the tax rate from `GET /tax-rates`. Omono doesn't mark which rate is for
  customers outside your tax area, so choose the 0 % rate that your
  organisation uses for them;
- the currency: your base currency from `GET /organisation`, or one of the
  currencies in `GET /currency-rates`. It can't change once the company
  has a quote, sales order, credit note or purchase order;
- the account manager, a user from `GET /users` whose `assignable` is
  `true`.

Read `GET /settings` too. When its `xero.connected` is `true`, Omono queues
each company you create or change to sync to Xero, so agree a first load of
many customers with the people who look after your accounts first.

## For each customer

1. **Find the company.**

   ```http
   GET /api/v1/companies?externalRef=CRM-10087
   ```

   An empty list means the company isn't in Omono yet. The filter also
   finds a company your staff archived, because archived records keep their
   `externalRef`. To sync many companies, send up to 100 values at once,
   separated by commas.

   Before you create a company the first time, check that your staff
   haven't already added it under a slightly different name. Send part of
   the name in `search`, such as `GET /api/v1/companies?search=acme&archived=any`,
   and link your CRM record to the right company by setting its
   `externalRef`. Search matches the start of each word, and a company you
   just created can take a few seconds to appear in it, so use it to help
   a person choose, and keep the exact filters for the sync itself.

2. **Create a missing company with its first contact and address.**

   ```http
   POST /api/v1/companies
   Idempotency-Key: crm-company-10087
   Content-Type: application/json

   {
     "companyName": "Acme Engineering Ltd",
     "externalRef": "CRM-10087",
     "accountNo": "ACME01",
     "industryId": "…",
     "typeId": "…",
     "countryId": "…",
     "currencyId": "…",
     "taxRateId": "…",
     "isCustomer": true,
     "isSupplier": false,
     "accountManagerId": "…",
     "contact": {
       "externalRef": "CRM-CONTACT-5521",
       "firstName": "Priya",
       "lastName": "Shah",
       "email": "priya.shah@acme-engineering.example"
     },
     "address": {
       "line1": "1 Harbour Road",
       "city": "Bristol",
       "postcode": "BS1 5AA",
       "countryId": "…",
       "accountsEmail": "accounts@acme-engineering.example"
     }
   }
   ```

   The address becomes the company's accounts address, which Omono uses
   for invoicing. The `201` response returns the company with its
   `contacts` and `addresses`.

3. **Change an existing company.** Send only the fields that are different
   in a `PATCH /api/v1/companies/{id}`. A `PATCH` that changes nothing
   writes nothing, so it's safe to send the CRM's values every time.

4. **Sync its contacts.** Before you add a contact, look for the person by
   their `externalRef` across all your companies:

   ```http
   GET /api/v1/contacts?externalRef=CRM-CONTACT-5521
   ```

   For a contact that staff added in Omono, which has no `externalRef`,
   look by email address instead (`?email=`, which ignores capital
   letters, with `archived=any`), and set the `externalRef` when you find
   it. If you have only part of a name, `?search=` finds it, as it does for
   companies. Both also find a contact your staff archived. If the contact is on this company,
   change it with `PATCH /companies/{id}/contacts/{contactId}`. If it's
   archived, send `"archived": false` in the same `PATCH` to unarchive it,
   rather than adding the person again. If the contact isn't on this
   company, add it with `POST /companies/{id}/contacts`.

5. **Archive instead of delete.** The API never deletes a company, a
   contact or an address. When a person leaves the customer, send
   `{ "archived": true }` in a `PATCH` of the contact. When a customer
   closes in your CRM, send the same in a `PATCH` of the company, and
   `{ "archived": false }` if it comes back. A company must keep
   one active contact, and its accounts address can't be archived. To move
   the accounts address, send `"accountsAddress": true` on another address.

## Errors to handle

| Status   | Code                                                                                                                 | What to do                                                                                                                                                                                      |
| -------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 409      | [`duplicate-name`](/docs/errors/duplicate-name), [`duplicate-account-number`](/docs/errors/duplicate-account-number) | Another company already uses the name or account number. `conflictingId` names that company: link your CRM record to it instead of creating a new one, or ask your staff which record is right. |
| 409      | [`last-contact`](/docs/errors/last-contact)                                                                          | You tried to archive the company's last active contact. Add or unarchive another contact first.                                                                                                 |
| 409      | [`accounts-address-protected`](/docs/errors/accounts-address-protected)                                              | You tried to archive the accounts address. Make another address the accounts address first.                                                                                                     |
| 409      | [`currency-locked`](/docs/errors/currency-locked)                                                                    | The company already has documents in its currency. Create a new company for the other currency.                                                                                                 |
| 409      | [`company-archived`](/docs/errors/company-archived)                                                                  | You changed a company that's archived. Send `"archived": false` in the same `PATCH` to unarchive it with your change, or skip it if it should stay archived.                                    |
| 409      | [`contact-archived`](/docs/errors/contact-archived), [`address-archived`](/docs/errors/address-archived)             | You changed a contact or address that's archived. Send `"archived": false` in the same `PATCH` to unarchive it with your change.                                                                |
| 422      | [`invalid-reference`](/docs/errors/invalid-reference), [`validation-failed`](/docs/errors/validation-failed)         | A value is wrong, and `errors[].field` names it. Fix the data instead of retrying the same request.                                                                                             |
| 429, 503 | [`rate-limited`](/docs/errors/rate-limited), [`temporarily-unavailable`](/docs/errors/temporarily-unavailable)       | Retry the same request, with the same `Idempotency-Key`, after the number of seconds in `Retry-After`.                                                                                          |
