# Sales documents and e-invoices (Trade)

Trade holds a tenant's commercial documents (*Vorgänge*): offers, order confirmations, delivery notes, invoices and
credit notes, purchase orders and inbound (supplier) invoices. Everything below is under `https://api.mbcom.cloud/api/trade/v1`;
every operation is in the [Trade reference](/reference/trade).

| Step | Operations | Permission |
|---|---|---|
| Offer and order | [`createOffer`](/reference/trade/createOffer), [`createOrderConfirmation`](/reference/trade/createOrderConfirmation), [`updateTransaction`](/reference/trade/updateTransaction), [`createTransactionRevision`](/reference/trade/createTransactionRevision) | `tenant:trade:sales:write` |
| Deliver | [`deliverOrder`](/reference/trade/deliverOrder), [`getOrderFulfilment`](/reference/trade/getOrderFulfilment) | `tenant:trade:sales:write` / `:read` |
| Invoice | [`draftInvoice`](/reference/trade/draftInvoice), [`previewInvoiceIssue`](/reference/trade/previewInvoiceIssue), [`issueInvoiceDraft`](/reference/trade/issueInvoiceDraft), [`draftCreditNote`](/reference/trade/draftCreditNote) | draft: `tenant:trade:sales:write`, issue: `tenant:trade:invoice:issue` |
| E-invoice check | [`getInvoiceValidation`](/reference/trade/getInvoiceValidation), [`listInvoiceValidations`](/reference/trade/listInvoiceValidations) | `tenant:trade:sales:read` |
| Inbound invoices | [`listInboundInvoices`](/reference/trade/listInboundInvoices), [`getInboundInvoice`](/reference/trade/getInboundInvoice), [`releaseInboundInvoice`](/reference/trade/releaseInboundInvoice), [`rejectInboundInvoice`](/reference/trade/rejectInboundInvoice) | `tenant:trade:inbound:read` / `:write` / `:approve` |

## One shape for every document

Every document is a **transaction** in one shape: a header (partner `addressId`, recipient, dates, payment terms,
totals) and `items` (the lines). `transactionType` names its type from the tenant's catalogue – `OFFER`, `ORDER`,
`DELIVERY_NOTE`, `INVOICE`, `CREDIT_NOTE`, `PURCHASE_ORDER`, `INBOUND_INVOICE` and the tenant's own types; read it
with [`listTransactionTypes`](/reference/trade/listTransactionTypes) instead of assuming more than these. The generic
routes ([`listTransactions`](/reference/trade/listTransactions), [`getTransaction`](/reference/trade/getTransaction),
[`createTransaction`](/reference/trade/createTransaction), [`updateTransaction`](/reference/trade/updateTransaction))
work on every type; the permission follows the type: `tenant:trade:sales:*` for sales documents,
`tenant:trade:purchasing:*` for purchasing and `tenant:trade:inbound:*` for inbound invoices.

- Totals (`netTotal`, `taxTotal`, `grossTotal`) are computed from the lines when a document is saved; you never send
  them.
- Payment terms are a snapshot taken on create: the partner's terms from master data, else the tenant default.
- `version` and `predecessorId` are **revisions** of one document
  ([`createTransactionRevision`](/reference/trade/createTransactionRevision) copies it as version `n+1` in `DRAFT`);
  `sourceTransactionId` is the document this one was made from (offer → order → delivery note → invoice).
- `PUT` replaces the stored document: send the whole document with its `items` on every
  [`updateTransaction`](/reference/trade/updateTransaction). There is no optimistic locking in trade.
- Every change is written to the document's protocol ([`listTransactionProtocol`](/reference/trade/listTransactionProtocol)).

Sales statuses are `DRAFT`, `SENT`, `ACCEPTED`, `EXPIRED`, `REVOKED` and `CONVERTED`; delivery notes made from an
order are `DELIVERED` or `CANCELLED`, issued invoices and credit notes `ISSUED`.

## Offers and orders

```bash
curl -X POST 'https://api.mbcom.cloud/api/trade/v1/sales/offers' \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' \
  -d '{
    "addressId": "10042",
    "recipientCompany": "Muster GmbH",
    "validUntil": "2026-12-31T00:00:00Z",
    "items": [
      { "name": "Notebook 14\"", "articleNumber": "NB-1400", "quantity": 3, "unit": "Stk", "unitPriceNet": 1149.00, "taxRate": 19 },
      { "name": "Einrichtung", "quantity": 2, "unit": "h", "unitPriceNet": 95.00, "taxRate": 19 }
    ]
  }'
```

