# Mirror your data in another system

Use this recipe to keep a copy of your Omono data somewhere else, such as a
business intelligence (BI) tool, a CRM or a data warehouse. You load
everything once, and then check for changes and deleted records every few
minutes. Omono lists deleted records as events, in `GET /events`.
[Keeping in sync](/docs/syncing) explains each rule in more depth.

Every request in this recipe sends your API key in an
`Authorization: Bearer <key>` header. The recipe only reads, so it never
needs an `Idempotency-Key`. Paths are relative to `https://<host>/api/v1`,
and the examples show the full path.

You need the read scope of each kind of record you copy. A complete mirror
needs `companies:read`, `sales:read`, `purchasing:read`, `stock:read`,
`tasks:read`, `documents:read` and `reference:read`.

## Load everything once

1. **Note where the list of deleted records ends.** Call
   `GET /events?limit=1`, and store the `latestSequence` from the response
   as your saved sequence. Ignore the response's `data` and `hasMore`,
   because only `latestSequence` matters here. Because you do this first,
   a record that's deleted while your load runs is still caught.
2. **Read every record in each list you mirror**, starting from the
   beginning of time:

   ```http
   GET /api/v1/<list>?updated_since=1970-01-01T00:00:00.000Z&sort=updated&limit=200
   ```

   Add the parameters each list needs, so that you get archived records and
   the related records that belong to each one:

   | List               | Add                                       |
   | ------------------ | ----------------------------------------- |
   | `/companies`       | `archived=any&include=contacts,addresses` |
   | `/quotes`          | `include=lineItems`                       |
   | `/sales-orders`    | `include=lineItems,dispatches`            |
   | `/credit-notes`    | `include=lineItems`                       |
   | `/invoices`        | Nothing more.                             |
   | `/purchase-orders` | `include=lineItems,deliveries`            |
   | `/stock-items`     | `archived=any`                            |
   | `/documents`       | `archived=any`                            |
   | `/tasks`           | Nothing more.                             |

   A company's contacts come with it, and a purchase order's deliveries
   come with it. If you mirror only part of your data, you can read them
   on their own instead: `GET /contacts` lists the contacts of all your
   companies (add `archived=any`), and `GET /deliveries` lists the
   deliveries of all your purchase orders, with each one's purchase order
   and supplier.

   Keep asking for the next page with `nextCursor` until `hasMore` is
   `false`. Upsert each record by its `id`: update your copy if you have
   one, and add the record if you don't. For each list, store the highest
   `updated` value you saw. If a list is empty, keep
   `1970-01-01T00:00:00.000Z` as its mark until a record arrives.

3. **Copy the reference lists.** Reference lists, such as tax rates,
   currencies, users and workflow statuses, have no `updated` time and
   don't take `updated_since` or `sort`. Read each one in full, with
   `archived=any` on the lists that take it, and read `GET /organisation`
   too. Replace your copy of each list with what you receive.

## Then, every few minutes

1. **Read what changed.** For each list, call:

   ```http
   GET /api/v1/<list>?updated_since=<highest updated minus 60 seconds>&sort=updated&limit=200
   ```

   Add the same parameters as in your first load, from the table above.
   Page through the results, upsert each record by its `id`, and store the
   new highest `updated`. The 60-second overlap is deliberate, because a
   change can become visible a few seconds after the time in its `updated`
   field. It means you'll see some records twice, so always upsert, and
   never insert.

2. **Remove deleted records.** Call `GET /events?since=<saved sequence>`.
   For each event whose `op` is `deleted`, delete your copy of the record
   that its `resource` and `resourceId` name, and skip any event with
   another `op`. Store `nextSince` as your new saved sequence, even when the
   page is empty, and call again while `hasMore` is `true`.

   Events about tasks are the one exception. Omono also writes a `tasks`
   event when someone makes a task private, which hides the task from the
   API. So for a `tasks` event, call `GET /tasks/{id}` first. Delete your
   copy only if you get a `404`. If you get a `200`, upsert the task
   instead.

3. **Refresh the reference lists now and then.** They change rarely, so
   read them again every hour or once a day, rather than on every poll.
   That keeps you well inside your daily request limit, which
   [Rate limits](/docs/limits) explains. Run the refresh at a random
   minute, not on the hour, as
   [Spread your polls over time](/docs/limits#spread-polls) explains.

## Keep your copy accurate

- Each time you read a quote, sales order, credit note, purchase order,
  dispatch or delivery, replace all of its `lineItems` in your copy. Never
  merge them line by line. In the same way, replace a company's contacts
  and addresses, and a sales order's dispatches, each time the company or
  order comes back.
- A dispatch's `legalTransitions`, and the `blockedBy` list in each of
  them, are worked out when you read the order. They can change without
  changing the order's `updated` time, for example when someone creates a
  task that blocks shipping. Don't act on your copy of them: read the order
  again just before you move a dispatch.
- Deleting a document in Omono archives it, so it comes back in your poll
  with `archived` set to `true`, and it doesn't create an event.
- For reports on line items, such as what you've sold of each stock item,
  `GET /sales-order-lines` lists the line items of all your sales orders,
  Draft and Cancelled orders included, with their order's number,
  customer, status, currency and exchange rate. A line item's prices and
  costs are in its order's currency. Don't mirror your orders
  from it: a line item that staff remove leaves the list, and no event
  tells you. Keep your orders in step with `GET /sales-orders`, which
  returns each changed order with all its line items.
- A record can come back with no change that you can see. Compare it with
  your copy before you act on it.
- Ignore fields you don't recognise, and accept values you don't recognise,
  such as a new status. Omono can add both at any time.

## Errors to handle

| Status   | Code                                                         | What to do                                                                                                                                                                                                                                                                                                                                                                                                                         |
| -------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 410      | `events-expired`                                             | Your saved sequence is older than 30 days, or higher than `latestSequence`, for example because it comes from before a sandbox reset or a restore. Load everything again, and start reading events from the `latestSequence` in the `410` response.                                                                                                                                                                                |
| 422      | `validation-failed`                                          | If `errors[].field` is `cursor`, Omono can't use the cursor you sent. On a list, start again without a cursor. On `GET /events`, poll again with `since` set to your saved sequence.                                                                                                                                                                                                                                               |
| 404      | `not-found`                                                  | On a `GET` of a single record by its own ID, such as `GET /tasks/{id}`, this means the record is gone. Remove your copy. A `404` from `GET /documents/{id}/content` can also mean that the document is archived, so read the document itself before you remove your copy. A `404` with the code `route-not-found` means the path is wrong, not that the record is gone, so keep your copy.                                         |
| 409      | `document-too-large`                                         | A record on the page has more than 10,000 related records, or more than 32 MB of JSON with them, so retrying won't help. Send the same request again with the same `cursor` but without `include`, to get that page without related records, then carry on from its `nextCursor` with `include`. Read the related records of the other records on that page on their own, and ask your staff to look at the large record in Omono. |
| 429, 503 | `rate-limited`, `temporarily-unavailable`, `request-timeout` | Wait for the number of seconds in `Retry-After`, then carry on from where you stopped.                                                                                                                                                                                                                                                                                                                                             |
