# Writing data

This guide explains how to create and change records through the Omono API
without doing the same work twice or overwriting someone else's change. It
covers the headers that make a write safe to retry, how to change a
document's line items, what to do when a create fails, and which fields
Omono fills in for you. Read it before your integration sends its first
`POST`, `PATCH` or `DELETE`.

## The rules for every write

Four rules keep your writes safe. The sections below explain each one in
more detail.

1. **Send an `Idempotency-Key` header on every `POST` and `PATCH`.** If you
   have to send a request again, for example after a timeout, the key makes
   sure Omono doesn't do the work twice. Learn more in
   [Retry requests safely](/docs/writing#idempotency).
2. **Send the record's `ETag` in an `If-Match` header on every `PATCH`,
   every action and every `DELETE`.** If the record has changed since you
   read it, the request fails instead of overwriting a change you haven't
   seen. Learn more in [Avoid overwriting changes with ETags](/docs/writing#etags).
3. **A `PATCH` changes only the fields you send.** Any field you leave out
   stays as it is. To clear a field, send `null`. You can clear only a
   field that's allowed to be empty, and `null` on any other field fails
   with a `422` error. A field that Omono doesn't recognise also fails,
   with a `422` error and the code `unknown-field`.
4. **In a `PATCH`, `lineItems` is a list of changes**, not the full list of
   line items, and `lineItemOrder` is the only way to reorder them. Learn
   more in [Change line items](/docs/writing#line-changes).

A `PATCH` body follows these rules, which are Omono's own, and not the JSON
Merge Patch standard (RFC 7396). The two differ in ways that matter. A field
whose value is an object, such as a task's `recurrenceConfig`, is replaced
as a whole by the object you send, not merged with the stored one. And
`lineItems` is a list of changes, not a new array. So build your `PATCH`
bodies yourself, rather than with a merge-patch library.

A `PATCH` that doesn't change anything writes nothing. That's true of an
empty body (`{}`), and of a body that sends fields back with the values they
already have. Omono still makes its usual checks and returns the record
with a `200` response, but the record's `updated` time and ETag stay the
same, and no note is added to its history in Omono.

This holds even for a document that can't change any more, such as a Won
quote, a Complete credit note, or a sales order that's Complete or
Cancelled. A `PATCH` that sends back its current values succeeds. One that
would change it fails with a `409` error and the document's own code, such
as `quote-locked`. If the change is to a line item, `errors[].field` names
the first entry of your `lineItems` array that would change it, such as
`lineItems[0]`. If the change is to the order of the line items, it names
`lineItemOrder`.

An empty body works on every `PATCH` except a stock item's. Every `PATCH`
of a stock item sends the item's `kind`, so `{}` fails with a `422` error
and the code `missing-required-field`.

For example, this request changes a sales order's customer order number and
clears its Incoterm, the international trade term for its delivery. Every
other field on the order stays as it is:

```http
PATCH /api/v1/sales-orders/{id}
Idempotency-Key: so-1042-edit-8
If-Match: "1758879330123"
Content-Type: application/json

{
  "customerOrderNo": "PO-7781",
  "incotermId": null
}
```

## Retry requests safely

When a request times out or the connection drops, you can't tell whether
Omono received it and did the work. An idempotency key lets you send the
request again without doing the work twice, such as creating
the same sales order two times.

Send an `Idempotency-Key` header on every `POST` and `PATCH`, including
every action: `/activate`, `/issue`, `/cancel`, `/complete`, `/mark-won`,
`/mark-lost`, `/reactivate`, `/transitions` and `/proforma-paid`. A `DELETE` doesn't use
one, as [Delete a record](/docs/writing#deleting) explains. The key can
be any unique string from 1 to 255 characters long. Use a new key for each new
request, and send the same key every time you retry that request. A key
taken from your own records works well, for example your web shop's order
number:

```http
POST /api/v1/sales-orders
Idempotency-Key: shop-order-10452
```

When you send a key that Omono has seen before, this is what happens:

| When you send the key again                                    | What Omono does                                                                                                                                       |
| -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| After the first request succeeded                              | It doesn't run the request again. It returns the original status code with the record as it is now, and adds the header `Idempotency-Replayed: true`. |
| After the first request failed                                 | It runs the request again. Omono stores only successful requests, so a retry of a failed one is a fresh attempt.                                      |
| While the first request is still running                       | It returns a `409` error with the code `idempotency-in-progress` and a `Retry-After` header. Wait that many seconds, then retry.                      |
| To the same operation, with a different body or another record | It returns a `409` error with the code `idempotency-key-reuse`. Use a new key for a new request.                                                      |

Omono compares the two bodies as JSON, so the order of their fields and
their spacing don't matter.

A key belongs to one operation, which is one method on one path, such as
`POST /sales-orders` or `PATCH /tasks/{id}`. Sending the same key to
another operation counts as a new key there, so Omono runs that request and
doesn't refuse it as a reuse. Don't rely on Omono to catch a key you've used
somewhere else: make every key unique. Each API key has its own set of
idempotency keys.

Omono keeps a key for up to 24 hours, so retry promptly. It can forget a
key sooner, for example when its cache is short of memory or unavailable,
and a retry with a key Omono has forgotten runs the request again. So before
you retry a create after a long gap, check whether the record already
exists, for example by your own reference for it. The
[push orders recipe](/docs/recipes/push-orders) shows how, with a sales
order's `customerOrderNo`. If you upload several files, give each upload
its own key.

A replay tells you what the first request did, even though it doesn't run
again. A replayed create, or a replayed `PATCH` with `lineItems`, returns
the original `createdLineItems`, and a replayed action returns the original
`applied` value. If the record has been deleted since
the first request, the replay fails with a `404` error.

> **Note:** A key makes a second run very unlikely, but it can't rule one
> out. Besides a key that Omono has forgotten, there's one more rare case:
> if Omono fails after it saves your change but before it stores the
> result, a retry with the same key can run the request once more, after 60
> seconds. On a `PATCH` or an action, send `If-Match` as well, and a second
> run can't overwrite anything newer.

## Avoid overwriting changes with ETags

Every response that returns a single record has an `ETag` header. The ETag
identifies the version of the record you received. When you change the
record, send that value back in an `If-Match` header, on a `PATCH` or on
one of the record's actions. A dispatch or a delivery has no `ETag` of its
own, so when you change or delete one, send the `ETag` of its sales order
or purchase order.

An ETag is opaque. Send back exactly the value from your latest read,
including its double quotes, and don't build one yourself or compare two
ETags to decide which is newer, because Omono can change how ETags are made.
A weak ETag, which starts with `W/`, or an ETag without its quotes never
matches, so the request fails with a `412` error even though the record
hasn't changed. Lists don't carry ETags, so retrieve the record on its own
when you need one.

```http
GET /api/v1/sales-orders/{id}

HTTP/1.1 200 OK
ETag: "1758879330123"
```

```http
PATCH /api/v1/sales-orders/{id}
If-Match: "1758879330123"
```

If the record has changed since you read it, the request fails with a `412`
error and the code `precondition-failed`, and nothing is written. Read the
record again, apply your change to the fresh copy, and retry with the new
ETag. Omono doesn't store a failed request, so you can retry with the same
`Idempotency-Key`, even if the body you rebuilt is different.

When you apply a line item change again, rebuild it from the fresh copy.
Someone may have added, changed or deleted a line item in the meantime, so
check that the IDs you send still exist, and build any `lineItemOrder` from
every line item in the fresh copy, including ones someone else added.

A `PATCH` that sends `lineItems` or `lineItemOrder`, and every `DELETE`,
must send `If-Match`. Without it, the request fails with a `428` error and
the code `precondition-required`. If you don't need to check the version,
send `If-Match: *`, which only requires the record to exist. Don't send it
on a `DELETE`, as [Delete a record](/docs/writing#deleting) explains.

### Changes that staff make in Omono

Your staff can edit the same records in Omono while your integration works
with them. Between Omono's edit forms and the API, the last save wins, in
the same way as between two people using Omono. An edit form in Omono
saves every field it shows, so if someone has a record open while you
change it, their save can overwrite your change.

`If-Match` protects you from acting on your own out-of-date reads, but it
can't stop a later save in Omono. Always treat your latest read as the
truth.

Changes to an order's dispatches or deliveries take turns. While someone
in Omono saves, deletes or moves one of an order's dispatches, or saves or
deletes one of a purchase order's deliveries, your request to change that
order's dispatches or deliveries waits for them to finish, and their save
waits for your request, so the two never mix.

Changes to a purchase order take turns in the same way. Someone in Omono
can change or delete one of its line items, receive one of its deliveries,
or cancel or delete the order. While they do, these requests wait:

- a request that changes the order's deliveries
- `POST /purchase-orders/{id}/issue`
- `POST /purchase-orders/{id}/cancel`
- a `PATCH` that sends `lineItems` or `lineItemOrder`

The save in Omono also waits for your request.

Changes to a sales order's line items take turns too. A `PATCH` that sends
`lineItems` or `lineItemOrder` to a sales order waits for your other
requests that change the order's dispatches or line items, or that
activate the order. It also waits while someone in Omono saves, deletes or
moves one of the order's dispatches, changes or deletes one of its line
items, or cancels the order. Their save waits for your request.

On a quote, a `PATCH` that sends `lineItems` or `lineItemOrder` takes
turns with your other requests that change the quote's line items or mark
it won or lost. On a credit note, it takes turns with your other requests
that change the credit note's line items or complete it. If two of your
requests send line item changes with the same `ETag`, Omono saves the
first, and the second fails with a `412` error.

A request that waits more than 5 seconds fails with a `503` error and the
code `temporarily-unavailable`. Retry it after the `Retry-After` delay.

## Change line items

Quotes, sales orders, credit notes and purchase orders have line items: the
individual products, quantities and prices on the document. In a `PATCH`,
the `lineItems` array is a list of changes to make, not a replacement for
every line item. Each item in the array does one of three things:

| You send                        | What Omono does                                                     |
| ------------------------------- | ------------------------------------------------------------------- |
| `{ "id": "…", "quantity": 5 }`  | Updates that line item. Any fields you leave out keep their values. |
| `{ "id": "…", "delete": true }` | Deletes that line item. Don't send any other fields with it.        |
| An item without an `id`         | Adds a new line item at the end.                                    |

Any line item you leave out of the array stays as it is. In an entry that
updates a line item, send only the fields you want to change. Some fields
of a line item you read can't be written, such as `bomItems`, `created` and
`updated`, and sending one back fails with a `422` error and the code
`unknown-field`. A line item's `description` can be `null` when you read it,
but you can't send `null`: leave the field out instead.

For example, this body changes the quantity of one line item, deletes
another, adds a new one, and leaves every other line item alone:

```json
{
  "lineItems": [
    { "id": "line-a", "quantity": 5 },
    { "id": "line-b", "delete": true },
    { "stockItemId": "…", "quantity": 1, "price": 10 }
  ]
}
```

Omono checks every change before it saves any of them. If one of them is
refused, `errors[].field` gives the entry's position in your array, such as
`lineItems[1]` or `lineItems[1].quantity`, and nothing is saved. The array
can hold up to 250 items. On a quote or sales order, each new line item for an
assembly also brings the BOM items Omono copies from the assembly, and one
request can carry at most 1,000 line items and BOM items in all. A write
with line items counts as more than one request against your rate limits,
as [How heavy writes count](/docs/limits#heavy-writes) explains.

### Find your new line items

The `200` response includes `createdLineItems`. It gives the ID of each
line item you added, together with its position in your array, counting
from 0. Every item in the array counts towards the position, including the
ones that update or delete a line item. For the body above, it looks like
this:

```json
{
  "createdLineItems": [{ "index": 2, "id": "…" }]
}
```

Use these IDs to find your new line items. Don't use a line item's position
in the response, because someone may add a line item in Omono at the same
time.

### Change the order of line items

`lineItems` never changes the order of the line items. A line item you
update keeps its place, and new line items go after the existing ones, in
the order you send them. To reorder the line items, send `lineItemOrder`,
a list of the IDs of every line item that stays, in the order you want:

```json
{
  "lineItemOrder": ["line-c", "line-a", "line-b"]
}
```

You can send `lineItemOrder` on its own or with `lineItems`, and these
rules apply:

- List each line item that stays exactly once. Leave out any line item your
  `lineItems` deletes in the same request, and any new line item you add,
  because new line items go after the ones you list.
- A list that leaves out a line item, names one twice or names one you
  delete fails with a `422` error and the code `validation-failed`. An ID
  that isn't one of the document's line items fails with a `422` error and
  the code `invalid-reference`. The error's `errors[].field` names the
  entry at fault, such as `lineItemOrder[2]`, or names `lineItemOrder`
  itself when a line item is missing from the list.
- Sending the order the line items already have changes nothing.
- Like `lineItems`, `lineItemOrder` needs `If-Match`, and it counts against
  your rate limits in the same way, as
  [How heavy writes count](/docs/limits#heavy-writes) explains.

Once a sales order has a dispatch, which is a shipment of its goods, or a
purchase order has a delivery from the supplier, the order of its line
items is fixed. A `lineItemOrder` that would change it fails with a `409`
error and the code `line-order-fixed`, but you can still add new line items
at the end. On a cancelled purchase order, it fails with a `409` error and
the code `purchase-order-cancelled`.

### Documents with more than 250 line items

You can't change the line items of a document that already has more than
250 of them. A `PATCH` with `lineItems` or `lineItemOrder` on such a
document fails with a `422` error and the code `validation-failed`. You can
still change the document's other fields with a `PATCH` that leaves out
both, and your staff edit its line items in Omono.

### Very large documents

A write on a document answers with the whole document, so the limit of
10,000 related records that applies when you
[read one](/docs/reading#include) applies to writes too. A `PATCH` or a
lifecycle action on a document whose line items and BOM items come to more
than 10,000 fails with a `409` error and the code `document-too-large`, and
nothing changes. A `PATCH` also counts the new line items in its `lineItems`
and the BOM items that new assembly line items bring. Updating or deleting a
line item doesn't add to the count. Moving a dispatch or marking one as
paid also counts the order's dispatches and their line items, because the
response includes them. Retrying won't help, so your staff make that change
in Omono.

The size of those related records counts too. A `PATCH` or a lifecycle
action on a document whose line items and other related records come to
more than about 24 MB, as Omono stores them, fails in the same way, and
nothing changes.

### If a change stops part-way

In rare cases, a `PATCH` with `lineItems` stops after it has already changed
some line items. This can happen with a `500` error, or with a `409` error
when someone in Omono changes a line item at the same moment. The error then
includes `appliedLineItems`, which lists the line items that were already
created (with their index and ID), updated and deleted. If your `PATCH` also
changes the document's other fields, Omono saves those first, so
`appliedLineItems` can hold three empty lists: the other fields changed, but
no line item did. The document's ETag has changed, so read the document
again, rebuild your array from the fresh copy, and retry with the new
`If-Match`. In a very rare case, a failure while Omono saves the other
fields can leave some of them saved with no `appliedLineItems` in the
error, so read the document again after any error on a `PATCH` with
`lineItems`.

## Create a document with its line items

When you create a quote, sales order, credit note or purchase order, you can
send its line items in the same request, in `lineItems`. You can send up
to 250 of them. Each one is a new line item, so none of them has an `id`.
On a quote or sales order, the line items and the BOM items that
assemblies bring with them can add up to at most 1,000, so a document with
many assemblies may need its line items sent in more than one request:
create it with some of them, then add the rest with a `PATCH`.

1. Send the `POST` with the line items and an `Idempotency-Key`. The `201`
   response returns the whole document, its `ETag`, and `createdLineItems`.
2. When the document is ready, move it on with its action: `/activate` for a
   quote or sales order, or `/issue` for a purchase order. A sales order
   needs all of its line items on dispatches first, and a purchase order
   all of its line items on deliveries, unless it's a call-off.

The [Push orders into Omono](/docs/recipes/push-orders) recipe shows a
complete example.

Omono checks every line item before it writes anything. If a check fails,
the request fails and `errors[].field` names the line item at fault, for
example `lineItems[2].stockItemId`. Nothing is saved, and no document number is
used.

While Omono writes the line items, the new document already exists in
Omono with the status Draft, which every new document starts with. Its
totals don't include your line items until the create finishes and returns
its `201` response, so a PDF printed from the draft during that time leaves
your line items out of its totals. Check the `status` in the `201` response
too, because someone may have acted on the draft in the meantime.

## Recover from a failed create

Creating a quote, sales order, credit note or purchase order takes several
steps inside Omono, so a create can occasionally stop part-way, usually
with a `500` error. When that happens, Omono deletes the new draft again.
The document number the draft took isn't reused, so it leaves a gap in your
numbering, in the same way as when someone deletes a draft in Omono. Retry
the request with the same `Idempotency-Key`.

Omono keeps the draft instead if someone has already changed it in Omono,
or added a note, a file or a task to it. Omono also keeps a purchase order
that someone issued in Omono, and its `status` is then `on_order` or
`on_order_call_off`. The `500` error then names the kept document in
`keptDocument`, with `createdLineItems` for the line items that were
already written:

```json
{
  "keptDocument": {
    "resource": "sales_orders",
    "id": "…",
    "status": "draft",
    "createdLineItems": [{ "index": 0, "id": "…" }]
  }
}
```

`resource` says which kind of document was kept, in the same words that
the events list uses, such as `sales_orders`. Read that document and
finish it with a `PATCH` that sends the remaining line items, or deal with
it in Omono. Check its `status` first: on an issued purchase order, each
line item that you add raises the `onOrder` quantity of its stock item at
once, unless the item is never-diminishing.

### If a create never answers

If you never got a response to a create, retry it with the same key. For up
to 60 seconds, the retry fails with a `409` error and the code
`idempotency-in-progress`. After that, the retry cleans up the unfinished
draft and creates the document again from the start. If someone has changed
that draft in the meantime, Omono keeps it, and the retry fails with a `409`
error and the code `create-incomplete`, naming the draft in `keptDocument`.
Don't send the create again with a new key, because that would make a
second document. Finish the kept draft with a `PATCH` instead, or deal with
it in Omono.

### Other creates

The other creates, for companies, contacts, addresses, stock items, tasks
and documents, work differently. The record may already be saved when a
`500` error arrives, so before you retry, list the records with
`created_gte` to check whether yours exists.

When you create a company, you send its first contact and its accounts
address, which is the address the company is invoiced at, in the same
request. If that create fails with a `500` error, the company you find may
be missing its accounts address or its contact. To find it, retry the
create with the same `Idempotency-Key`: the retry fails with a `409` error
and the code `duplicate-name`, and `conflictingId` gives the company's ID.
Add the address with
`POST /companies/{id}/addresses`, sending `accountsAddress: true` and an
`accountsEmail`. Then add the contact with `POST /companies/{id}/contacts`.

## Move a record through its lifecycle

You don't change a document's status by writing its `status` field.
Instead, you call one of its actions, so that every check Omono makes on the
change runs for your request too:

| Action           | What it does                                                                                                        |
| ---------------- | ------------------------------------------------------------------------------------------------------------------- |
| `/activate`      | Activates a draft quote or sales order.                                                                             |
| `/mark-won`      | Marks an active quote as won, and creates a draft sales order from it.                                              |
| `/mark-lost`     | Marks an active quote as lost, with the reason the customer gave.                                                   |
| `/reactivate`    | Makes a lost quote active again, with no lost reason.                                                               |
| `/issue`         | Issues a draft purchase order.                                                                                      |
| `/cancel`        | Cancels a purchase order.                                                                                           |
| `/complete`      | Completes a credit note, which you can't undo, or a task. On a repeating task, it completes the current occurrence. |
| `/transitions`   | Moves one of a sales order's dispatches to another status, which can ship and invoice it.                           |
| `/proforma-paid` | Records whether a proforma customer, who pays before the goods ship, has paid for a dispatch.                       |

Send `/activate`, `/reactivate`, `/issue`, `/cancel` and a credit note's
`/complete` without a body. Omono ignores any body you send with them, so set a field
such as a sales order's `callOff` with a `PATCH` before you call the
action. The other actions read a body:

- `/mark-lost` needs `lostReasonId`, the reason the customer gave.
- `/mark-won` takes an optional `revisionId` and `customerOrderNo`. Your
  organisation's settings can make `customerOrderNo` required.
- A task's `/complete` takes an optional `taskStatusId`, the closed status
  to give the task.
- `/transitions` and `/proforma-paid` need the fields that their pages in
  the [API reference](/docs#tag/dispatches) describe.

Every action returns `applied`, which says whether the action changed
anything, and the record as it is now:

```json
{
  "applied": true,
  "salesOrder": { "id": "…", "status": "on_order" }
}
```

When `applied` is `false`, the record, or the dispatch, was already in that
state, so nothing changed. This is true whatever `If-Match` you sent, so a
retry of an action is safe.

`/reactivate` mirrors the **Reactivate** action in Omono. The quote's
`lostReasonId` becomes `null`, Omono adds a note and an activity feed
entry, and the automatic follow-up tasks that `/mark-lost` closed stay
closed. To change the reason on a lost quote, reactivate it, then mark it
as lost again with the new reason. If your organisation's settings close
quotes automatically, Omono's nightly job can close a reactivated quote
again. `/reactivate` on a draft or a won quote fails with a `409` error
and the code `quote-not-lost`, and on a lost quote that has a sales order
with a `409` error and the code `quote-locked`.

If a `/mark-won` request fails part of the way through, the quote can be
left won with no sales order. A retry of `/mark-won` then creates the order
and returns `"applied": true`.

A repeating task is the exception. Each `/complete` completes the task's
current occurrence and moves the task on to its next one, so the task isn't
complete until its series ends, and a second request completes the next
occurrence too. Send an `Idempotency-Key` with every `/complete`, and send
the same key when you retry it, so that Omono replays the first response
instead. Send `If-Match` as well: the first request changes the task's
`ETag`, so a request with an old `ETag` fails with a `412` error rather
than completing another occurrence.

If the record can't reach that state from where it is, the action fails
with a `409` error and a code that says why. For example, activating a
cancelled sales order fails with the code `sales-order-locked`, and marking
a draft quote as won fails with the code `quote-not-active`.
`/activate`, `/issue` and a credit note's `/complete` also refuse a draft
that has no line items, and `/mark-won` refuses a quote revision that has
none, with a `409` error and the code `no-line-items` on the field
`lineItems`. A
sales order that isn't a call-off needs all of its line items on dispatches
before `/activate` (`409` with the code `dispatches-incomplete`), and a
purchase order that isn't a call-off needs them all on deliveries before
`/issue` (`409` with the code `deliveries-incomplete`), as in Omono.

An action on a document with many line items and BOM items does more work
than an ordinary request, so it can count as more than one request against
your rate limits, as [How heavy writes count](/docs/limits#heavy-writes)
explains.

Shipping and invoicing have their own guide,
[Dispatches and invoicing](/docs/workflow).

## Archive and unarchive a record

To archive or unarchive a company, a contact, an address or a stock item,
send `archived` in a `PATCH` of the record, such as
[`PATCH /companies/{id}`](/docs#tag/companies/PATCH/companies/{id}).
A stock item's `PATCH` also needs its `kind`, as every stock item update
does:

```json
{ "kind": "normal", "archived": true }
```

- **Send the state you want.** `archived` isn't a toggle: sending the
  value the record already has changes nothing, so the record's `updated`
  time and `ETag` stay the same and no note is added.
- **An archived record can't change.** A `PATCH` that changes another
  field of an archived record fails with a `409` error and the record's
  own code, such as `company-archived`, unless it also sends
  `archived: false`. Omono then unarchives the record first and applies
  your changes after. With `archived: true` and other changes, Omono
  applies the changes first and archives the record last. Omono checks
  your changes before it unarchives the record, so a request that fails
  its checks changes nothing. If the request fails after Omono unarchived
  the record, because someone changed the record at the same moment or
  because of a server error, the record stays unarchived. Read it again
  before you retry.
- **The response shows the record as it is now.** If someone else changed
  `archived` at the same moment, it can differ from what you asked for.
- **An archived company takes no new work.** You can't create a quote,
  sales order, credit note or purchase order for an archived company, or
  add a contact or an address to it (`409` with the code
  `company-archived`). You can still update its contacts and addresses.
- **The same as in Omono.** Archiving needs the record's write scope,
  such as `companies:write` or `stock:write`. As when staff archive a
  record in Omono, it doesn't check open quotes, orders or stock on hand.
  Omono adds a note to the record's history that names your key, and you
  can undo it by sending `archived: false`.

## Delete a record

The API has seven `DELETE` operations. Four delete a Draft document:

- `DELETE /quotes/{id}` deletes a Draft quote.
- `DELETE /sales-orders/{id}` deletes a Draft sales order.
- `DELETE /credit-notes/{id}` deletes a Draft credit note.
- `DELETE /purchase-orders/{id}` deletes a Draft purchase order.

Two delete part of an order:
`DELETE /sales-orders/{id}/dispatches/{dispatchId}` deletes a sales
order's dispatch, and `DELETE /purchase-orders/{id}/deliveries/{deliveryId}`
deletes a purchase order's delivery. Omono lets you delete one only while that can't change
your stock levels: a dispatch that's still in the first, unallocated stage
of your workflow and has no picked goods, or a delivery that hasn't been
received. To remove a line item, use a `PATCH` instead, as
[Change line items](/docs/writing#line-changes) explains.

One removes a supplier from a stock item:
`DELETE /stock-items/{id}/suppliers/{supplierId}` removes that supplier's
row. It needs the `purchasing:write` scope as well as `stock:write`.

Every `DELETE` follows these rules:

- **Send `If-Match`** with the `ETag` you read. For a dispatch or a
  delivery, that's the `ETag` of its sales order or purchase order, and
  for a supplier row, the `ETag` of its stock item.
  Without `If-Match`, the request fails with a `428` error and the code
  `precondition-required`. If the record has changed since you read it,
  the request fails with a `412` error, and nothing is deleted. Don't send
  `If-Match: *`, because it skips that check, and you could delete a record
  that someone changed after you read it.
- **You don't need an `Idempotency-Key`.** Omono doesn't use one on a
  `DELETE`.
- **A repeat gets a `404`.** If you send a `DELETE` again after it worked,
  for example because you never got the first response, the request fails
  with a `404` error and the code `not-found`. On a retry, treat that `404`
  as success: the record is already gone.

A successful `DELETE` returns `204` with no body. After you delete a
dispatch or a delivery, its `ETag` header is the order's new `ETag`, so use
it for your next write to the order. After you remove a supplier, it's the
stock item's new `ETag`.

### Delete a Draft document

You can delete a quote, sales order, credit note or purchase order only
while it's a Draft, as in Omono. Anything else fails with a `409` error and
the code `not-a-draft`, and nothing is deleted. A Draft quote that has more
than one revision fails with the code `quote-has-revisions`. Omono doesn't
use a deleted document's number again.

Omono deletes the Draft only if it still matches your `ETag` at the moment
it deletes it. If someone changes the Draft while your request runs, the
request fails with a `412` error, and nothing is deleted. With
`If-Match: *`, Omono doesn't check the version.

A delete works as it does in Omono:

- **Everything that belongs to the document goes with it:** its line
  items, its dispatches or deliveries, its notes and files, and the tasks
  linked to it.
- **Records that point to it stay.** A purchase order that was raised from
  a deleted sales order loses its link, and Omono adds a note to it. When
  you delete a purchase order that was raised from a sales order, Omono
  adds a note to the sales order.
- **A won quote stays Won.** When you delete the sales order that a won
  quote created, the quote keeps its Won status, and Omono adds a note to
  it. If you call `/mark-won` on that quote again, Omono creates a new
  sales order.
- **The deletes appear in the events feed.** Each deleted record appears
  in `GET /events`: the document, its line items, its dispatches or
  deliveries, its files and its public tasks. Learn more in
  [Find deleted records](/docs/syncing#deletes).

A key that has the `sales:write` scope can delete Draft quotes, sales
orders and credit notes. A key that has the `purchasing:write` scope can
delete Draft purchase orders.

## Avoid duplicates

Some values must be unique across your organisation, including archived
records. If you create a record with a value that another record already
has, the request fails with a `409` error:

| Value                      | Error code                 |
| -------------------------- | -------------------------- |
| A company's name           | `duplicate-name`           |
| A company's account number | `duplicate-account-number` |
| A stock item's part number | `duplicate-part-number`    |
| A record's `externalRef`   | `duplicate-external-ref`   |

Before a create, look the value up with `archived=any`, so that archived
records are included. For example:

```http
GET /api/v1/companies?accountNo=ACME01&archived=any
```

If you still get a duplicate error after your lookup found nothing,
someone created the same value at the same moment. Look it up again. If you
still find nothing, the other request didn't keep the value, so retry
yours.

A stock item has one row for each supplier. Adding a company that's
already a supplier of the item fails with a `409` error and the code
`duplicate-supplier`. To change that supplier's part number, lead time or
price, send a `PATCH` to its row instead.

In rare cases, someone who creates the same value in Omono at the very
moment of your write can leave two records with the same value. Every later
write to either record then fails with the duplicate error until one of
them is renamed.

## Keep your own IDs with external references

Companies, contacts, addresses, stock items, quotes, sales orders,
purchase orders, credit notes, tasks and the line items of the four
documents each have an `externalRef` field. Use it for the record's ID in your own
system, such as the order number in your web shop, so that you don't have
to put your IDs in fields that staff and your customers see, like
`customerOrderNo` or `accountNo`.

- Only the API sets `externalRef`. Omono doesn't show it to staff, and it
  doesn't copy it when staff copy a record, so a copy has none. When a
  quote is won, each sales order line item gets the `externalRef` of the
  quote line item it came from, so you can match the order's lines to
  yours. The order itself has none.
- It's up to 100 characters, with no spaces at the start or end, and Omono
  compares it exactly, capital letters included.
- Send it when you create the record, or set it later with an update. Send
  `null` to remove it.
- It's unique among your organisation's records of the same kind, archived
  and cancelled ones included. A line item's is unique among the line items
  of its document (for a quote, of its revision).

So `externalRef` also protects you from creating a record twice, long
after an `Idempotency-Key` has expired. If another record already has the
value, the request fails with a `409` error and the code
`duplicate-external-ref`, and `conflictingId` names the record that has it.
That's usually the record you sent before, so read it instead of creating
it again. On a line item, `conflictingId` names the line item.

Each list of these records takes an `externalRef` filter, with up to 100
values separated by commas, so you can find your records again with one
request:

```http
GET /api/v1/sales-orders?externalRef=WEB-10452,WEB-10453
```

As with `ids`, the filter includes archived records unless you send
`archived=false`.

## Price a line

When staff add a stock item to a quote or sales order in Omono, Omono
fills in its price from the customer's price list, or from the stock
item's sell price, and fills in a discount. The API doesn't fill in
`price` or `discount` for you, but it tells you the values Omono would
use. You need the `pricing:read` scope, and the `sales:read` or
`sales:write` scope to name a quote or sales order.

1. Call
   [`GET /companies/{id}/price`](/docs#tag/customer-prices/GET/companies/{id}/price)
   with the customer's ID, the `stockItemId`, the `quantity`, and the
   quote's ID in `quoteId` or the sales order's ID in `salesOrderId`.
2. Send `linePrice` as the line's `price`, and `discount` as its
   `discount`.

`linePrice` is in the document's currency, which `lineCurrencyId` names.
A price from the price list is sent as it is. A sell price is in your
base currency, and Omono converts it with the document's exchange rate,
so `linePrice` matches the price staff get in Omono to the penny.
`discount` is 0 on a price from the price list, and the customer's sales
discount on a sell price.

The price list Omono uses is always the one in effect today, whatever the
date of the quote or sales order. If the stock item has no sell price, or
can't be sold, `price` is 0 with `source` `stock-sell-price`, as Omono
fills in on a new line. A price of 0 on the price list is used as it is.
A 0 means Omono holds no price for the item, so don't send a line at 0
unless you mean it to be free.

A few old quotes and orders have an `exchangeRate` of `null`, and for
them `linePrice` is `null` when the price is a sell price. Set the rate
first with `PATCH /quotes/{id}` or `PATCH /sales-orders/{id}`, taking it
from [your currency rates](/docs#tag/tax-and-currency/GET/currency-rates).

A price from the price list is in the customer's currency now. If the
customer's currency changed after the document was made, the document
keeps its old currency, and `linePrice` is `null` for a price from the
price list, because that price isn't in the document's currency. Price
that line by hand. A sell price is converted as usual.

**To create a document with its lines in one request**, there's no
document to name yet. Call without `quoteId` or `salesOrderId`. If
`source` is `customer-price-list`, send `price` as it is. If `source` is
`stock-sell-price`, the price is in your base currency: round the
document's exchange rate to 5 decimal places, multiply the price by it,
and round the result to your Unit Pricing setting, 2 or 4 decimal places.
The setting is `unitPricing.salesDecimalPlaces` in
[your settings](/docs#tag/organisation/GET/settings). For example, with a
2-place setting, a sell price of 5000 at an exchange rate of 1.234567 is
5000 × 1.23457 = 6172.85. A document in your base currency has an
exchange rate of 1. Send
`discount` as it is. Or create the document first, and add its lines
with a `PATCH` priced by the call above.

Omono rounds a price to your organisation's Unit Pricing setting when it
writes the line, so a price-list price with more decimal places is
rounded. `linePrice` is already rounded this way. When staff first pick a
stock item in Omono, the line starts with the stock item's sell price,
and Omono looks up the price list once they type a quantity. The API
needs a quantity above 0, so its answer can differ from that first price.

The price can change when the quantity changes, because a price list can
have a lower price from a higher minimum quantity, so ask again for each
quantity. Changes to price lists don't appear in `GET /events`. To see a
customer's whole price list, call
[`GET /companies/{id}/price-list`](/docs#tag/customer-prices/GET/companies/{id}/price-list).

## Fields Omono fills in for you

When you leave a field out, Omono fills it in as this section describes.
To leave a field empty instead, send `null`. These defaults follow Omono's
own, so they can change as Omono changes, and the
[changelog](/docs/changelog) lists any change.

**On every new line item**, whether you add it in a create or in a `PATCH`:

| Field                                    | Where Omono takes it from                                                                                                                  |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| The tax rate                             | The customer or supplier. A line item whose stock item is tax-exempt gets the exempt tax rate instead.                                     |
| The analysis code and description        | The stock item.                                                                                                                            |
| The commodity code and country of origin | The stock item, on quote and sales order line items only. If the stock item has no commodity code, Omono uses its analysis code's default. |
| `unitPrice`                              | Worked out from `price` and `discount`.                                                                                                    |
| `discount`                               | Defaults to 0.                                                                                                                             |

An analysis code is a category your organisation uses to analyse its sales
or purchases.

You always send `price`, and you can [look it up](/docs/writing#pricing-a-line) as
Omono does. If you send `unitPrice` as well, it may differ
from the value Omono works out by at most one unit in the last decimal
place.

**On a new document**, Omono fills in these fields only when you create
it. A `PATCH` never fills in a document's own fields.

- The division, which is one of the offices or branches your organisation
  is split into, comes from the company, as long as that division isn't
  archived.
- On quotes and sales orders, the commission comes from the customer, as
  long as that commission isn't archived. If it's archived, the new
  document has no commission.
- The EORI number, the customs registration number used for imports and
  exports, is filled in when your organisation has exactly one.
- A quote's enquiry date is today, in your organisation's time zone.

## Point to other records

Many fields point to another record, such as `salesPersonId` or
`taxRateId`. When you set one, the record it names must belong to your
organisation and must not be archived. Otherwise the request fails with a
`422` error and the code `invalid-reference`, and `errors[].field` names the
field. A field that points to a user must name a user whose `assignable` is
`true` in `GET /users`.

There's one exception, so that you can send back a record exactly as you
read it: if a field already holds an archived value, you can send that same
value again.

The API's other limits have no such exception. Records that staff create in
Omono can hold values the API doesn't accept, such as a telephone number
longer than 50 characters or a name with an invisible character in it. If
you send one of those values back, even unchanged, the request fails with a
`422` error that names the field. So in a `PATCH`, send only the fields you
want to change.

## Add a note to a record

Add a note to a company, quote, sales order, credit note, purchase order,
stock item or task with `POST /<record>/{id}/notes`, such as
[`POST /quotes/{id}/notes`](/docs#tag/notes/POST/quotes/{id}/notes). Send
the note's text, and nothing else:

```json
{ "text": "Called Priya Shah: the customer wants delivery before 12 December." }
```

The note needs the record's own write scope, such as `sales:write` for a
quote. Omono answers `201` with the new note.

- **Plain text only.** Omono shows the text with no formatting. Start a
  new line with a line feed (`\n`). The `text` Omono returns can differ
  from what you sent in two ways: Omono removes spaces and line breaks from
  the start and end, and replaces a character that isn't valid Unicode.
- **Up to 2,000 characters and 50 lines.** The text must have at least
  one character that isn't a space or a line break. A longer text, more
  lines, or a control character other than a tab or a line break fails
  with a `422` error and the code `validation-failed`. Notes are for short
  history, such as a call or a decision: put long text in a document.
- **About 50 notes on a record in 24 hours.** All your keys together can
  add about 50 notes to one record in any 24 hours. Omono checks the count
  before it adds a note, so notes sent at the same moment can pass it by a
  few. Past it, the next one fails with a `429` error and the code
  `rate-limited`. This `429` is a daily cap on the record, not a request
  limit: `Retry-After` gives the seconds until the record can take
  another, which can be many hours. Don't retry it sooner.
- **The author is your key.** Staff see the note's author as
  `API · <key name>`, and the note's `apiKeyId` is your key's ID. You can't
  send an author, a user or a date.
- **Any state.** You can add a note to an archived company or stock item,
  and to a document or task in any status, closed or cancelled ones
  included, as staff can in Omono.
- **Add-only.** A note can't be changed or deleted through the API, so
  check the text before you send it. Send an `Idempotency-Key`, so that a
  retry doesn't add the note twice.
- **The record doesn't change.** A new note doesn't change the record's
  `updated` time or its `ETag`. To see new notes, read the record's notes
  list, as [Read a record's notes](/docs/reading#notes) explains.

Notes count towards your organisation's daily limit of stored text, with
descriptions, as [Limits](/docs/limits#stored-descriptions) explains.

## Good to know

- **Quantities** can have up to 4 decimal places, and can be at most
  1,000,000,000. On a line item for an assembly (a stock item that Omono
  builds from other stock items), the quantity must be a whole number.
- **Prices** can be at most 1,000,000,000. Omono rounds a price you send to
  your organisation's Unit Pricing precision, which is 2 or 4 decimal
  places. You can read it with `GET /settings`, in
  `unitPricing.salesDecimalPlaces` for sales prices and
  `unitPricing.purchasingDecimalPlaces` for purchase prices. A price you read can have more
  decimal places than that, so parse amounts as decimals, as
  [Money and exchange rates](/docs/conventions#money) explains.
- **Text fields** have length limits, which each field's description in
  the API reference gives, and names can't contain invisible characters.
  [Text](/docs/conventions#text) explains how length is counted.
- **Request bodies** are JSON, sent as `application/json` in UTF-8. A body
  can be up to 1 MB, and it can nest objects and arrays at most 32 levels
  deep. A body in another character set fails with a `415` error.
- **Compressed bodies** are accepted. You can compress a JSON body with
  `gzip`, `deflate` or `br`, and name the encoding in a `Content-Encoding`
  header. The 1 MB limit then applies to the body after Omono decompresses
  it. Any other encoding fails with a `415` error, and a body that can't be
  decompressed fails with a `400` error. An upload to `POST /documents`
  can't be compressed at all.
- **System tax rates** are the tax rates Omono defines itself. A company or
  a line item can't use one. The only exception is the exempt tax rate,
  which a line item gets when its stock item is tax-exempt.