[`createOffer`](/reference/trade/createOffer) is `createTransaction` with `transactionType: OFFER`; it answers
**201** with the offer, its number (the type's prefix) and the computed totals. `opportunityId` links it to a
[CRM](/reference/crm) opportunity. Without a `status` the document is a `DRAFT`.

When the customer orders, create the order with
[`createOrderConfirmation`](/reference/trade/createOrderConfirmation) (`transactionType: ORDER`) and the offer's id as
`sourceTransactionId`. An order is delivered and invoiced only once it is confirmed: create it with `status: SENT` or
set the status with [`updateTransaction`](/reference/trade/updateTransaction) – a `DRAFT` order answers
`409 order_not_confirmed` below.

## Deliver an order

[`deliverOrder`](/reference/trade/deliverOrder) (`POST /sales/order-confirmations/{id}/delivery-notes`) creates a
delivery note for the newest revision of the order. An empty body delivers everything still open; `lines` deliver part
of it:

```bash
curl -X POST 'https://api.mbcom.cloud/api/trade/v1/sales/order-confirmations/7d1e…/delivery-notes' \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' \
  -d '{"deliveryDate": "2026-11-20T00:00:00Z", "lines": [{"orderLineId": "4b0c…", "quantity": 2}]}'
```

The note is numbered gaplessly (`LS-2026-00017`), its lines point to the order lines (`sourceLineId`) and the stock is
booked out in the same transaction. A line is never delivered beyond its ordered quantity: **409** `over_delivery`
names `details.lineId`, `open` and `requested`; `nothing_to_deliver` when everything is delivered.
[`getOrderFulfilment`](/reference/trade/getOrderFulfilment) shows the delivered and invoiced quantity of every order
line, [`cancelSalesDeliveryNote`](/reference/trade/cancelSalesDeliveryNote) cancels a delivery note.

## Invoice and issue an XRechnung

Invoicing takes two steps: a **draft** without a number, then **issuing** it.

1. [`draftInvoice`](/reference/trade/draftInvoice) with `sourceIds`: delivery notes of one customer and currency (a
   collective invoice) or one confirmed order (what is ordered and not invoiced yet, e.g. services). The draft has the
   placeholder number `ENTWURF-<id>` and status `DRAFT`; its quantities count as invoiced until it is deleted, so a
   quantity is never drafted twice (`409` when nothing is left to invoice).
2. [`previewInvoiceIssue`](/reference/trade/previewInvoiceIssue) names in German what is still missing for an
   XRechnung: the tenant's company profile (address, VAT ID, IBAN, invoice contact) and the customer's master data
   address and invoice e-mail. [`getInvoiceSheet`](/reference/trade/getInvoiceSheet) shows the invoice as the
   customer reads it.
3. [`issueInvoiceDraft`](/reference/trade/issueInvoiceDraft) issues it in one database transaction:

```bash
curl -X POST 'https://api.mbcom.cloud/api/trade/v1/invoices/2c9f…/issue' \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' \
  -d '{"version": 1, "send": true}'
```

Issuing takes the next gapless number (`RE-2026-00042`, credit notes `GS-…`), dates the invoice today, writes an
**XRechnung 3.0 (CII)**, validates it with the KoSIT rules, archives the XML in the [DMS](/guides/dms)
(`typeData.einvoice`) and, with `send: true`, mails it through comms to the customer's invoice e-mail (or
`recipient`). Nothing is numbered when it fails:

- **422** `not_ready` – facts are missing; `details.problems` lists them (the same as the preview).
- **422** `einvoice_invalid` – the XRechnung fails the KoSIT rules; `details.findings` lists the findings.
- **409** – the document is no draft any more, or it changed since the `version` you sent.

An issued invoice is never changed again (`409 issued_document`), and `ISSUED` is set only by issuing (`409
issue_only`). Correct it with a credit note: [`draftCreditNote`](/reference/trade/draftCreditNote) drafts one for the
given invoice lines (or everything not credited yet), issued the same way with XRechnung type 381.
[`getInvoiceValidation`](/reference/trade/getInvoiceValidation) returns the e-invoice check of an issued invoice with
all findings, [`listInvoiceValidations`](/reference/trade/listInvoiceValidations) every check of the tenant.

Drafts another module made (`numberPending: true`, e.g. the project invoices of desk) are issued with
[`releaseTransaction`](/reference/trade/releaseTransaction) (`tenant:trade:invoice:issue`), which gives them the next
gapless number.

### Invoices you issue yourself

If your system writes the invoices (an ERP or a shop), record them with
[`issueInvoice`](/reference/trade/issueInvoice) (`POST /invoices/issue`, `tenant:trade:invoice:issue`) with
`invoiceNumber`, `addressId`, the totals and lines, and the e-invoice as `eInvoice: {content, fileName}` (base64
XRechnung or ZUGFeRD/Factur-X XML, CII or UBL, or a hybrid PDF; at most 10 MB). When the customer's master data asks
for an e-invoice, it is required (`422 einvoice_required`; an XRechnung customer also needs a Leitweg-ID,
`eInvoiceBuyerRef`: `422 leitweg_id_required`). The file is scanned for malware (`422 malware`) and validated
against the KoSIT rules; whether an invalid file is refused (`422 einvoice_invalid` with `details.report`) or only
reported depends on the tenant's setting. `503` (`scan_unavailable`, `einvoice_unavailable`) means the check cannot
run now: retry later.

## Inbound e-invoices

Supplier invoices arrive as [DMS documents](/guides/dms) – by mail or upload – and trade picks them up on its own. To
process a document you uploaded yourself, call [`createInboundInvoice`](/reference/trade/createInboundInvoice) with its
`dmsDocumentId` (idempotent per document). Processing runs in the background: the answer carries `processing`; read
the invoice with [`getInboundInvoice`](/reference/trade/getInboundInvoice) until `processing` is gone.

Trade reads the e-invoice XML (`sourceKind` `XRECHNUNG_CII`, `XRECHNUNG_UBL`, `ZUGFERD`) or, for other PDFs, OCR and AI
extraction (`PDF_OCR`), assigns the supplier from master data and matches the invoice against purchase orders and goods
receipts. Its status moves `RECEIVED → OCR_DONE → EXTRACTED → MATCHED | DISCREPANCY | DUPLICATE`, then `IN_REVIEW`,
`RELEASED` or `REJECTED` (`FAILED` when processing failed, with `error`).

- **Lock reasons** (`lockReasons`: `PREISABWEICHUNG`, `MENGENABWEICHUNG`, `DUPLIKAT`, `FEHLENDER_LIEFERANT`, …) say
  why the invoice may not be released as it is; `isBlocking: true` ones block the release.
- [`updateInboundInvoice`](/reference/trade/updateInboundInvoice) corrects it during review (matched again);
  [`resolveInboundInvoiceLockReason`](/reference/trade/resolveInboundInvoiceLockReason) accepts a blocking reason.
- [`releaseInboundInvoice`](/reference/trade/releaseInboundInvoice) releases a `MATCHED`, `DISCREPANCY` or
  `IN_REVIEW` invoice; with blocking reasons only with `override: true` and a `comment` (else `409 blocked`).
  [`rejectInboundInvoice`](/reference/trade/rejectInboundInvoice) needs a `comment`. Both need
  `tenant:trade:inbound:approve`; a state that does not allow the action is `409 invalid_state`.
- [`getInboundInvoiceDocument`](/reference/trade/getInboundInvoiceDocument) streams the original file.

## 423 workflow_locked

A tenant can run approval **workflows** on trade documents (the [Workflow](/reference/workflow) module). While a
workflow runs on a document, trade locks it
against every other change, and writes answer:

```http
HTTP/1.1 423 Locked
Content-Type: application/json

{"error": "Der Vorgang ist durch einen laufenden Workflow gesperrt.", "code": "workflow_locked"}
```

Every write on a single document can answer it – updating, revising, delivering, drafting and issuing invoices,
releasing or rejecting inbound invoices, sending purchase orders; the reference lists `423` on each of them. Reads are
never locked. The lock is recorded in `metadata.workflow` of the document (the workflow states `OPEN` and `RETRYING_SYNC` lock it); this
field belongs to the workflow module and is kept on every write, whatever you send.

How to handle it:

- **Do not retry in a loop.** The lock ends when people finish the workflow (approve, reject), which can take days –
  unlike `429` or `5xx` it is no transient error. Report it, park the change and try again after the document changed.
- To know when, subscribe to `trade.transaction.updated` (see [Webhooks](/guides/webhooks)), or look the workflow up:
  [`listInstancesByObject`](/reference/workflow/listInstancesByObject) (`GET /api/workflow/v1/tasks/object/{transactionNumber}`)
  lists the instances of a document with their `workflowState` and `currentStep`.
- If a workflow should apply your change, it is done in the workflow: the assignee changes the fields the step marks
  editable when completing the task ([`completeTask`](/reference/workflow/completeTask)).
- A document that stays locked although its workflow is over (state `RETRYING_SYNC`: the write-back to trade is
  retried automatically) can be released by an administrator with
  [`resyncInstance`](/reference/workflow/resyncInstance) (`workflow:admin`).

## Events

For [webhooks](/guides/webhooks) and [flows](/guides/flows), trade announces `trade.transaction.created`,
`trade.transaction.updated`, `trade.transaction.deleted`, `trade.offer.created`, `trade.order.created`,
`trade.deliverynote.created`, `trade.invoice.issued` and the inbound invoice states
(`trade.inboundinvoice.extracted`, `…matched`, `…blocked`, `…released`, `…rejected`, …). Events carry ids, numbers,
states and totals: read the document through the API for its lines.
