# ConnectCloud CRM API (v1.0.0)

Leads, campaigns, opportunities and customer satisfaction (CSAT), the customer timeline of calls and meetings, address quality checks and the NFON phone book settings.

Base URLs:

- Production: `https://api.mbcom.cloud`
- Staging: `https://api.mbcom.cloud`
- Sandbox: `https://developers.mbcom.cloud/sandbox/crm`

The CRM module keeps the sales pipeline of a tenant: **leads**, **opportunities**, marketing
**campaigns**, **activities** (notes, calls, meetings, tasks), a configurable **pipeline** with reports
and customer satisfaction (**CSAT**) feedback. It also checks VAT identification
numbers of EU member states (officially through EU VIES or the German Federal Central Tax
Office BZSt), scores the completeness of contact data and decides which contacts go into the
tenant's phone book of the **NFON** cloud telephony system (comms writes it).

All paths in this document are full paths (the module serves `/api/crm/v1` plus a few
service routes); the server URL is the origin.

## Model
- **Leads** are prospects (`company`, `contactName`, optional `email`, `phone`, `notes`) with
  a `status` (`NEW → CONTACTED → QUALIFIED | LOST`), a free-text `source` (default: the
  tenant's `defaultLeadSource`, else `MANUAL`) and a `score` from 0 to 100. They also have an
  owner (`ownerEmail`; by default the person who creates the lead; filter `owner=me` or an
  e-mail), an optional `campaignId`, `website`, `vatId`, GDPR consent (`consent`, `consentSource`;
  `consentAt` is set by the server when `consent` turns true, `marketingOptOut`) and the values of
  the tenant's custom fields (`customFields`, see the configuration).
  **Converting** a lead links it to a masterdata address (`convertedAddressId`) and
  sets `status` to `CONVERTED`; that status can only be reached by conversion, a lead is
  converted once and keeps `CONVERTED` (its other fields stay editable). Conversion either
  uses an existing address (`addressId`) or creates the company address in masterdata
  (`createAddress`, once per lead: status `INTERESSENT`, the lead's contact as contact person
  (Ansprechpartner)); exactly one of the two is required (`400`, `convert_target_required`). It can
  create a first opportunity (`opportunity`) in the same step.
- **Duplicates:** creating a lead checks for leads with the same normalised company name or the same
  e-mail address (and masterdata addresses). With candidates the answer is `409`
  (`duplicate_lead`, the body lists the `candidates` and `masterdataUnavailable`, which is `true`
  when only leads could be searched) unless `force` is `true`. `findLeadDuplicates` runs the same
  check beforehand.
- **Lead scoring:** when `leadAutoScoring` is on, a lead's `score` is calculated: fit (max 40:
  company 8, contact 8, email 8, phone 6, website 5, VAT ID 5) plus engagement of the last 30 days
  (max 40: CALL, MEETING and EMAIL activities 10 each, NOTE 5) plus status (QUALIFIED 20,
  CONTACTED 10). A `score` sent in a request wins for that write. The score is recomputed on lead
  and activity writes. With `leadAutoScoring` off a new lead without `score` gets 0.
- **Retention:** with `leadRetentionMonths` (0–120, 0 is off) a daily job anonymises `LOST` leads
  and `NEW` / `CONTACTED` leads without change or activity in that time: `contactName` becomes
  `Anonymisiert`; `email`, `phone`, `notes`, `website`, `vatId` (with `vatStatus` and `vatCheckedAt`),
  `consentSource` and `customFields` are cleared; their activities other than `SYSTEM` keep their entry with
  the subject `Anonymisiert`, without body and mail recipient; mails to the lead not sent yet are dropped,
  sent ones lose recipient, subject and text; the lead's rows in stored import results and the personal
  fields of its `crm.lead.created` event are cleared (deleting a lead clears the same traces). `company`,
  `status` and `marketingOptOut` stay, `anonymizedAt` is set and a `SYSTEM` activity is written. Results of
  lead imports older than the retention keep their counters, not their rows. An anonymised lead is
  read-only: changing, converting it, new activities, mails and VAT checks on it answer `409`
  (`lead_anonymized`); deleting it stays possible. Emits `crm.lead.anonymized`.
- **Opportunities** are possible deals with a `stage` (the key of an active stage of the tenant,
  default the first open stage), a win `probability` in percent (default: the stage's) and a
  `value` in the tenant's currency. They have an owner (`ownerEmail`, default the creating
  person), a `lostReason`, `closedAt` and `customFields`. They may
  reference a lead of the tenant (`leadId`) and a masterdata address of the tenant
  (`addressId`); both are checked when set or changed (`422` otherwise). Deleting a lead keeps
  its opportunities and removes their `leadId`.
- **Stages** are tenant configuration (`listStages`, `replaceStages`). Until the tenant saves its own
  they are `PROSPECTING` Akquise (10), `QUALIFICATION` Qualifizierung (30), `PROPOSAL` Angebot (50),
  `NEGOTIATION` Verhandlung (75), `CLOSED_WON` Gewonnen (100, won) and `CLOSED_LOST` Verloren (0,
  lost). A stage has a `phase` (`open`, `won`, `lost`) and a default `probability`; every phase
  needs at least one active stage (`400`, `invalid_stages`). A key that opportunities use can only be
  archived, not removed (`400`, `stage_in_use`). The stage of an opportunity must be an active
  stage (`400`, `unknown_stage`). `closedAt` is set by the server when an opportunity enters a won or
  lost stage and cleared when it leaves; entering a lost stage needs a `lostReason` (`422`,
  `lost_reason_required`).
- **Activities** are `NOTE`, `CALL`, `MEETING`, `EMAIL` and `TASK` (with `dueAt`, `assigneeEmail`,
  completion `doneAt` / `doneBy`) linked to a lead, an opportunity, an address or a campaign; at least one
  of `leadId`, `opportunityId` and `addressId` is required (`400`, `activity_link_required`). `SYSTEM` entries are
  the history the CRM writes itself (stage changes, conversion, anonymisation, …); they are read-only
  (`409`, `system_activity`). `completeActivity` and `reopenActivity` work only on tasks
  (`409`, `activity_not_task`).
- **Reports:** `getPipelineReport` (open pipeline per stage, forecast per month, per owner, win
  rate) and `getCampaignReport` (leads, conversions, opportunities, won value, cost and ROI per campaign).
- **Campaigns** have a `type` (`EMAIL`, `WEBINAR`, `TRADE_SHOW`, `ADS`, `EVENT`,
  `SOCIAL_MEDIA`, `OTHER`; default `EMAIL`), a `status` (`PLANNING`, `ACTIVE`, `COMPLETED`,
  `CANCELLED`; default `PLANNING`), `budget`, `actualCost` and an optional date range
  (`endDate` must not lie before `startDate`).
- **CSAT feedback** is a rating from 1 to 5 with an optional comment, given through a
  `channel` (`PORTAL`, `EMAIL`, `PHONE`, `IN_PERSON`; default `PORTAL`), optionally tied to a
  masterdata address or a desk ticket. Feedback cannot be changed or deleted.
- The **module configuration** holds the CRM settings (`getCrmConfig`): `leadAutoScoring`,
  `defaultLeadSource`, `vatCheckEnabled` (`validateVatId` answers `409` when off),
  `leadRetentionMonths`, the custom field definitions `customFields` (`lead` and `opportunity`) and `active`,
  which marks the module as set up for the portal; the API does not refuse requests of an
  inactive module, the permissions decide. The NFON connector has its own settings
  (`getNfonConfig`).
- The **NFON phone book**: CRM decides which contacts go into the tenant's NFON phone book and sends
  it to the comms module, which holds the NFON connection (account, Service Portal API key) and
  writes the phone book with the NFON Service Portal API (it compares with its own entry index and
  changes only what differs). The phone book holds the tenant's masterdata addresses and active
  contact persons (not marked `doNotCall`) with phone numbers and, unless `includeLeads` is
  `false`, the leads with a phone number (numbers normalised to E.164 with the address country,
  else DE; an address's main number is named after the company, a contact's numbers
  "First Last T1/T2/M (Company)", names cut to NFON's 50 characters; a number appears once, the
  first source wins: address, its contacts, then leads). Every run sends the **complete** phone
  book; a **full** run asks comms to empty the NFON phone book and recreate it. By default a run is
  scheduled every minute (`syncIntervalCron`) and the full run Sundays at 03:00 (`fullSyncCron`),
  both in German time; a scheduled run sends only when masterdata addresses or the leads changed
  since the last run that was sent (otherwise nothing is sent or logged). A tenant's first
  scheduled run is a regular one, also when only the full run is scheduled. A full run that fails
  still uses its slot. Only one run per tenant at a time across all instances. Every sent or failed
  run is logged (`listNfonSyncRuns`) with the numbers it left out.
- A **VAT check** with a `leadId` stores `vatId`, `vatStatus` and `vatCheckedAt` on the lead.

## Authentication
Send an access token as `Authorization: Bearer <accessToken>`. Get it by exchanging an API key at
`POST https://api.mbcom.cloud/api/hr/v1/auth/token`; it lives 15 minutes and carries the key's permissions.
The tenant is always the one of the token. Guide: https://developers.mbcom.cloud/guides/authentication

## Permissions
| Permission | Grants |
|---|---|
| `tenant:crm:read` | read leads, opportunities, campaigns, activities, stages, reports and CSAT feedback; duplicate search; quality score; the CRM module configuration |
| `tenant:crm:write` | create, change, convert and delete leads, opportunities, campaigns and activities; record CSAT feedback; VAT check (it queries VIES/BZSt and is logged in masterdata) |
| `tenant:crm:admin` | replace the pipeline stages; change the CRM module configuration (custom fields, retention) |
| `tenant:settings:read` | read the CRM module configuration (as `tenant:crm:read` does), the module status, the NFON phone book settings and sync status |
| `tenant:settings:write` | change the CRM module configuration (as `tenant:crm:admin` does) and NFON phone book settings, start syncs |

## Conventions
- Lists (leads, campaigns, opportunities, CSAT feedback, activities) return `{items, total, nextCursor}`:
  the page, the number of all matching records and the cursor of the next page (missing on the last
  page). Page with `limit` (1–200, default 50) and `cursor` (the `nextCursor` of the previous page; keep
  `sort` and the filters unchanged). They are sorted by `sort`: a field name for ascending, `-field`
  for descending (the allowed fields are listed per operation); the default is `-createdAt`, tasks
  (`kind=TASK` or `open=true`) by `dueAt`; empty values come last. The record id breaks ties, so pages
  are stable while records change. An unknown sort is `400` with `code: invalid_sort`; a `limit`
  outside 1–200 or a cursor of another sort or an altered one is `400 invalid` (`field` `limit` or
  `cursor`). **Breaking change within `v1`:** `offset` is gone.
- Errors have the shared shape `{error, code, field?, details?}` (`Error`, guide „Errors“): `error` is a German
  message for people, `code` the stable reason to branch on (listed in the `Error` schema). Invalid input is
  `400 invalid` with `field` and every invalid field in `details.fields` (`field`, `rule`, `message`); other
  `400` codes: `lead_convert_required`, `convert_target_required`, `unknown_stage`, `invalid_stages`,
  `stage_in_use`, `activity_link_required`, `invalid_sort`, `invalid_custom_fields`. `401` has no body. `404`
  means the record does not exist in the token's tenant (also for an id that is no UUID). `409` means the
  record's state does not allow the change (`lead_converted`, `lead_anonymized`, `vat_check_disabled`,
  `duplicate_lead` – the candidates in `details` –, `system_activity`, `activity_locked`, `activity_not_task`).
  `422` marks a reference to a record that does not exist, or (`lost_reason_required`) a change that is not
  possible as sent; `502` a failing upstream service (masterdata, VAT check); unexpected errors are
  `500 internal`.
- `owner` filters take an e-mail address or `me` (the calling person).
- `PUT` on leads, opportunities and campaigns is a partial update: only the fields you send
  change. `null` counts as not sent, so a field cannot be cleared with `null`; send an empty
  string to empty a text field. An update applies the fields sent to the record as it is at
  that moment (the record is locked for the change), so simultaneous updates of different
  fields all stay; for the same field the last write wins.
- IDs are UUIDs. Timestamps are RFC 3339 in UTC; amounts are decimals with two places.
- Requests are not idempotent: retrying a `POST` creates another record – except `importLeads` and
  `sendContactMail`, which take an `Idempotency-Key`.

## Events
Changes are written to the module's transactional outbox, which other ConnectCloud modules
read. CRM sends no webhooks itself: `crm.lead.created|updated|assigned|converted`,
`crm.opportunity.created|updated|won|lost`, `crm.activity.created`, `crm.task.assigned|completed` and
`crm.csat.created` are flow events (`x-flows-events`, guide „Flows“) – a flow with an `event` trigger can forward
them to a webhook channel (guide „Webhooks“); the others are only on the outbox feed.
`crm.lead.created|updated|converted|deleted`, `crm.opportunity.created|updated|deleted`,
`crm.campaign.created|updated|deleted`, `crm.csat.created`, `crm.lead.assigned|anonymized`,
`crm.opportunity.won|lost`, `crm.activity.created|updated|deleted`,
`crm.task.assigned|completed|reopened`, `crm.stages.updated`. Payloads carry the record id
(`leadId`, `opportunityId`, `campaignId`, `csatId`, `activityId`) and the changed key fields (status,
stage, score, value, …).
`crm.lead.assigned` (`leadId`, `ownerEmail`), `crm.task.assigned` (`activityId`, `assigneeEmail`, `dueAt`, the
linked ids) and `crm.opportunity.won|lost` (`opportunityId`, `stage`, `value`, `ownerEmail`, `leadId`, `addressId`)
are offered to personal subscriptions in comms (group „Vertrieb“); they carry ids and
employee e-mails only.

# Leads

## List leads (tenant:crm:read)

`GET /api/crm/v1/leads`

Module: CRM · operationId: `listLeads` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `status` | query | LeadStatus |  | (one of `NEW`, `CONTACTED`, `QUALIFIED`, `LOST`, `CONVERTED`) |
| `addressId` | query | string (uuid) |  | Only leads converted to this masterdata address. |
| `search` | query | string |  | Substring of company, contact name, email, phone, website or VAT ID; ignores case and accents (`Muller` finds `Müller`). (max length 255) |
| `campaignId` | query | string (uuid) |  | Only leads of this campaign. |
| `owner` | query | string |  | Only records of this owner (e-mail address), or `me` for the calling person. (max length 255) |
| `consent` | query | boolean |  | Only leads with (`true`) or without (`false`) GDPR consent. |
| `sort` | query | string |  | Sort order: a field for ascending, `-field` for descending. Fields: createdAt, updatedAt, company, contactName, score, status. Default `-createdAt`. Unknown values answer `400` (`invalid_sort`). (max length 32) |
| `limit` | query | integer |  | Page size, 1–200 (default 50); any other value is `400 invalid`. (default `50`; max 200) |
| `cursor` | query | string |  | `nextCursor` of the previous page; leave out for the first page. Keep `sort` and the filters unchanged while paging: a cursor of another sort or an altered one is `400 invalid` (`field: cursor`). (max length 1024) |

### Responses

- **200** A page of leads and the total number of matching leads (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of Lead, required): One page of leads.
  - `company` (string, required): Company name.
  - `contactName` (string, required): Name of the contact person.
  - `createdAt` (string (date-time), required): Creation time.
  - `customerNo` (string, required): Customer number of the tenant.
  - `id` (string (uuid), required): Id of the lead.
  - `score` (integer, required): Lead score 0–100. (max 100)
  - `source` (string, required): Free text. The portal offers the codes `MANUAL`, `WEBSITE`, `FAIR`, `IMPORT`, `REFERRAL`, `CAMPAIGN`, `PHONE` and `OTHER`; these are stored in upper case (`import` becomes `IMPORT`), any other value is kept as written. A CSV import without a source column writes `IMPORT`.
  - `status` (LeadStatus, required): (one of `NEW`, `CONTACTED`, `QUALIFIED`, `LOST`, `CONVERTED`)
  - `tenantName` (string, required): Tenant name.
  - `updatedAt` (string (date-time), required): Time of the last change.
  - `anonymizedAt` (string (date-time), read-only): Set when the retention job removed the personal data; omitted otherwise.
  - `campaignId` (string (uuid)): Campaign the lead comes from; omitted when not set.
  - `consent` (boolean): GDPR consent to be contacted.
  - `consentAt` (string (date-time), read-only): Set by the server when `consent` turns true.
  - `consentSource` (string): Where the consent was given; omitted when not set.
  - `convertedAddressId` (string (uuid)): Masterdata address after conversion; omitted before.
  - `customFields` (object): Values of the tenant's lead fields by field key (`CRMSettings.customFields.lead`).
  - `email` (string): Omitted when not set.
  - `marketingOptOut` (boolean): The person objected to marketing.
  - `notes` (string): Omitted when not set.
  - `ownerEmail` (string): Employee responsible for the lead (lower-case e-mail); omitted when not set.
  - `phone` (string): Omitted when not set.
  - `vatCheckedAt` (string (date-time), read-only): Time of that check.
  - `vatId` (string): Omitted when not set.
  - `vatStatus` (string, read-only): Status of the last `validateVatId` with this lead (see its `status` values); omitted before.
  - `website` (string): Omitted when not set.
- `total` (integer, required): Number of all records matching the filters.
- `nextCursor` (string): Cursor of the next page (pass it as `cursor`); missing on the last page.

Example 200 answer:

```json
{
  "items": [
    {
      "campaignId": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
      "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
      "consent": true,
      "consentAt": "2026-07-19T15:40:00Z",
      "consentSource": "Visitenkarte am Messestand",
      "contactName": "Eva Gaßner",
      "createdAt": "2026-07-19T15:40:00Z",
      "customFields": {
        "branche": "gastronomie",
        "mitarbeitende": 45
      },
      "customerNo": "99999",
      "email": "eva.gassner@brauerei-gassner.example",
      "id": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
      "marketingOptOut": false,
      "notes": "Hat am Messestand nach WLAN für Sudhaus und Lager gefragt. Termin vor Ort hat stattgefunden, Angebot in Arbeit.",
      "ownerEmail": "lena.vogel@muster-it.example",
      "phone": "+49 9441 50070",
      "score": 80,
      "source": "FAIR",
      "status": "QUALIFIED",
      "tenantName": "DEMO",
      "updatedAt": "2026-10-28T10:20:00Z",
      "vatCheckedAt": "2026-10-28T10:02:14Z",
      "vatId": "DE999000231",
      "vatStatus": "OFFICIALLY_CONFIRMED",
      "website": "https://www.brauerei-gassner.example"
    }
  ],
  "total": 1
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/leads' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Create a lead (tenant:crm:write)

`POST /api/crm/v1/leads`

Module: CRM · operationId: `createLead` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

The lead starts with status `NEW`. Without `source` it is the tenant's `defaultLeadSource`
(else `MANUAL`); without `ownerEmail` the owner is the calling person; without `score` it is
calculated (lead scoring, see Model). `customFields` are validated against the tenant's
definitions (`400`, `invalid_custom_fields`). Leads with the same normalised company name or the
same e-mail address (also masterdata addresses) are duplicates: the answer is `409`
(`code: duplicate_lead`, `candidates`, `masterdataUnavailable`) unless `force` is `true`.
Emits `crm.lead.created` (and `crm.lead.assigned` for an owner other than the caller).

### Request body

`application/json` (required)

- `company` (string, required): Company name. (max length 255)
- `contactName` (string, required): Name of the contact person. (max length 255)
- `campaignId` (string (uuid)): A campaign of the tenant (`422` otherwise).
- `consent` (boolean): GDPR consent to be contacted.
- `consentSource` (string): Where the consent was given. (max length 255)
- `customFields` (object): Values by field key; validated against the tenant's definitions (`400`, `invalid_custom_fields`).
- `email` (string (email)): E-mail address. (max length 255)
- `force` (boolean): Create the lead although duplicates were found (otherwise `409`, `duplicate_lead`). (default `false`)
- `marketingOptOut` (boolean): The person objected to marketing.
- `notes` (string): Notes. (max length 10000)
- `ownerEmail` (string (email)): Default: the calling person. (max length 255)
- `phone` (string): Phone number. (max length 64)
- `score` (integer): Default is the data quality score. (max 100)
- `source` (string): Default `MANUAL`. (max length 64)
- `vatId` (string): VAT ID. (max length 32)
- `website` (string): Website. (max length 512)

Example:

```json
{
  "company": "Müller Haustechnik GmbH",
  "contactName": "Sabine Müller",
  "email": "s.mueller@mueller-haustechnik.de",
  "notes": "Interesse an Wartungsvertrag für drei Standorte.",
  "phone": "+49 89 1234567",
  "source": "WEBSITE"
}
```

### Responses

- **201** Created (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **409** Leads or addresses that look like the new lead exist (`code: duplicate_lead`); repeat the request with `force: true` to create it anyway. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 201 answer:

- `company` (string, required): Company name.
- `contactName` (string, required): Name of the contact person.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the lead.
- `score` (integer, required): Lead score 0–100. (max 100)
- `source` (string, required): Free text. The portal offers the codes `MANUAL`, `WEBSITE`, `FAIR`, `IMPORT`, `REFERRAL`, `CAMPAIGN`, `PHONE` and `OTHER`; these are stored in upper case (`import` becomes `IMPORT`), any other value is kept as written. A CSV import without a source column writes `IMPORT`.
- `status` (LeadStatus, required): (one of `NEW`, `CONTACTED`, `QUALIFIED`, `LOST`, `CONVERTED`)
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `anonymizedAt` (string (date-time), read-only): Set when the retention job removed the personal data; omitted otherwise.
- `campaignId` (string (uuid)): Campaign the lead comes from; omitted when not set.
- `consent` (boolean): GDPR consent to be contacted.
- `consentAt` (string (date-time), read-only): Set by the server when `consent` turns true.
- `consentSource` (string): Where the consent was given; omitted when not set.
- `convertedAddressId` (string (uuid)): Masterdata address after conversion; omitted before.
- `customFields` (object): Values of the tenant's lead fields by field key (`CRMSettings.customFields.lead`).
- `email` (string): Omitted when not set.
- `marketingOptOut` (boolean): The person objected to marketing.
- `notes` (string): Omitted when not set.
- `ownerEmail` (string): Employee responsible for the lead (lower-case e-mail); omitted when not set.
- `phone` (string): Omitted when not set.
- `vatCheckedAt` (string (date-time), read-only): Time of that check.
- `vatId` (string): Omitted when not set.
- `vatStatus` (string, read-only): Status of the last `validateVatId` with this lead (see its `status` values); omitted before.
- `website` (string): Omitted when not set.

Example 201 answer:

```json
{
  "campaignId": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
  "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
  "consent": true,
  "consentAt": "2026-07-19T15:40:00Z",
  "consentSource": "Visitenkarte am Messestand",
  "contactName": "Eva Gaßner",
  "createdAt": "2026-07-19T15:40:00Z",
  "customFields": {
    "branche": "gastronomie",
    "mitarbeitende": 45
  },
  "customerNo": "99999",
  "email": "eva.gassner@brauerei-gassner.example",
  "id": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "marketingOptOut": false,
  "notes": "Hat am Messestand nach WLAN für Sudhaus und Lager gefragt. Termin vor Ort hat stattgefunden, Angebot in Arbeit.",
  "ownerEmail": "lena.vogel@muster-it.example",
  "phone": "+49 9441 50070",
  "score": 80,
  "source": "FAIR",
  "status": "QUALIFIED",
  "tenantName": "DEMO",
  "updatedAt": "2026-10-28T10:20:00Z",
  "vatCheckedAt": "2026-10-28T10:02:14Z",
  "vatId": "DE999000231",
  "vatStatus": "OFFICIALLY_CONFIRMED",
  "website": "https://www.brauerei-gassner.example"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/leads' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"company":"Müller Haustechnik GmbH","contactName":"Sabine Müller","email":"s.mueller@mueller-haustechnik.de","notes":"Interesse an Wartungsvertrag für drei Standorte.","phone":"+49 89 1234567","source":"WEBSITE"}'
```

## Find duplicates of a lead (tenant:crm:read)

`GET /api/crm/v1/leads/duplicates`

Module: CRM · operationId: `findLeadDuplicates` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

Leads and masterdata addresses with the same normalised company name or the same e-mail
address. `masterdataUnavailable` is `true` when masterdata could not be asked and only leads were
searched.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `company` | query | string |  | (max length 255) |
| `email` | query | string |  | (max length 255) |
| `excludeId` | query | string (uuid) |  | A lead to leave out (the one being edited). |

### Responses

- **200** Candidates (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `candidates` (array of DuplicateCandidate, required): Leads and addresses that look the same.
  - `company` (string, required): Company name.
  - `match` (string, required): What matched. (one of `email`, `company`)
  - `source` (string, required): `import`: an earlier row of the same import file (`id` empty, see `line`). (one of `lead`, `address`, `import`)
  - `adrNr` (string): Address number (masterdata addresses).
  - `city` (string): City (masterdata addresses).
  - `contactName` (string): Contact person (leads).
  - `email` (string): E-mail address (leads).
  - `id` (string (uuid)): Set for leads and addresses.
  - `line` (integer): Line of the earlier row (source `import`).
  - `status` (string): Lead status (leads).
- `masterdataUnavailable` (boolean, required): Only leads were searched.

Example 200 answer:

```json
{
  "candidates": [
    {
      "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
      "contactName": "Eva Gaßner",
      "email": "eva.gassner@brauerei-gassner.example",
      "id": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
      "match": "email",
      "source": "lead",
      "status": "QUALIFIED"
    },
    {
      "adrNr": "10031",
      "city": "Mallersdorf-Pfaffenberg",
      "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
      "id": "0e2a4c6e-8a1b-4d3f-9b5d-7f9b1d3f5a7b",
      "match": "company",
      "source": "address"
    }
  ],
  "masterdataUnavailable": false
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/leads/duplicates' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Import leads from a CSV file (tenant:crm:write)

`POST /api/crm/v1/leads/import`

Module: CRM · operationId: `importLeads` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

Takes a CSV file (multipart field `file`, at most 5 MB and 5000 data rows; UTF-8 with or without BOM; `;`
or `,` as delimiter, detected from the header line; the first line is the header). The file is scanned for
malware before it is read: a finding is `422` (`infected`), a scan that cannot run `503`
(`scan_unavailable`) – nothing is imported unscanned.

Columns are matched by their German or English header (case, spaces and punctuation do not matter):
`Firma`/`Company` and `Ansprechpartner`/`Contact` (both required, `400` `missing_columns` otherwise),
`E-Mail`, `Telefon`/`Phone`, `Website`, `USt-IdNr.`/`VAT ID`, `Quelle`/`Source` (default: the tenant's
`defaultLeadSource`), `Kampagne`/`Campaign` (the campaign's name), `Verantwortlich`/`Owner` (an employee
e-mail; default: the importing person), `Notizen`/`Notes`, `Einwilligung`/`Consent` (`ja`/`nein`,
`yes`/`no`, `1`/`0`, `x`) and the tenant's custom lead fields by key or label (dates as `YYYY-MM-DD` or
`DD.MM.YYYY`, several values of a multi-select separated by `|`). Other columns are listed in
`ignoredColumns`.

Every row is checked and compared like a new lead (`findLeadDuplicates`: leads with the same e-mail or
normalised company name, masterdata addresses) and with the earlier rows of the file (`duplicateOf.source`
`import` with its `line`). A row is `create`, `duplicate` (skipped unless `importDuplicates=true`; then it
is `create` and keeps `duplicateOf`) or `invalid` (`errors` name the fields).

With `dryRun=true` nothing is written. Otherwise the `create` rows are created in one transaction, each
with a `SYSTEM` activity „Lead importiert“ and the events `crm.lead.created` (with `importId`) and
`crm.lead.assigned`. A real run is stored under its `Idempotency-Key` – without one under the file's
SHA-256 hash and `importDuplicates` –: repeating it answers the stored result with `replayed: true` and
creates nothing; the same key with another file is `409` (`idempotency_key_reused`).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `dryRun` | query | boolean |  | Only check the file and answer what would happen. (default `false`) |
| `importDuplicates` | query | boolean |  | Also create the rows that look like an existing lead, address or earlier row. (default `false`) |
| `Idempotency-Key` | header | string |  | Names the import (at most 128 characters); without it the file hash does. (max length 128) |

### Request body

`multipart/form-data` (required)

- `file` (string (binary), required): The CSV file.

### Responses

- **200** The outcome per row (a dry run, the real run or the stored result of an earlier run) (`application/json`)
- **400** No file, or the file is no readable CSV (`invalid_csv`), lacks a required column (`missing_columns`) or has too many rows (`too_many_rows`). (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **413** The file is larger than 5 MB (`file_too_large`). (`application/json`)
- **422** A referenced record (lead, masterdata address) does not exist in the tenant, or the change is not
possible as sent; `code` says why (`lost_reason_required`).
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **503** The malware scan cannot run (`scan_unavailable`); nothing was imported. (`application/json`)

Fields of the 200 answer:

- `created` (integer, required): Rows that are created (dry run: would be created).
- `dryRun` (boolean, required): The file was only checked; nothing was written.
- `duplicates` (integer, required): Rows with `duplicateOf` (also those created with `importDuplicates`).
- `ignoredColumns` (array of string, required): Header names the import does not know.
- `invalid` (integer, required): Rows that cannot be imported.
- `masterdataUnavailable` (boolean, required): Masterdata could not be asked; rows were compared with leads only.
- `replayed` (boolean, required): The import ran before; this is its stored result.
- `rows` (array of LeadImportRow, required): Outcome per data row of the file.
  - `lead` (object, required): The lead the row describes; `id` is set once the real run created it.
    - `company` (string, required): Company name.
    - `consent` (boolean, required): GDPR consent to be contacted.
    - `contactName` (string, required): Name of the contact person.
    - `source` (string, required): Lead source.
    - `campaignId` (string (uuid)): Campaign of the lead.
    - `email` (string): E-mail address.
    - `id` (string (uuid)): Id of the created lead.
    - `notes` (string): Notes.
    - `ownerEmail` (string): Employee responsible for the lead.
    - `phone` (string): Phone number.
    - `vatId` (string): VAT ID.
    - `website` (string): Website.
  - `line` (integer, required): Line in the file (the header is line 1).
  - `status` (string, required): What happens to the row. (one of `create`, `duplicate`, `invalid`)
  - `duplicateOf` (DuplicateCandidate)
    - `company` (string, required): Company name.
    - `match` (string, required): What matched. (one of `email`, `company`)
    - `source` (string, required): `import`: an earlier row of the same import file (`id` empty, see `line`). (one of `lead`, `address`, `import`)
    - `adrNr` (string): Address number (masterdata addresses).
    - `city` (string): City (masterdata addresses).
    - `contactName` (string): Contact person (leads).
    - `email` (string): E-mail address (leads).
    - `id` (string (uuid)): Set for leads and addresses.
    - `line` (integer): Line of the earlier row (source `import`).
    - `status` (string): Lead status (leads).
  - `errors` (array of object): What is wrong with the row; omitted when nothing is.
    - `field` (string, required): Column the error refers to.
    - `message` (string, required): German message.
- `importId` (string (uuid)): Id of the real run (not set on a dry run).

Example 200 answer:

```json
{
  "created": 1,
  "dryRun": true,
  "duplicates": 1,
  "ignoredColumns": [
    "Bemerkung intern"
  ],
  "invalid": 1,
  "masterdataUnavailable": false,
  "replayed": false,
  "rows": [
    {
      "lead": {
        "company": "Schreinerei Wallner",
        "consent": false,
        "contactName": "Josef Wallner",
        "email": "info@schreinerei-wallner.example",
        "phone": "+49 9971 40210",
        "source": "IMPORT"
      },
      "line": 2,
      "status": "create"
    },
    {
      "duplicateOf": {
        "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
        "contactName": "Eva Gaßner",
        "email": "eva.gassner@brauerei-gassner.example",
        "id": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
        "match": "email",
        "source": "lead",
        "status": "QUALIFIED"
      },
      "lead": {
        "company": "Brauerei Gaßner",
        "consent": false,
        "contactName": "Eva Gaßner",
        "email": "eva.gassner@brauerei-gassner.example",
        "source": "IMPORT"
      },
      "line": 3,
      "status": "duplicate"
    },
    {
      "errors": [
        {
          "field": "email",
          "message": "Keine gültige E-Mail-Adresse."
        }
      ],
      "lead": {
        "company": "Autohaus Kerscher",
        "consent": false,
        "contactName": "Tobias Kerscher",
        "email": "kerscher@autohaus",
        "source": "IMPORT"
      },
      "line": 4,
      "status": "invalid"
    }
  ]
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/leads/import' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@document.pdf'
```

## Get a lead (tenant:crm:read)

`GET /api/crm/v1/leads/{id}`

Module: CRM · operationId: `getLead` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **200** The lead (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `company` (string, required): Company name.
- `contactName` (string, required): Name of the contact person.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the lead.
- `score` (integer, required): Lead score 0–100. (max 100)
- `source` (string, required): Free text. The portal offers the codes `MANUAL`, `WEBSITE`, `FAIR`, `IMPORT`, `REFERRAL`, `CAMPAIGN`, `PHONE` and `OTHER`; these are stored in upper case (`import` becomes `IMPORT`), any other value is kept as written. A CSV import without a source column writes `IMPORT`.
- `status` (LeadStatus, required): (one of `NEW`, `CONTACTED`, `QUALIFIED`, `LOST`, `CONVERTED`)
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `anonymizedAt` (string (date-time), read-only): Set when the retention job removed the personal data; omitted otherwise.
- `campaignId` (string (uuid)): Campaign the lead comes from; omitted when not set.
- `consent` (boolean): GDPR consent to be contacted.
- `consentAt` (string (date-time), read-only): Set by the server when `consent` turns true.
- `consentSource` (string): Where the consent was given; omitted when not set.
- `convertedAddressId` (string (uuid)): Masterdata address after conversion; omitted before.
- `customFields` (object): Values of the tenant's lead fields by field key (`CRMSettings.customFields.lead`).
- `email` (string): Omitted when not set.
- `marketingOptOut` (boolean): The person objected to marketing.
- `notes` (string): Omitted when not set.
- `ownerEmail` (string): Employee responsible for the lead (lower-case e-mail); omitted when not set.
- `phone` (string): Omitted when not set.
- `vatCheckedAt` (string (date-time), read-only): Time of that check.
- `vatId` (string): Omitted when not set.
- `vatStatus` (string, read-only): Status of the last `validateVatId` with this lead (see its `status` values); omitted before.
- `website` (string): Omitted when not set.

Example 200 answer:

```json
{
  "campaignId": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
  "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
  "consent": true,
  "consentAt": "2026-07-19T15:40:00Z",
  "consentSource": "Visitenkarte am Messestand",
  "contactName": "Eva Gaßner",
  "createdAt": "2026-07-19T15:40:00Z",
  "customFields": {
    "branche": "gastronomie",
    "mitarbeitende": 45
  },
  "customerNo": "99999",
  "email": "eva.gassner@brauerei-gassner.example",
  "id": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "marketingOptOut": false,
  "notes": "Hat am Messestand nach WLAN für Sudhaus und Lager gefragt. Termin vor Ort hat stattgefunden, Angebot in Arbeit.",
  "ownerEmail": "lena.vogel@muster-it.example",
  "phone": "+49 9441 50070",
  "score": 80,
  "source": "FAIR",
  "status": "QUALIFIED",
  "tenantName": "DEMO",
  "updatedAt": "2026-10-28T10:20:00Z",
  "vatCheckedAt": "2026-10-28T10:02:14Z",
  "vatId": "DE999000231",
  "vatStatus": "OFFICIALLY_CONFIRMED",
  "website": "https://www.brauerei-gassner.example"
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/leads/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Update a lead (tenant:crm:write)

`PUT /api/crm/v1/leads/{id}`

Module: CRM · operationId: `updateLead` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

Partial update: only the fields sent change. `status` may be sent unchanged (also
`CONVERTED`, as a form sends it). Setting `CONVERTED` on a lead that is not converted is
refused with `400` (`code: lead_convert_required`; use `convertLead`), changing the status of
a converted lead with `409` (`code: lead_converted`). An anonymised lead is read-only: `409`
(`code: lead_anonymized`). `ownerEmail: ""` removes the owner.
The score is recomputed when lead scoring is on and no `score` is sent. Emits `crm.lead.updated`
(and `crm.lead.assigned` when the owner changes).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Request body

`application/json` (required)

- `campaignId` (string): An empty string removes the campaign. (max length 36)
- `company` (string): Company name. (max length 255)
- `consent` (boolean): GDPR consent to be contacted.
- `consentSource` (string): Where the consent was given. (max length 255)
- `contactName` (string): Name of the contact person. (max length 255)
- `customFields` (object): Values by field key.
- `email` (string (email)): E-mail address. (max length 255)
- `marketingOptOut` (boolean): The person objected to marketing.
- `notes` (string): Notes. (max length 10000)
- `ownerEmail` (string): An empty string removes the owner. (max length 255)
- `phone` (string): Phone number. (max length 64)
- `score` (integer): Lead score 0–100. (max 100)
- `source` (string): Lead source. (max length 64)
- `status` (string): `CONVERTED` is accepted only unchanged (a converted lead keeps it); converting is `convertLead`. (one of `NEW`, `CONTACTED`, `QUALIFIED`, `LOST`, `CONVERTED`)
- `vatId` (string): VAT ID. (max length 32)
- `website` (string): Website. (max length 512)

Example:

```json
{
  "notes": "Angebot für Q1 angefragt.",
  "score": 80,
  "status": "QUALIFIED"
}
```

### Responses

- **200** The updated lead (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `company` (string, required): Company name.
- `contactName` (string, required): Name of the contact person.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the lead.
- `score` (integer, required): Lead score 0–100. (max 100)
- `source` (string, required): Free text. The portal offers the codes `MANUAL`, `WEBSITE`, `FAIR`, `IMPORT`, `REFERRAL`, `CAMPAIGN`, `PHONE` and `OTHER`; these are stored in upper case (`import` becomes `IMPORT`), any other value is kept as written. A CSV import without a source column writes `IMPORT`.
- `status` (LeadStatus, required): (one of `NEW`, `CONTACTED`, `QUALIFIED`, `LOST`, `CONVERTED`)
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `anonymizedAt` (string (date-time), read-only): Set when the retention job removed the personal data; omitted otherwise.
- `campaignId` (string (uuid)): Campaign the lead comes from; omitted when not set.
- `consent` (boolean): GDPR consent to be contacted.
- `consentAt` (string (date-time), read-only): Set by the server when `consent` turns true.
- `consentSource` (string): Where the consent was given; omitted when not set.
- `convertedAddressId` (string (uuid)): Masterdata address after conversion; omitted before.
- `customFields` (object): Values of the tenant's lead fields by field key (`CRMSettings.customFields.lead`).
- `email` (string): Omitted when not set.
- `marketingOptOut` (boolean): The person objected to marketing.
- `notes` (string): Omitted when not set.
- `ownerEmail` (string): Employee responsible for the lead (lower-case e-mail); omitted when not set.
- `phone` (string): Omitted when not set.
- `vatCheckedAt` (string (date-time), read-only): Time of that check.
- `vatId` (string): Omitted when not set.
- `vatStatus` (string, read-only): Status of the last `validateVatId` with this lead (see its `status` values); omitted before.
- `website` (string): Omitted when not set.

Example 200 answer:

```json
{
  "campaignId": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
  "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
  "consent": true,
  "consentAt": "2026-07-19T15:40:00Z",
  "consentSource": "Visitenkarte am Messestand",
  "contactName": "Eva Gaßner",
  "createdAt": "2026-07-19T15:40:00Z",
  "customFields": {
    "branche": "gastronomie",
    "mitarbeitende": 45
  },
  "customerNo": "99999",
  "email": "eva.gassner@brauerei-gassner.example",
  "id": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "marketingOptOut": false,
  "notes": "Hat am Messestand nach WLAN für Sudhaus und Lager gefragt. Termin vor Ort hat stattgefunden, Angebot in Arbeit.",
  "ownerEmail": "lena.vogel@muster-it.example",
  "phone": "+49 9441 50070",
  "score": 80,
  "source": "FAIR",
  "status": "QUALIFIED",
  "tenantName": "DEMO",
  "updatedAt": "2026-10-28T10:20:00Z",
  "vatCheckedAt": "2026-10-28T10:02:14Z",
  "vatId": "DE999000231",
  "vatStatus": "OFFICIALLY_CONFIRMED",
  "website": "https://www.brauerei-gassner.example"
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/leads/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"notes":"Angebot für Q1 angefragt.","score":80,"status":"QUALIFIED"}'
```

## Delete a lead (tenant:crm:write)

`DELETE /api/crm/v1/leads/{id}`

Module: CRM · operationId: `deleteLead` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

Deletes the lead permanently. Opportunities referencing it stay, without `leadId`. Emits `crm.lead.deleted`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **204** Deleted
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

### Example request

```bash
curl -X DELETE 'https://api.mbcom.cloud/api/crm/v1/leads/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Convert a lead into a customer (tenant:crm:write)

`POST /api/crm/v1/leads/{id}/convert`

Module: CRM · operationId: `convertLead` · Tag: Leads · Auth: access token (`Authorization: Bearer <accessToken>`)

Links the lead to a masterdata address of the same tenant and sets its status to
`CONVERTED`. Send exactly one of `addressId` (an existing address, checked with the masterdata
module) or `createAddress` (masterdata creates the company address with status `INTERESSENT`,
the lead's contact as contact person; once per lead, a retry reuses the address); otherwise `400`
(`code: convert_target_required`). `opportunity` creates a first opportunity of the lead and
address; it is checked before masterdata is called, so a refusal creates no address: a `stageKey` that is no
active stage of the tenant returns `400` (`code: unknown_stage`, field `opportunity.stageKey`), an invalid
custom field `400` with the field `opportunity.customFields.<key>`.
An unknown address returns `422`, an unreachable masterdata module `502`. A lead that is already converted
returns `409` (`code: lead_converted`), also when two conversions run at the same time; an anonymised lead
returns `409` (`code: lead_anonymized`).
Emits `crm.lead.converted` (and `crm.opportunity.created`).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Request body

`application/json` (required)

- `addressId` (string (uuid)): Existing masterdata address of the tenant.
- `createAddress` (ConvertAddress): The company address masterdata creates (status `INTERESSENT`, external key `crm_lead`).
  - `companyName` (string, required): Company name of the new address. (max length 255)
  - `city` (string): City. (max length 128)
  - `country` (string): ISO 3166-1 alpha-2. (max length 2)
  - `email` (string (email)): E-mail address. (max length 255)
  - `phone` (string): Phone number. (max length 64)
  - `street` (string): Street with house number. (max length 255)
  - `vatId` (string): VAT ID. (max length 32)
  - `website` (string): Website. (max length 512)
  - `zip` (string): Postal code. (max length 16)
- `opportunity` (ConvertOpportunity): The first opportunity created with the conversion (linked to the lead and the address).
  - `title` (string, required): Title of the opportunity. (max length 255)
  - `customFields` (object): Values of the tenant's opportunity fields by key; validated against the definitions before the address is created, a missing required field is `400` (`opportunity.customFields.<key>`) and creates nothing.
  - `expectedCloseDate` (string (date-time)): Expected close date.
  - `stageKey` (string): Active stage; default the first open stage. (max length 64)
  - `value` (number (double)): Expected value. (max 9999999999)

Example:

```json
{
  "createAddress": {
    "city": "Mallersdorf-Pfaffenberg",
    "companyName": "Brauerei Gaßner GmbH \u0026 Co. KG",
    "country": "DE",
    "email": "eva.gassner@brauerei-gassner.example",
    "phone": "+49 9441 50070",
    "street": "Brauhausstraße 4",
    "vatId": "DE999000231",
    "website": "https://www.brauerei-gassner.example",
    "zip": "84066"
  },
  "opportunity": {
    "expectedCloseDate": "2026-12-15T00:00:00Z",
    "stageKey": "PROPOSAL",
    "title": "WLAN Sudhaus und Lager",
    "value": 18400
  }
}
```

### Responses

- **200** The converted lead; `opportunity` is the opportunity created with it. (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **422** A referenced record (lead, masterdata address) does not exist in the tenant, or the change is not
possible as sent; `code` says why (`lost_reason_required`).
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **502** An upstream service (masterdata, VAT check) failed, is switched off or is not configured. (`application/json`)

Fields of the 200 answer:

- `company` (string, required): Company name.
- `contactName` (string, required): Name of the contact person.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the lead.
- `score` (integer, required): Lead score 0–100. (max 100)
- `source` (string, required): Free text. The portal offers the codes `MANUAL`, `WEBSITE`, `FAIR`, `IMPORT`, `REFERRAL`, `CAMPAIGN`, `PHONE` and `OTHER`; these are stored in upper case (`import` becomes `IMPORT`), any other value is kept as written. A CSV import without a source column writes `IMPORT`.
- `status` (LeadStatus, required): (one of `NEW`, `CONTACTED`, `QUALIFIED`, `LOST`, `CONVERTED`)
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `anonymizedAt` (string (date-time), read-only): Set when the retention job removed the personal data; omitted otherwise.
- `campaignId` (string (uuid)): Campaign the lead comes from; omitted when not set.
- `consent` (boolean): GDPR consent to be contacted.
- `consentAt` (string (date-time), read-only): Set by the server when `consent` turns true.
- `consentSource` (string): Where the consent was given; omitted when not set.
- `convertedAddressId` (string (uuid)): Masterdata address after conversion; omitted before.
- `customFields` (object): Values of the tenant's lead fields by field key (`CRMSettings.customFields.lead`).
- `email` (string): Omitted when not set.
- `marketingOptOut` (boolean): The person objected to marketing.
- `notes` (string): Omitted when not set.
- `ownerEmail` (string): Employee responsible for the lead (lower-case e-mail); omitted when not set.
- `phone` (string): Omitted when not set.
- `vatCheckedAt` (string (date-time), read-only): Time of that check.
- `vatId` (string): Omitted when not set.
- `vatStatus` (string, read-only): Status of the last `validateVatId` with this lead (see its `status` values); omitted before.
- `website` (string): Omitted when not set.
- `opportunity` (Opportunity)
  - `createdAt` (string (date-time), required): Creation time.
  - `customerNo` (string, required): Customer number of the tenant.
  - `id` (string (uuid), required): Id of the opportunity.
  - `probability` (integer, required): Win probability in percent. (max 100)
  - `stage` (OpportunityStage, required): Key of a stage of the tenant (`listStages`). The defaults are `PROSPECTING`, `QUALIFICATION`, `PROPOSAL`, `NEGOTIATION`, `CLOSED_WON` and `CLOSED_LOST`. (max length 64)
  - `tenantName` (string, required): Tenant name.
  - `title` (string, required): Title of the opportunity.
  - `updatedAt` (string (date-time), required): Time of the last change.
  - `value` (number (double), required): Expected value.
  - `addressId` (string (uuid)): Masterdata address; omitted when not set.
  - `closedAt` (string (date-time), read-only): Set by the server when the opportunity enters a won or lost stage, cleared when it leaves.
  - `customFields` (object): Values of the tenant's opportunity fields by field key.
  - `expectedCloseDate` (string (date-time)): Omitted when not set.
  - `leadId` (string (uuid)): Omitted when not set.
  - `lostReason` (string): Required in a lost stage, cleared when the opportunity leaves it; omitted when not set.
  - `notes` (string): Omitted when not set.
  - `ownerEmail` (string): Employee responsible for the opportunity; omitted when not set.

Example 200 answer:

```json
{
  "company": "Brauerei Gaßner GmbH \u0026 Co. KG",
  "consent": true,
  "contactName": "Eva Gaßner",
  "convertedAddressId": "0e2a4c6e-8a1b-4d3f-9b5d-7f9b1d3f5a7b",
  "createdAt": "2026-07-19T15:40:00Z",
  "customerNo": "99999",
  "email": "eva.gassner@brauerei-gassner.example",
  "id": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "marketingOptOut": false,
  "opportunity": {
    "addressId": "0e2a4c6e-8a1b-4d3f-9b5d-7f9b1d3f5a7b",
    "createdAt": "2026-11-04T09:15:00Z",
    "customFields": {
      "budget-freigegeben": true,
      "entscheider": "Eva Gaßner"
    },
    "customerNo": "99999",
    "expectedCloseDate": "2026-12-15T00:00:00Z",
    "id": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
    "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
    "notes": "Acht Access Points, Controller und Ausleuchtung; Montage in der Betriebspause.",
    "ownerEmail": "lena.vogel@muster-it.example",
    "probability": 50,
    "stage": "PROPOSAL",
    "tenantName": "DEMO",
    "title": "WLAN Sudhaus und Lager",
    "updatedAt": "2026-11-12T16:40:00Z",
    "value": 18400
  },
  "ownerEmail": "lena.vogel@muster-it.example",
  "phone": "+49 9441 50070",
  "score": 80,
  "source": "FAIR",
  "status": "CONVERTED",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-04T09:15:00Z"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/leads/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12/convert' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"createAddress":{"city":"Mallersdorf-Pfaffenberg","companyName":"Brauerei Gaßner GmbH \u0026 Co. KG","country":"DE","email":"eva.gassner@brauerei-gassner.example","phone":"+49 9441 50070","street":"Brauhausstraße 4","vatId":"DE999000231","website":"https://www.brauerei-gassner.example","zip":"84066"},"opportunity":{"expectedCloseDate":"2026-12-15T00:00:00Z","stageKey":"PROPOSAL","title":"WLAN Sudhaus und Lager","value":18400}}'
```

# Opportunities

## List opportunities (tenant:crm:read)

`GET /api/crm/v1/opportunities`

Module: CRM · operationId: `listOpportunities` · Tag: Opportunities · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `stage` | query | string |  | Only opportunities in this stage (key, see `listStages`). (max length 64) |
| `phase` | query | string |  | Only opportunities in a stage of this phase. (one of `open`, `won`, `lost`) |
| `addressId` | query | string (uuid) |  | Only opportunities for this masterdata address. |
| `leadId` | query | string (uuid) |  | Only opportunities of this lead. |
| `owner` | query | string |  | Only records of this owner (e-mail address), or `me` for the calling person. (max length 255) |
| `closeFrom` | query | string (date-time) |  | Only opportunities closed (`closedAt`) at or after this time (RFC 3339). |
| `closeTo` | query | string (date-time) |  | Only opportunities closed (`closedAt`) before this time (RFC 3339). |
| `search` | query | string |  | Case-insensitive substring of title or notes. (max length 255) |
| `sort` | query | string |  | Sort order: a field for ascending, `-field` for descending. Fields: createdAt, updatedAt, title, value, probability, expectedCloseDate, closedAt, stage. Default `-createdAt`. Unknown values answer `400` (`invalid_sort`). (max length 32) |
| `limit` | query | integer |  | Page size, 1–200 (default 50); any other value is `400 invalid`. (default `50`; max 200) |
| `cursor` | query | string |  | `nextCursor` of the previous page; leave out for the first page. Keep `sort` and the filters unchanged while paging: a cursor of another sort or an altered one is `400 invalid` (`field: cursor`). (max length 1024) |

### Responses

- **200** A page of opportunities and the total number of matching opportunities (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of Opportunity, required): One page of opportunities.
  - `createdAt` (string (date-time), required): Creation time.
  - `customerNo` (string, required): Customer number of the tenant.
  - `id` (string (uuid), required): Id of the opportunity.
  - `probability` (integer, required): Win probability in percent. (max 100)
  - `stage` (OpportunityStage, required): Key of a stage of the tenant (`listStages`). The defaults are `PROSPECTING`, `QUALIFICATION`, `PROPOSAL`, `NEGOTIATION`, `CLOSED_WON` and `CLOSED_LOST`. (max length 64)
  - `tenantName` (string, required): Tenant name.
  - `title` (string, required): Title of the opportunity.
  - `updatedAt` (string (date-time), required): Time of the last change.
  - `value` (number (double), required): Expected value.
  - `addressId` (string (uuid)): Masterdata address; omitted when not set.
  - `closedAt` (string (date-time), read-only): Set by the server when the opportunity enters a won or lost stage, cleared when it leaves.
  - `customFields` (object): Values of the tenant's opportunity fields by field key.
  - `expectedCloseDate` (string (date-time)): Omitted when not set.
  - `leadId` (string (uuid)): Omitted when not set.
  - `lostReason` (string): Required in a lost stage, cleared when the opportunity leaves it; omitted when not set.
  - `notes` (string): Omitted when not set.
  - `ownerEmail` (string): Employee responsible for the opportunity; omitted when not set.
- `total` (integer, required): Number of all records matching the filters.
- `nextCursor` (string): Cursor of the next page (pass it as `cursor`); missing on the last page.

Example 200 answer:

```json
{
  "items": [
    {
      "addressId": "0e2a4c6e-8a1b-4d3f-9b5d-7f9b1d3f5a7b",
      "createdAt": "2026-11-04T09:15:00Z",
      "customFields": {
        "budget-freigegeben": true,
        "entscheider": "Eva Gaßner"
      },
      "customerNo": "99999",
      "expectedCloseDate": "2026-12-15T00:00:00Z",
      "id": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
      "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
      "notes": "Acht Access Points, Controller und Ausleuchtung; Montage in der Betriebspause.",
      "ownerEmail": "lena.vogel@muster-it.example",
      "probability": 50,
      "stage": "PROPOSAL",
      "tenantName": "DEMO",
      "title": "WLAN Sudhaus und Lager",
      "updatedAt": "2026-11-12T16:40:00Z",
      "value": 18400
    }
  ],
  "total": 1
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/opportunities' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Create an opportunity (tenant:crm:write)

`POST /api/crm/v1/opportunities`

Module: CRM · operationId: `createOpportunity` · Tag: Opportunities · Auth: access token (`Authorization: Bearer <accessToken>`)

Defaults are the first open stage, the stage's probability, value `0` and the calling person as
owner. `stage` must be an active stage of the tenant (`400`, `unknown_stage`); a lost stage needs
`lostReason` (`422`, `lost_reason_required`). A `leadId` must name a lead
of the tenant, an `addressId` a masterdata address of the tenant (`422` otherwise, `502` when
masterdata is unreachable). `customFields` are validated against the tenant's definitions.
Emits `crm.opportunity.created` (and `crm.opportunity.won` / `crm.opportunity.lost` for a closed stage).

### Request body

`application/json` (required)

- `title` (string, required): Title of the opportunity. (max length 255)
- `addressId` (string (uuid)): A masterdata address of the tenant (`422` otherwise).
- `customFields` (object): Values by field key; validated against the tenant's definitions.
- `expectedCloseDate` (string (date-time)): Expected close date.
- `leadId` (string (uuid)): A lead of the tenant (`422` otherwise).
- `lostReason` (string): Required when the stage is a lost stage (`422`, `lost_reason_required`). (max length 2000)
- `notes` (string): Notes. (max length 10000)
- `ownerEmail` (string): Default: the calling person. (max length 255)
- `probability` (integer): Default: the stage's probability. (max 100)
- `stage` (object): An active stage of the tenant; default the first open stage (`400`, `unknown_stage`).
- `value` (number (double)): Default 0. (max 9999999999)

Example:

```json
{
  "expectedCloseDate": "2026-12-15T00:00:00Z",
  "leadId": "3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12",
  "probability": 40,
  "stage": "PROPOSAL",
  "title": "Wartungsvertrag Standorte Süd",
  "value": 24500
}
```

### Responses

- **201** Created (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **422** A referenced record (lead, masterdata address) does not exist in the tenant, or the change is not
possible as sent; `code` says why (`lost_reason_required`).
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **502** An upstream service (masterdata, VAT check) failed, is switched off or is not configured. (`application/json`)

Fields of the 201 answer:

- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the opportunity.
- `probability` (integer, required): Win probability in percent. (max 100)
- `stage` (OpportunityStage, required): Key of a stage of the tenant (`listStages`). The defaults are `PROSPECTING`, `QUALIFICATION`, `PROPOSAL`, `NEGOTIATION`, `CLOSED_WON` and `CLOSED_LOST`. (max length 64)
- `tenantName` (string, required): Tenant name.
- `title` (string, required): Title of the opportunity.
- `updatedAt` (string (date-time), required): Time of the last change.
- `value` (number (double), required): Expected value.
- `addressId` (string (uuid)): Masterdata address; omitted when not set.
- `closedAt` (string (date-time), read-only): Set by the server when the opportunity enters a won or lost stage, cleared when it leaves.
- `customFields` (object): Values of the tenant's opportunity fields by field key.
- `expectedCloseDate` (string (date-time)): Omitted when not set.
- `leadId` (string (uuid)): Omitted when not set.
- `lostReason` (string): Required in a lost stage, cleared when the opportunity leaves it; omitted when not set.
- `notes` (string): Omitted when not set.
- `ownerEmail` (string): Employee responsible for the opportunity; omitted when not set.

Example 201 answer:

```json
{
  "addressId": "0e2a4c6e-8a1b-4d3f-9b5d-7f9b1d3f5a7b",
  "createdAt": "2026-11-04T09:15:00Z",
  "customFields": {
    "budget-freigegeben": true,
    "entscheider": "Eva Gaßner"
  },
  "customerNo": "99999",
  "expectedCloseDate": "2026-12-15T00:00:00Z",
  "id": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "notes": "Acht Access Points, Controller und Ausleuchtung; Montage in der Betriebspause.",
  "ownerEmail": "lena.vogel@muster-it.example",
  "probability": 50,
  "stage": "PROPOSAL",
  "tenantName": "DEMO",
  "title": "WLAN Sudhaus und Lager",
  "updatedAt": "2026-11-12T16:40:00Z",
  "value": 18400
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/opportunities' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"expectedCloseDate":"2026-12-15T00:00:00Z","leadId":"3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12","probability":40,"stage":"PROPOSAL","title":"Wartungsvertrag Standorte Süd","value":24500}'
```

## Get an opportunity (tenant:crm:read)

`GET /api/crm/v1/opportunities/{id}`

Module: CRM · operationId: `getOpportunity` · Tag: Opportunities · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **200** The opportunity (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the opportunity.
- `probability` (integer, required): Win probability in percent. (max 100)
- `stage` (OpportunityStage, required): Key of a stage of the tenant (`listStages`). The defaults are `PROSPECTING`, `QUALIFICATION`, `PROPOSAL`, `NEGOTIATION`, `CLOSED_WON` and `CLOSED_LOST`. (max length 64)
- `tenantName` (string, required): Tenant name.
- `title` (string, required): Title of the opportunity.
- `updatedAt` (string (date-time), required): Time of the last change.
- `value` (number (double), required): Expected value.
- `addressId` (string (uuid)): Masterdata address; omitted when not set.
- `closedAt` (string (date-time), read-only): Set by the server when the opportunity enters a won or lost stage, cleared when it leaves.
- `customFields` (object): Values of the tenant's opportunity fields by field key.
- `expectedCloseDate` (string (date-time)): Omitted when not set.
- `leadId` (string (uuid)): Omitted when not set.
- `lostReason` (string): Required in a lost stage, cleared when the opportunity leaves it; omitted when not set.
- `notes` (string): Omitted when not set.
- `ownerEmail` (string): Employee responsible for the opportunity; omitted when not set.

Example 200 answer:

```json
{
  "addressId": "0e2a4c6e-8a1b-4d3f-9b5d-7f9b1d3f5a7b",
  "createdAt": "2026-11-04T09:15:00Z",
  "customFields": {
    "budget-freigegeben": true,
    "entscheider": "Eva Gaßner"
  },
  "customerNo": "99999",
  "expectedCloseDate": "2026-12-15T00:00:00Z",
  "id": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "notes": "Acht Access Points, Controller und Ausleuchtung; Montage in der Betriebspause.",
  "ownerEmail": "lena.vogel@muster-it.example",
  "probability": 50,
  "stage": "PROPOSAL",
  "tenantName": "DEMO",
  "title": "WLAN Sudhaus und Lager",
  "updatedAt": "2026-11-12T16:40:00Z",
  "value": 18400
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/opportunities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Update an opportunity (tenant:crm:write)

`PUT /api/crm/v1/opportunities/{id}`

Module: CRM · operationId: `updateOpportunity` · Tag: Opportunities · Auth: access token (`Authorization: Bearer <accessToken>`)

Partial update; only the fields sent change. A changed `leadId` or `addressId` is checked
like on create (`422`, `502`). Changing `stage` follows the rules of the stage (`400`
`unknown_stage`, `422` `lost_reason_required`); `closedAt` is set when a won or lost stage is
entered and cleared when it is left, a stage change without `probability` takes the stage's
probability and writes a `SYSTEM` activity. Emits `crm.opportunity.updated`, `crm.opportunity.won`
or `crm.opportunity.lost` when it enters such a stage.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Request body

`application/json` (required)

- `addressId` (string (uuid)): A masterdata address of the tenant (`422` otherwise).
- `customFields` (object): Values by field key; validated against the tenant's definitions.
- `expectedCloseDate` (string (date-time)): Expected close date.
- `leadId` (string (uuid)): A lead of the tenant (`422` otherwise).
- `lostReason` (string): Required when the stage is a lost stage. (max length 2000)
- `notes` (string): Notes. (max length 10000)
- `ownerEmail` (string): An empty string removes the owner. (max length 255)
- `probability` (integer): Win probability in percent. (max 100)
- `stage` (OpportunityStage): Key of a stage of the tenant (`listStages`). The defaults are `PROSPECTING`, `QUALIFICATION`, `PROPOSAL`, `NEGOTIATION`, `CLOSED_WON` and `CLOSED_LOST`. (max length 64)
- `title` (string): Title of the opportunity. (max length 255)
- `value` (number (double)): Expected value. (max 9999999999)

Example:

```json
{
  "probability": 100,
  "stage": "CLOSED_WON"
}
```

### Responses

- **200** The updated opportunity (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **422** A referenced record (lead, masterdata address) does not exist in the tenant, or the change is not
possible as sent; `code` says why (`lost_reason_required`).
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **502** An upstream service (masterdata, VAT check) failed, is switched off or is not configured. (`application/json`)

Fields of the 200 answer:

- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the opportunity.
- `probability` (integer, required): Win probability in percent. (max 100)
- `stage` (OpportunityStage, required): Key of a stage of the tenant (`listStages`). The defaults are `PROSPECTING`, `QUALIFICATION`, `PROPOSAL`, `NEGOTIATION`, `CLOSED_WON` and `CLOSED_LOST`. (max length 64)
- `tenantName` (string, required): Tenant name.
- `title` (string, required): Title of the opportunity.
- `updatedAt` (string (date-time), required): Time of the last change.
- `value` (number (double), required): Expected value.
- `addressId` (string (uuid)): Masterdata address; omitted when not set.
- `closedAt` (string (date-time), read-only): Set by the server when the opportunity enters a won or lost stage, cleared when it leaves.
- `customFields` (object): Values of the tenant's opportunity fields by field key.
- `expectedCloseDate` (string (date-time)): Omitted when not set.
- `leadId` (string (uuid)): Omitted when not set.
- `lostReason` (string): Required in a lost stage, cleared when the opportunity leaves it; omitted when not set.
- `notes` (string): Omitted when not set.
- `ownerEmail` (string): Employee responsible for the opportunity; omitted when not set.

Example 200 answer:

```json
{
  "addressId": "0e2a4c6e-8a1b-4d3f-9b5d-7f9b1d3f5a7b",
  "createdAt": "2026-11-04T09:15:00Z",
  "customFields": {
    "budget-freigegeben": true,
    "entscheider": "Eva Gaßner"
  },
  "customerNo": "99999",
  "expectedCloseDate": "2026-12-15T00:00:00Z",
  "id": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "notes": "Acht Access Points, Controller und Ausleuchtung; Montage in der Betriebspause.",
  "ownerEmail": "lena.vogel@muster-it.example",
  "probability": 50,
  "stage": "PROPOSAL",
  "tenantName": "DEMO",
  "title": "WLAN Sudhaus und Lager",
  "updatedAt": "2026-11-12T16:40:00Z",
  "value": 18400
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/opportunities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"probability":100,"stage":"CLOSED_WON"}'
```

## Delete an opportunity (tenant:crm:write)

`DELETE /api/crm/v1/opportunities/{id}`

Module: CRM · operationId: `deleteOpportunity` · Tag: Opportunities · Auth: access token (`Authorization: Bearer <accessToken>`)

Deletes the opportunity permanently. Emits `crm.opportunity.deleted`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **204** Deleted
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

### Example request

```bash
curl -X DELETE 'https://api.mbcom.cloud/api/crm/v1/opportunities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## List the sales documents of an opportunity (tenant:crm:read)

`GET /api/crm/v1/opportunities/{id}/documents`

Module: CRM · operationId: `listOpportunityDocuments` · Tag: Opportunities · Auth: access token (`Authorization: Bearer <accessToken>`)

The trade documents (offers, orders and the documents made from them) that name the opportunity
(`opportunityId` in trade), as the CRM keeps them from trade's event feed – newest change first, every
revision on its own. A deleted document disappears. The CRM reacts to them: a new offer or order is a
`SYSTEM` activity of the opportunity; an offer that becomes `ACCEPTED` or a new order moves an open
opportunity to the tenant's first won stage (`crm.opportunity.won`); an offer that becomes `REJECTED`,
`EXPIRED` or `REVOKED` is only noted (a person decides whether the opportunity is lost). Read the
documents themselves through the trade API (`transactionId`).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **200** The documents (all of them; no paging). (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of OpportunityDocument, required): Documents of the opportunity.
  - `createdAt` (string (date-time), required): When the CRM first saw the document.
  - `netTotal` (number (double), required): Net total of the document.
  - `number` (string, required): Document number in trade.
  - `opportunityId` (string (uuid), required): The opportunity the document names.
  - `status` (string, required): Status in trade, e.g. `DRAFT`, `SENT`, `ACCEPTED`, `REJECTED`, `EXPIRED`, `REVOKED`, `CONFIRMED`.
  - `transactionId` (string (uuid), required): Id of the document in trade.
  - `type` (string, required): Trade document type, e.g. `OFFER`, `ORDER`, `DELIVERY_NOTE`, `INVOICE`.
  - `updatedAt` (string (date-time), required): Last change the CRM saw.
  - `version` (integer, required): Revision of the document (each revision is its own document).
  - `sourceTransactionId` (string (uuid)): The document this one was made from (the offer of an order). Omitted when not set.
- `total` (integer, required): Number of documents.

Example 200 answer:

```json
{
  "items": [
    {
      "createdAt": "2026-11-06T10:30:00Z",
      "netTotal": 18400,
      "number": "AN-2026-0012",
      "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
      "status": "SENT",
      "transactionId": "2b4d6f8b-0c2e-4a4c-8e6a-0c2e4a6c8e0a",
      "type": "OFFER",
      "updatedAt": "2026-11-12T16:40:00Z",
      "version": 2
    }
  ],
  "total": 1
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/opportunities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12/documents' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

# Campaigns

## List campaigns (tenant:crm:read)

`GET /api/crm/v1/campaigns`

Module: CRM · operationId: `listCampaigns` · Tag: Campaigns · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `status` | query | CampaignStatus |  | (one of `PLANNING`, `ACTIVE`, `COMPLETED`, `CANCELLED`) |
| `type` | query | CampaignType |  | (one of `EMAIL`, `WEBINAR`, `TRADE_SHOW`, `ADS`, `EVENT`, `SOCIAL_MEDIA`, `OTHER`) |
| `search` | query | string |  | Case-insensitive substring of name or description. (max length 255) |
| `sort` | query | string |  | Sort order: a field for ascending, `-field` for descending. Fields: createdAt, updatedAt, name, startDate, endDate, budget, actualCost, status. Default `-createdAt`. Unknown values answer `400` (`invalid_sort`). (max length 32) |
| `limit` | query | integer |  | Page size, 1–200 (default 50); any other value is `400 invalid`. (default `50`; max 200) |
| `cursor` | query | string |  | `nextCursor` of the previous page; leave out for the first page. Keep `sort` and the filters unchanged while paging: a cursor of another sort or an altered one is `400 invalid` (`field: cursor`). (max length 1024) |

### Responses

- **200** A page of campaigns and the total number of matching campaigns (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of Campaign, required): One page of campaigns.
  - `actualCost` (number (double), required): Cost so far.
  - `budget` (number (double), required): Planned budget.
  - `createdAt` (string (date-time), required): Creation time.
  - `customerNo` (string, required): Customer number of the tenant.
  - `id` (string (uuid), required): Id of the campaign.
  - `name` (string, required): Name of the campaign.
  - `status` (CampaignStatus, required): (one of `PLANNING`, `ACTIVE`, `COMPLETED`, `CANCELLED`)
  - `tenantName` (string, required): Tenant name.
  - `type` (CampaignType, required): (one of `EMAIL`, `WEBINAR`, `TRADE_SHOW`, `ADS`, `EVENT`, `SOCIAL_MEDIA`, `OTHER`)
  - `updatedAt` (string (date-time), required): Time of the last change.
  - `description` (string): Omitted when not set.
  - `endDate` (string (date-time)): Omitted when not set.
  - `startDate` (string (date-time)): Omitted when not set.
- `total` (integer, required): Number of all records matching the filters.
- `nextCursor` (string): Cursor of the next page (pass it as `cursor`); missing on the last page.

Example 200 answer:

```json
{
  "items": [
    {
      "actualCost": 11340,
      "budget": 12000,
      "createdAt": "2026-04-16T14:00:00Z",
      "customerNo": "99999",
      "description": "Gemeinschaftsstand mit Nordlicht IT-Distribution auf der regionalen IT-Messe; Schwerpunkt Netzwerk, WLAN und Managed Services.",
      "endDate": "2026-07-20T00:00:00Z",
      "id": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
      "name": "Messe IT-Business Ostbayern",
      "startDate": "2026-07-18T00:00:00Z",
      "status": "COMPLETED",
      "tenantName": "DEMO",
      "type": "TRADE_SHOW",
      "updatedAt": "2026-08-18T09:00:00Z"
    }
  ],
  "total": 1
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/campaigns' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Create a campaign (tenant:crm:write)

`POST /api/crm/v1/campaigns`

Module: CRM · operationId: `createCampaign` · Tag: Campaigns · Auth: access token (`Authorization: Bearer <accessToken>`)

Defaults are type `EMAIL`, status `PLANNING`, budget and cost `0`. Emits `crm.campaign.created`.

### Request body

`application/json` (required)

- `name` (string, required): Name of the campaign. (max length 255)
- `actualCost` (number (double)): Cost so far. (max 9999999999)
- `budget` (number (double)): Planned budget. (max 9999999999)
- `description` (string): Description. (max length 10000)
- `endDate` (string (date-time)): Not before `startDate`.
- `startDate` (string (date-time)): Start of the campaign.
- `status` (object): Default `PLANNING`.
- `type` (object): Default `EMAIL`.

Example:

```json
{
  "budget": 5000,
  "description": "Mailing an Bestandskunden mit Gaskessel älter als 15 Jahre.",
  "endDate": "2027-04-30T00:00:00Z",
  "name": "Frühjahrsaktion Wärmepumpen",
  "startDate": "2027-03-01T00:00:00Z",
  "type": "EMAIL"
}
```

### Responses

- **201** Created (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 201 answer:

- `actualCost` (number (double), required): Cost so far.
- `budget` (number (double), required): Planned budget.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the campaign.
- `name` (string, required): Name of the campaign.
- `status` (CampaignStatus, required): (one of `PLANNING`, `ACTIVE`, `COMPLETED`, `CANCELLED`)
- `tenantName` (string, required): Tenant name.
- `type` (CampaignType, required): (one of `EMAIL`, `WEBINAR`, `TRADE_SHOW`, `ADS`, `EVENT`, `SOCIAL_MEDIA`, `OTHER`)
- `updatedAt` (string (date-time), required): Time of the last change.
- `description` (string): Omitted when not set.
- `endDate` (string (date-time)): Omitted when not set.
- `startDate` (string (date-time)): Omitted when not set.

Example 201 answer:

```json
{
  "actualCost": 11340,
  "budget": 12000,
  "createdAt": "2026-04-16T14:00:00Z",
  "customerNo": "99999",
  "description": "Gemeinschaftsstand mit Nordlicht IT-Distribution auf der regionalen IT-Messe; Schwerpunkt Netzwerk, WLAN und Managed Services.",
  "endDate": "2026-07-20T00:00:00Z",
  "id": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
  "name": "Messe IT-Business Ostbayern",
  "startDate": "2026-07-18T00:00:00Z",
  "status": "COMPLETED",
  "tenantName": "DEMO",
  "type": "TRADE_SHOW",
  "updatedAt": "2026-08-18T09:00:00Z"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/campaigns' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"budget":5000,"description":"Mailing an Bestandskunden mit Gaskessel älter als 15 Jahre.","endDate":"2027-04-30T00:00:00Z","name":"Frühjahrsaktion Wärmepumpen","startDate":"2027-03-01T00:00:00Z","type":"EMAIL"}'
```

## Get a campaign (tenant:crm:read)

`GET /api/crm/v1/campaigns/{id}`

Module: CRM · operationId: `getCampaign` · Tag: Campaigns · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **200** The campaign (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `actualCost` (number (double), required): Cost so far.
- `budget` (number (double), required): Planned budget.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the campaign.
- `name` (string, required): Name of the campaign.
- `status` (CampaignStatus, required): (one of `PLANNING`, `ACTIVE`, `COMPLETED`, `CANCELLED`)
- `tenantName` (string, required): Tenant name.
- `type` (CampaignType, required): (one of `EMAIL`, `WEBINAR`, `TRADE_SHOW`, `ADS`, `EVENT`, `SOCIAL_MEDIA`, `OTHER`)
- `updatedAt` (string (date-time), required): Time of the last change.
- `description` (string): Omitted when not set.
- `endDate` (string (date-time)): Omitted when not set.
- `startDate` (string (date-time)): Omitted when not set.

Example 200 answer:

```json
{
  "actualCost": 11340,
  "budget": 12000,
  "createdAt": "2026-04-16T14:00:00Z",
  "customerNo": "99999",
  "description": "Gemeinschaftsstand mit Nordlicht IT-Distribution auf der regionalen IT-Messe; Schwerpunkt Netzwerk, WLAN und Managed Services.",
  "endDate": "2026-07-20T00:00:00Z",
  "id": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
  "name": "Messe IT-Business Ostbayern",
  "startDate": "2026-07-18T00:00:00Z",
  "status": "COMPLETED",
  "tenantName": "DEMO",
  "type": "TRADE_SHOW",
  "updatedAt": "2026-08-18T09:00:00Z"
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/campaigns/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Update a campaign (tenant:crm:write)

`PUT /api/crm/v1/campaigns/{id}`

Module: CRM · operationId: `updateCampaign` · Tag: Campaigns · Auth: access token (`Authorization: Bearer <accessToken>`)

Partial update: only the fields sent change. The resulting date range is checked
(`endDate` not before `startDate`, otherwise `400`). Emits `crm.campaign.updated`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Request body

`application/json` (required)

- `actualCost` (number (double)): Cost so far. (max 9999999999)
- `budget` (number (double)): Planned budget. (max 9999999999)
- `description` (string): Description. (max length 10000)
- `endDate` (string (date-time)): End of the campaign; not before `startDate`.
- `name` (string): Name of the campaign. (max length 255)
- `startDate` (string (date-time)): Start of the campaign.
- `status` (CampaignStatus): (one of `PLANNING`, `ACTIVE`, `COMPLETED`, `CANCELLED`)
- `type` (CampaignType): (one of `EMAIL`, `WEBINAR`, `TRADE_SHOW`, `ADS`, `EVENT`, `SOCIAL_MEDIA`, `OTHER`)

Example:

```json
{
  "actualCost": 1250.5,
  "status": "ACTIVE"
}
```

### Responses

- **200** The updated campaign (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `actualCost` (number (double), required): Cost so far.
- `budget` (number (double), required): Planned budget.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the campaign.
- `name` (string, required): Name of the campaign.
- `status` (CampaignStatus, required): (one of `PLANNING`, `ACTIVE`, `COMPLETED`, `CANCELLED`)
- `tenantName` (string, required): Tenant name.
- `type` (CampaignType, required): (one of `EMAIL`, `WEBINAR`, `TRADE_SHOW`, `ADS`, `EVENT`, `SOCIAL_MEDIA`, `OTHER`)
- `updatedAt` (string (date-time), required): Time of the last change.
- `description` (string): Omitted when not set.
- `endDate` (string (date-time)): Omitted when not set.
- `startDate` (string (date-time)): Omitted when not set.

Example 200 answer:

```json
{
  "actualCost": 11340,
  "budget": 12000,
  "createdAt": "2026-04-16T14:00:00Z",
  "customerNo": "99999",
  "description": "Gemeinschaftsstand mit Nordlicht IT-Distribution auf der regionalen IT-Messe; Schwerpunkt Netzwerk, WLAN und Managed Services.",
  "endDate": "2026-07-20T00:00:00Z",
  "id": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
  "name": "Messe IT-Business Ostbayern",
  "startDate": "2026-07-18T00:00:00Z",
  "status": "COMPLETED",
  "tenantName": "DEMO",
  "type": "TRADE_SHOW",
  "updatedAt": "2026-08-18T09:00:00Z"
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/campaigns/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"actualCost":1250.5,"status":"ACTIVE"}'
```

## Delete a campaign (tenant:crm:write)

`DELETE /api/crm/v1/campaigns/{id}`

Module: CRM · operationId: `deleteCampaign` · Tag: Campaigns · Auth: access token (`Authorization: Bearer <accessToken>`)

Deletes the campaign permanently; its leads and activities stay and lose their `campaignId`. Emits `crm.campaign.deleted`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **204** Deleted
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

### Example request

```bash
curl -X DELETE 'https://api.mbcom.cloud/api/crm/v1/campaigns/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

# CSAT

## List CSAT feedback (tenant:crm:read)

`GET /api/crm/v1/csat`

Module: CRM · operationId: `listCsatFeedbacks` · Tag: CSAT · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | query | string (uuid) |  | Only this feedback (a hit of the global search opens it so). |
| `addressId` | query | string (uuid) |  | Only feedback for this masterdata address. |
| `ticketId` | query | string |  | Only feedback for this ticket. (max length 64) |
| `channel` | query | CSATChannel |  | (one of `PORTAL`, `EMAIL`, `PHONE`, `IN_PERSON`) |
| `from` | query | string (date-time) |  | Only feedback created at or after this time (RFC 3339). |
| `to` | query | string (date-time) |  | Only feedback created before this time (RFC 3339). |
| `search` | query | string |  | Case-insensitive substring of comment or submitter. (max length 255) |
| `sort` | query | string |  | Sort order: a field for ascending, `-field` for descending. Fields: createdAt, rating, channel. Default `-createdAt`. Unknown values answer `400` (`invalid_sort`). (max length 32) |
| `limit` | query | integer |  | Page size, 1–200 (default 50); any other value is `400 invalid`. (default `50`; max 200) |
| `cursor` | query | string |  | `nextCursor` of the previous page; leave out for the first page. Keep `sort` and the filters unchanged while paging: a cursor of another sort or an altered one is `400 invalid` (`field: cursor`). (max length 1024) |

### Responses

- **200** A page of feedback and the total number of matching entries (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of CSATFeedback, required): One page of feedback.
  - `channel` (CSATChannel, required): (one of `PORTAL`, `EMAIL`, `PHONE`, `IN_PERSON`)
  - `createdAt` (string (date-time), required): When the feedback was given.
  - `customerNo` (string, required): Customer number of the tenant.
  - `id` (string (uuid), required): Id of the feedback.
  - `rating` (integer, required): Rating from 1 (bad) to 5 (very good). (max 5)
  - `tenantName` (string, required): Tenant name.
  - `addressId` (string (uuid)): Omitted when not set.
  - `comment` (string): Omitted when not set.
  - `submittedBy` (string): Omitted when not set.
  - `ticketId` (string): Omitted when not set. For a rating from the customer portal the desk ticket id.
  - `ticketNumber` (integer (int64)): Number of the desk ticket the customer rated in the portal (desk.ticket.rated); omitted for feedback recorded by hand.
- `total` (integer, required): Number of all records matching the filters.
- `nextCursor` (string): Cursor of the next page (pass it as `cursor`); missing on the last page.

Example 200 answer:

```json
{
  "items": [
    {
      "addressId": "3c5e7a9c-1d3f-4b5a-9c7e-1a3c5e7a9c1e",
      "channel": "PORTAL",
      "comment": "Schnelle Hilfe, das WLAN im Restaurant läuft wieder stabil.",
      "createdAt": "2026-11-17T11:05:00Z",
      "customerNo": "99999",
      "id": "9f1b3d5f-7a9c-4e1d-8b3f-7e9a1c3e5b7d",
      "rating": 5,
      "submittedBy": "Katrin Stadler",
      "tenantName": "DEMO",
      "ticketId": "6a8c0e2a-4b6d-4f8a-9c1e-3b5d7f9a1c3e",
      "ticketNumber": 214
    }
  ],
  "total": 1
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/csat' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Record CSAT feedback (tenant:crm:write)

`POST /api/crm/v1/csat`

Module: CRM · operationId: `createCsatFeedback` · Tag: CSAT · Auth: access token (`Authorization: Bearer <accessToken>`)

`addressId` and `ticketId` are stored as given and not checked. Without `channel` it is
`PORTAL`. Emits `crm.csat.created`.

### Request body

`application/json` (required)

- `rating` (integer, required): Rating from 1 (bad) to 5 (very good). (max 5)
- `addressId` (string (uuid)): Masterdata address the feedback is about.
- `channel` (object): Default `PORTAL`.
- `comment` (string): Comment of the customer. (max length 10000)
- `submittedBy` (string): Who gave the feedback. Left out by a person: their name (or e-mail); by a service: not set. (max length 255)
- `ticketId` (string): Ticket the feedback is about. (max length 64)

Example:

```json
{
  "channel": "EMAIL",
  "comment": "Schnelle Hilfe, Techniker war sehr freundlich.",
  "rating": 4,
  "submittedBy": "Sabine Müller",
  "ticketId": "4711"
}
```

### Responses

- **201** Created (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 201 answer:

- `channel` (CSATChannel, required): (one of `PORTAL`, `EMAIL`, `PHONE`, `IN_PERSON`)
- `createdAt` (string (date-time), required): When the feedback was given.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the feedback.
- `rating` (integer, required): Rating from 1 (bad) to 5 (very good). (max 5)
- `tenantName` (string, required): Tenant name.
- `addressId` (string (uuid)): Omitted when not set.
- `comment` (string): Omitted when not set.
- `submittedBy` (string): Omitted when not set.
- `ticketId` (string): Omitted when not set. For a rating from the customer portal the desk ticket id.
- `ticketNumber` (integer (int64)): Number of the desk ticket the customer rated in the portal (desk.ticket.rated); omitted for feedback recorded by hand.

Example 201 answer:

```json
{
  "addressId": "3c5e7a9c-1d3f-4b5a-9c7e-1a3c5e7a9c1e",
  "channel": "PORTAL",
  "comment": "Schnelle Hilfe, das WLAN im Restaurant läuft wieder stabil.",
  "createdAt": "2026-11-17T11:05:00Z",
  "customerNo": "99999",
  "id": "9f1b3d5f-7a9c-4e1d-8b3f-7e9a1c3e5b7d",
  "rating": 5,
  "submittedBy": "Katrin Stadler",
  "tenantName": "DEMO",
  "ticketId": "6a8c0e2a-4b6d-4f8a-9c1e-3b5d7f9a1c3e",
  "ticketNumber": 214
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/csat' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"channel":"EMAIL","comment":"Schnelle Hilfe, Techniker war sehr freundlich.","rating":4,"submittedBy":"Sabine Müller","ticketId":"4711"}'
```

## CSAT summary of the tenant (tenant:crm:read)

`GET /api/crm/v1/csat/summary`

Module: CRM · operationId: `getCsatSummary` · Tag: CSAT · Auth: access token (`Authorization: Bearer <accessToken>`)

Count, average rating and distribution over the tenant's feedback matching the filters of `GET /csat` (the
list's key figures: the portal sends the list's filter); without filters over all feedback. Sort, limit and
cursor are ignored.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | query | string (uuid) |  | Only this feedback (the list opened by a hit of the global search; its figures cover that one rating). |
| `addressId` | query | string (uuid) |  | Only feedback for this masterdata address. |
| `ticketId` | query | string |  | Only feedback for this ticket. (max length 64) |
| `channel` | query | CSATChannel |  | (one of `PORTAL`, `EMAIL`, `PHONE`, `IN_PERSON`) |
| `from` | query | string (date-time) |  | Only feedback created at or after this time (RFC 3339). |
| `to` | query | string (date-time) |  | Only feedback created before this time (RFC 3339). |
| `search` | query | string |  | Case-insensitive substring of comment or submitter. (max length 255) |

### Responses

- **200** Summary (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `averageScore` (number (double), required): Average rating; 0 without feedback.
- `distribution` (object, required): Number of ratings per value; keys `1` to `5` are always present.
- `totalCount` (integer, required): Number of ratings matching the filters.

Example 200 answer:

```json
{
  "averageScore": 4.19,
  "distribution": {
    "1": 1,
    "2": 2,
    "3": 4,
    "4": 13,
    "5": 22
  },
  "totalCount": 42
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/csat/summary' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

# Activities

## List activities (tenant:crm:read)

`GET /api/crm/v1/activities`

Module: CRM · operationId: `listActivities` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

Tasks (`kind=TASK` or `open=true`) are sorted by `dueAt`, everything else newest first, unless `sort` says otherwise.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `leadId` | query | string (uuid) |  |  |
| `opportunityId` | query | string (uuid) |  |  |
| `addressId` | query | string (uuid) |  |  |
| `campaignId` | query | string (uuid) |  |  |
| `kind` | query | ActivityKind |  | (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`) |
| `assignee` | query | string |  | Assignee e-mail address, or `me`. (max length 255) |
| `open` | query | boolean |  | `true`: only tasks that are not done; `false`: only done ones. |
| `dueBefore` | query | string (date-time) |  | Only tasks due before this time (RFC 3339). |
| `sort` | query | string |  | Sort order: a field for ascending, `-field` for descending. Fields: createdAt, dueAt, updatedAt. Default `-createdAt; `dueAt` for tasks`. Unknown values answer `400` (`invalid_sort`). (max length 32) |
| `limit` | query | integer |  | Page size, 1–200 (default 50); any other value is `400 invalid`. (default `50`; max 200) |
| `cursor` | query | string |  | `nextCursor` of the previous page; leave out for the first page. Keep `sort` and the filters unchanged while paging: a cursor of another sort or an altered one is `400 invalid` (`field: cursor`). (max length 1024) |

### Responses

- **200** A page of activities and the total number of matching ones (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of Activity, required): One page of activities.
  - `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
  - `createdAt` (string (date-time), required): Creation time.
  - `customerNo` (string, required): Customer number of the tenant.
  - `id` (string (uuid), required): Id of the activity.
  - `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
  - `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
  - `subject` (string, required): Subject (one line).
  - `tenantName` (string, required): Tenant name.
  - `updatedAt` (string (date-time), required): Time of the last change.
  - `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
  - `assigneeEmail` (string): Employee the task is assigned to.
  - `body` (string): Omitted when not set (and after anonymisation).
  - `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
  - `createdBy` (string): E-mail of the creating person; omitted for system entries.
  - `createdByName` (string): Name of the creating person; omitted when not known.
  - `doneAt` (string (date-time), read-only): Completion time of a task.
  - `doneBy` (string, read-only): Who completed the task.
  - `dueAt` (string (date-time)): Due date of a task.
  - `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
  - `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
  - `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
  - `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.
- `total` (integer, required): Number of all records matching the filters.
- `nextCursor` (string): Cursor of the next page (pass it as `cursor`); missing on the last page.

Example 200 answer:

```json
{
  "items": [
    {
      "assigneeEmail": "lena.vogel@muster-it.example",
      "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
      "bookedMinutes": 25,
      "createdAt": "2026-11-12T16:45:00Z",
      "createdBy": "lena.vogel@muster-it.example",
      "createdByName": "Lena Vogel",
      "customerNo": "99999",
      "dueAt": "2026-11-20T09:00:00Z",
      "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
      "kind": "TASK",
      "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
      "meta": {},
      "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
      "recordName": "WLAN Sudhaus und Lager",
      "subject": "Angebot WLAN Sudhaus nachfassen",
      "tenantName": "DEMO",
      "updatedAt": "2026-11-12T16:45:00Z"
    }
  ],
  "total": 1
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/activities' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Create an activity (tenant:crm:write)

`POST /api/crm/v1/activities`

Module: CRM · operationId: `createActivity` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

At least one of `leadId`, `opportunityId` and `addressId` is required (`400`,
`activity_link_required`); the records must exist in the tenant. The creating person is stored
as `createdBy`. Engagement activities change the score of the lead when lead scoring is on. An activity of an
anonymised lead is `409` (`lead_anonymized`).
Emits `crm.activity.created` (and `crm.task.assigned` for a task with an assignee).

### Request body

`application/json` (required)

- `kind` (string, required): Kind of the activity (`SYSTEM` cannot be created). (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`)
- `subject` (string, required): Subject (one line). (max length 255)
- `addressId` (string (uuid)): A masterdata address of the tenant (`422` otherwise).
- `assigneeEmail` (string (email)): Employee a task is assigned to. (max length 255)
- `body` (string): Text of the activity. (max length 20000)
- `dueAt` (string (date-time)): Due date of a task.
- `leadId` (string (uuid)): A lead of the tenant (`422` otherwise).
- `opportunityId` (string (uuid)): An opportunity of the tenant (`422` otherwise).

Example:

```json
{
  "assigneeEmail": "vertrieb@example.com",
  "dueAt": "2026-12-01T09:00:00Z",
  "kind": "TASK",
  "leadId": "3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12",
  "subject": "Angebot nachfassen"
}
```

### Responses

- **201** Created (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **422** A referenced record (lead, masterdata address) does not exist in the tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 201 answer:

- `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the activity.
- `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
- `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
- `subject` (string, required): Subject (one line).
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
- `assigneeEmail` (string): Employee the task is assigned to.
- `body` (string): Omitted when not set (and after anonymisation).
- `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
- `createdBy` (string): E-mail of the creating person; omitted for system entries.
- `createdByName` (string): Name of the creating person; omitted when not known.
- `doneAt` (string (date-time), read-only): Completion time of a task.
- `doneBy` (string, read-only): Who completed the task.
- `dueAt` (string (date-time)): Due date of a task.
- `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
- `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
- `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.

Example 201 answer:

```json
{
  "assigneeEmail": "lena.vogel@muster-it.example",
  "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
  "bookedMinutes": 25,
  "createdAt": "2026-11-12T16:45:00Z",
  "createdBy": "lena.vogel@muster-it.example",
  "createdByName": "Lena Vogel",
  "customerNo": "99999",
  "dueAt": "2026-11-20T09:00:00Z",
  "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
  "kind": "TASK",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "meta": {},
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "recordName": "WLAN Sudhaus und Lager",
  "subject": "Angebot WLAN Sudhaus nachfassen",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-12T16:45:00Z"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/activities' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"assigneeEmail":"vertrieb@example.com","dueAt":"2026-12-01T09:00:00Z","kind":"TASK","leadId":"3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12","subject":"Angebot nachfassen"}'
```

## Send an e-mail to a lead or contact (tenant:crm:write)

`POST /api/crm/v1/activities/mail`

Module: CRM · operationId: `sendContactMail` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

Sends a personal e-mail of the calling person through the tenant's default mail channel (comms, system
template `crm.contact_mail`: subject, the plain-text `body` – Markdown is sent as written –, then the sender's
name and e-mail) and records it as an `EMAIL` activity of the lead, opportunity or address (at least one is
required, `400` `activity_link_required`). The mail is queued in the transaction that stores the activity and
delivered right after; `meta` holds `to`, `template`, `idempotencyKey` and `commandId` (the queued delivery).
`marketingOptOut` does not stop a personal mail; an anonymised lead is `409` (`lead_anonymized`). Without mail
configured the answer is `503` (`mail_unavailable`). With an `Idempotency-Key` a repeated request answers the
activity of the first one and sends nothing. Emits `crm.activity.created`; an e-mail to a lead counts for its
score.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string |  | Makes a retry harmless (at most 128 characters, per person). (max length 128) |

### Request body

`application/json` (required)

- `body` (string, required): Plain text; Markdown is sent as written. (max length 4000)
- `subject` (string, required): One line. (max length 255)
- `to` (string (email), required): Recipient e-mail address. (max length 255)
- `addressId` (string (uuid)): A masterdata address of the tenant (checked).
- `leadId` (string (uuid)): Lead the mail is about (a lead of the tenant).
- `opportunityId` (string (uuid)): Opportunity the mail is about.

Example:

```json
{
  "body": "Guten Tag Frau Gaßner,\n\nwie besprochen erhalten Sie anbei unser Angebot AN-2026-0012.\n\nViele Grüße\nLena Vogel",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "subject": "Ihr Angebot für das WLAN in Sudhaus und Lager",
  "to": "eva.gassner@brauerei-gassner.example"
}
```

### Responses

- **201** The EMAIL activity of the queued mail (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **422** A referenced record (lead, masterdata address) does not exist in the tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **503** The CRM cannot send mail (`mail_unavailable`). (`application/json`)

Fields of the 201 answer:

- `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the activity.
- `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
- `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
- `subject` (string, required): Subject (one line).
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
- `assigneeEmail` (string): Employee the task is assigned to.
- `body` (string): Omitted when not set (and after anonymisation).
- `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
- `createdBy` (string): E-mail of the creating person; omitted for system entries.
- `createdByName` (string): Name of the creating person; omitted when not known.
- `doneAt` (string (date-time), read-only): Completion time of a task.
- `doneBy` (string, read-only): Who completed the task.
- `dueAt` (string (date-time)): Due date of a task.
- `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
- `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
- `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.

Example 201 answer:

```json
{
  "assigneeEmail": "lena.vogel@muster-it.example",
  "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
  "bookedMinutes": 25,
  "createdAt": "2026-11-12T16:45:00Z",
  "createdBy": "lena.vogel@muster-it.example",
  "createdByName": "Lena Vogel",
  "customerNo": "99999",
  "dueAt": "2026-11-20T09:00:00Z",
  "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
  "kind": "TASK",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "meta": {},
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "recordName": "WLAN Sudhaus und Lager",
  "subject": "Angebot WLAN Sudhaus nachfassen",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-12T16:45:00Z"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/activities/mail' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"body":"Guten Tag Frau Gaßner,\n\nwie besprochen erhalten Sie anbei unser Angebot AN-2026-0012.\n\nViele Grüße\nLena Vogel","leadId":"5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f","opportunityId":"7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f","subject":"Ihr Angebot für das WLAN in Sudhaus und Lager","to":"eva.gassner@brauerei-gassner.example"}'
```

## Get an activity (tenant:crm:read)

`GET /api/crm/v1/activities/{id}`

Module: CRM · operationId: `getActivity` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **200** The activity (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the activity.
- `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
- `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
- `subject` (string, required): Subject (one line).
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
- `assigneeEmail` (string): Employee the task is assigned to.
- `body` (string): Omitted when not set (and after anonymisation).
- `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
- `createdBy` (string): E-mail of the creating person; omitted for system entries.
- `createdByName` (string): Name of the creating person; omitted when not known.
- `doneAt` (string (date-time), read-only): Completion time of a task.
- `doneBy` (string, read-only): Who completed the task.
- `dueAt` (string (date-time)): Due date of a task.
- `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
- `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
- `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.

Example 200 answer:

```json
{
  "assigneeEmail": "lena.vogel@muster-it.example",
  "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
  "bookedMinutes": 25,
  "createdAt": "2026-11-12T16:45:00Z",
  "createdBy": "lena.vogel@muster-it.example",
  "createdByName": "Lena Vogel",
  "customerNo": "99999",
  "dueAt": "2026-11-20T09:00:00Z",
  "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
  "kind": "TASK",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "meta": {},
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "recordName": "WLAN Sudhaus und Lager",
  "subject": "Angebot WLAN Sudhaus nachfassen",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-12T16:45:00Z"
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/activities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Update an activity (tenant:crm:write)

`PUT /api/crm/v1/activities/{id}`

Module: CRM · operationId: `updateActivity` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

Partial update. `SYSTEM` entries cannot be changed (`409`, `system_activity`), nor e-mails sent through comms (`409`, `activity_locked`; the mail history is tamper-proof), nor those of an anonymised lead (`409`, `lead_anonymized`). A task changed to another kind is no longer done (`doneAt`, `doneBy` are cleared). `assigneeEmail: ""`
removes the assignee; `clearDueAt: true` removes the due date (`dueAt: null` keeps it). Emits
`crm.activity.updated` (and `crm.task.assigned` when the assignee changes).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Request body

`application/json` (required)

- `assigneeEmail` (string): An empty string removes the assignee. (max length 255)
- `body` (string): Text of the activity. (max length 20000)
- `clearDueAt` (boolean): Remove the due date.
- `dueAt` (string (date-time)): Due date of a task.
- `kind` (string): Kind of the activity (`SYSTEM` cannot be set). (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`)
- `subject` (string): Subject (one line). (max length 255)

Example:

```json
{
  "assigneeEmail": "felix.neumann@muster-it.example",
  "dueAt": "2026-11-25T09:00:00Z",
  "subject": "Angebot WLAN Sudhaus nachfassen"
}
```

### Responses

- **200** The updated activity (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the activity.
- `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
- `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
- `subject` (string, required): Subject (one line).
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
- `assigneeEmail` (string): Employee the task is assigned to.
- `body` (string): Omitted when not set (and after anonymisation).
- `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
- `createdBy` (string): E-mail of the creating person; omitted for system entries.
- `createdByName` (string): Name of the creating person; omitted when not known.
- `doneAt` (string (date-time), read-only): Completion time of a task.
- `doneBy` (string, read-only): Who completed the task.
- `dueAt` (string (date-time)): Due date of a task.
- `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
- `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
- `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.

Example 200 answer:

```json
{
  "assigneeEmail": "lena.vogel@muster-it.example",
  "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
  "bookedMinutes": 25,
  "createdAt": "2026-11-12T16:45:00Z",
  "createdBy": "lena.vogel@muster-it.example",
  "createdByName": "Lena Vogel",
  "customerNo": "99999",
  "dueAt": "2026-11-20T09:00:00Z",
  "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
  "kind": "TASK",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "meta": {},
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "recordName": "WLAN Sudhaus und Lager",
  "subject": "Angebot WLAN Sudhaus nachfassen",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-12T16:45:00Z"
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/activities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"assigneeEmail":"felix.neumann@muster-it.example","dueAt":"2026-11-25T09:00:00Z","subject":"Angebot WLAN Sudhaus nachfassen"}'
```

## Delete an activity (tenant:crm:write)

`DELETE /api/crm/v1/activities/{id}`

Module: CRM · operationId: `deleteActivity` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

`SYSTEM` entries cannot be deleted (`409`, `system_activity`), nor e-mails sent through comms (`409`, `activity_locked`). Emits `crm.activity.deleted`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **204** Deleted
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

### Example request

```bash
curl -X DELETE 'https://api.mbcom.cloud/api/crm/v1/activities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Complete a task (tenant:crm:write)

`POST /api/crm/v1/activities/{id}/complete`

Module: CRM · operationId: `completeActivity` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

Sets `doneAt` and `doneBy`. Only tasks (`409`, `activity_not_task`). Emits `crm.task.completed`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **200** The completed task (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the activity.
- `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
- `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
- `subject` (string, required): Subject (one line).
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
- `assigneeEmail` (string): Employee the task is assigned to.
- `body` (string): Omitted when not set (and after anonymisation).
- `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
- `createdBy` (string): E-mail of the creating person; omitted for system entries.
- `createdByName` (string): Name of the creating person; omitted when not known.
- `doneAt` (string (date-time), read-only): Completion time of a task.
- `doneBy` (string, read-only): Who completed the task.
- `dueAt` (string (date-time)): Due date of a task.
- `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
- `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
- `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.

Example 200 answer:

```json
{
  "assigneeEmail": "lena.vogel@muster-it.example",
  "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
  "bookedMinutes": 25,
  "createdAt": "2026-11-12T16:45:00Z",
  "createdBy": "lena.vogel@muster-it.example",
  "createdByName": "Lena Vogel",
  "customerNo": "99999",
  "dueAt": "2026-11-20T09:00:00Z",
  "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
  "kind": "TASK",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "meta": {},
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "recordName": "WLAN Sudhaus und Lager",
  "subject": "Angebot WLAN Sudhaus nachfassen",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-12T16:45:00Z"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/activities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12/complete' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Reopen a task (tenant:crm:write)

`POST /api/crm/v1/activities/{id}/reopen`

Module: CRM · operationId: `reopenActivity` · Tag: Activities · Auth: access token (`Authorization: Bearer <accessToken>`)

Clears `doneAt` and `doneBy`. Only tasks (`409`, `activity_not_task`). Emits `crm.task.reopened`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | Record ID (UUID). |

### Responses

- **200** The reopened task (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the activity.
- `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
- `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
- `subject` (string, required): Subject (one line).
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
- `assigneeEmail` (string): Employee the task is assigned to.
- `body` (string): Omitted when not set (and after anonymisation).
- `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
- `createdBy` (string): E-mail of the creating person; omitted for system entries.
- `createdByName` (string): Name of the creating person; omitted when not known.
- `doneAt` (string (date-time), read-only): Completion time of a task.
- `doneBy` (string, read-only): Who completed the task.
- `dueAt` (string (date-time)): Due date of a task.
- `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
- `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
- `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.

Example 200 answer:

```json
{
  "assigneeEmail": "lena.vogel@muster-it.example",
  "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
  "bookedMinutes": 25,
  "createdAt": "2026-11-12T16:45:00Z",
  "createdBy": "lena.vogel@muster-it.example",
  "createdByName": "Lena Vogel",
  "customerNo": "99999",
  "dueAt": "2026-11-20T09:00:00Z",
  "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
  "kind": "TASK",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "meta": {},
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "recordName": "WLAN Sudhaus und Lager",
  "subject": "Angebot WLAN Sudhaus nachfassen",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-12T16:45:00Z"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/activities/3f2b8c1e-6d4a-4f7b-9a2e-1c5d7e9f0a12/reopen' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

# Interactions

## List interactions of a customer or without a customer (tenant:crm:read)

`GET /api/crm/v1/interactions`

Module: CRM · operationId: `listInteractions` · Tag: Interactions · Auth: access token (`Authorization: Bearer <accessToken>`)

Calls, meetings and remote sessions comms recorded from the tenant's integrations (NFON, Microsoft Teams,
TeamViewer) and crm follows on comms' feed – metadata only (kind, who, with whom, when, how long, direction,
outcome); interactions between people of the tenant are not kept. Pass exactly one of `addressId` (the
customer's timeline: the address comms suggested or someone assigned) and `unassigned=true` (interactions
without a customer, e.g. unknown numbers); otherwise `400` (`interaction_filter_required`). Newest first, keyset
paging. Transcript and summary are never listed: they appear on the activity the person who had the
interaction tracks it as (`POST /api/crm/v1/interactions/{id}/activity`).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `addressId` | query | string (uuid) |  |  |
| `unassigned` | query | boolean |  | `true`: only interactions without a customer. |
| `limit` | query | integer |  | Page size, 1–200 (default 50); any other value is `400 invalid`. (default `50`; max 200) |
| `cursor` | query | string |  | `nextCursor` of the previous page; leave out for the first page. Keep `sort` and the filters unchanged while paging: a cursor of another sort or an altered one is `400 invalid` (`field: cursor`). (max length 1024) |

### Responses

- **200** A page of interactions (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of Interaction, required): One page of interactions.
  - `durationSeconds` (integer, required): Duration in seconds.
  - `id` (string (uuid), required): The interaction id of comms.
  - `kind` (string, required): call, meeting or remote_session.
  - `provider` (string, required): Integration that recorded it (nfon, teams, teamviewer).
  - `startedAt` (string (date-time), required): Start of the interaction.
  - `updatedAt` (string (date-time), required): Time of the last change.
  - `activityId` (string (uuid)): The crm activity the interaction is tracked as.
  - `addressId` (string (uuid)): The customer (masterdata address); missing while unassigned.
  - `contactId` (string (uuid)): Contact person of the address; missing when not known.
  - `counterpartName` (string): Name of the other side.
  - `direction` (string): Direction of a call, e.g. inbound or outbound.
  - `endedAt` (string (date-time)): End of the interaction; omitted while unknown.
  - `outcome` (string): Outcome reported by the provider, e.g. answered.
  - `personName` (string): Name of that person.
  - `personRef` (string): E-mail of the person of the tenant who had the interaction (lower case).
  - `phone` (string): Phone number of the other side (calls).
- `nextCursor` (string): Cursor of the next page (pass it as `cursor`); missing on the last page.

Example 200 answer:

```json
{
  "items": [
    {
      "addressId": "3c5e7a9c-1d3f-4b5a-9c7e-1a3c5e7a9c1e",
      "contactId": "8b0d2f4b-6c8e-4a0c-9e2a-4c6e8a0c2e4a",
      "counterpartName": "Katrin Stadler",
      "direction": "inbound",
      "durationSeconds": 487,
      "endedAt": "2026-11-16T09:20:07Z",
      "id": "4f6a8c0e-2b4d-4f6a-8c0e-2b4d6f8a0c2e",
      "kind": "call",
      "outcome": "answered",
      "personName": "Sophie Huber",
      "personRef": "sophie.huber@muster-it.example",
      "phone": "+498652987612",
      "provider": "nfon",
      "startedAt": "2026-11-16T09:12:00Z",
      "updatedAt": "2026-11-16T09:20:09Z"
    }
  ]
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/interactions' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Assign an interaction to a customer (tenant:crm:write)

`PUT /api/crm/v1/interactions/{id}/address`

Module: CRM · operationId: `assignInteraction` · Tag: Interactions · Auth: access token (`Authorization: Bearer <accessToken>`)

Sets the masterdata address (checked in masterdata, `422` `invalid_reference` when unknown) and optionally the
contact of an interaction in crm. The assignment stays in crm – later updates of comms keep it, and comms
learns nothing from it. An interaction tracked as an activity keeps its customer (`409` `already_tracked`).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | The interaction id (comms). |

### Request body

`application/json` (required)

- `addressId` (string (uuid), required): The customer (masterdata address of the tenant).
- `contactId` (string (uuid)): Contact person of that address.

Example:

```json
{
  "addressId": "3c5e7a9c-1d3f-4b5a-9c7e-1a3c5e7a9c1e",
  "contactId": "8b0d2f4b-6c8e-4a0c-9e2a-4c6e8a0c2e4a"
}
```

### Responses

- **200** The assigned interaction (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **422** A referenced record (lead, masterdata address) does not exist in the tenant. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **502** An upstream service (masterdata, VAT check) failed, is switched off or is not configured. (`application/json`)

Fields of the 200 answer:

- `durationSeconds` (integer, required): Duration in seconds.
- `id` (string (uuid), required): The interaction id of comms.
- `kind` (string, required): call, meeting or remote_session.
- `provider` (string, required): Integration that recorded it (nfon, teams, teamviewer).
- `startedAt` (string (date-time), required): Start of the interaction.
- `updatedAt` (string (date-time), required): Time of the last change.
- `activityId` (string (uuid)): The crm activity the interaction is tracked as.
- `addressId` (string (uuid)): The customer (masterdata address); missing while unassigned.
- `contactId` (string (uuid)): Contact person of the address; missing when not known.
- `counterpartName` (string): Name of the other side.
- `direction` (string): Direction of a call, e.g. inbound or outbound.
- `endedAt` (string (date-time)): End of the interaction; omitted while unknown.
- `outcome` (string): Outcome reported by the provider, e.g. answered.
- `personName` (string): Name of that person.
- `personRef` (string): E-mail of the person of the tenant who had the interaction (lower case).
- `phone` (string): Phone number of the other side (calls).

Example 200 answer:

```json
{
  "addressId": "3c5e7a9c-1d3f-4b5a-9c7e-1a3c5e7a9c1e",
  "contactId": "8b0d2f4b-6c8e-4a0c-9e2a-4c6e8a0c2e4a",
  "counterpartName": "Katrin Stadler",
  "direction": "inbound",
  "durationSeconds": 487,
  "endedAt": "2026-11-16T09:20:07Z",
  "id": "4f6a8c0e-2b4d-4f6a-8c0e-2b4d6f8a0c2e",
  "kind": "call",
  "outcome": "answered",
  "personName": "Sophie Huber",
  "personRef": "sophie.huber@muster-it.example",
  "phone": "+498652987612",
  "provider": "nfon",
  "startedAt": "2026-11-16T09:12:00Z",
  "updatedAt": "2026-11-16T09:20:09Z"
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/interactions/3f2b8c1e-7d4a-4e9b-9c2a-5b1d6e8f0a12/address' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"addressId":"3c5e7a9c-1d3f-4b5a-9c7e-1a3c5e7a9c1e","contactId":"8b0d2f4b-6c8e-4a0c-9e2a-4c6e8a0c2e4a"}'
```

## Track one's own interaction as an activity (tenant:crm:write, person)

`POST /api/crm/v1/interactions/{id}/activity`

Module: CRM · operationId: `trackInteraction` · Tag: Interactions · Auth: access token (`Authorization: Bearer <accessToken>`)

Records the interaction as an activity of its customer – `CALL` for calls and remote sessions, `MEETING` for
meetings – with `interactionId`, the interaction's `addressId` and optionally a lead or opportunity. Only the
person who had the interaction may (`403` `not_your_interaction`; service accounts `403` `person_required`);
it needs a customer (`409` `unassigned`, assign it first) and is tracked once (`409` `already_tracked`; deleting
the activity frees it). Only now crm reads the summary and the transcript from comms and keeps them in the
activity's `meta` (`summary`, `transcript` up to 5 MB, `transcriptContentType`); activity lists leave
`meta.transcript` out, `GET /api/crm/v1/activities/{id}` has it. Without a connection to comms the answer is
`503` (`comms_unavailable`). Only calls, meetings and remote sessions can be tracked (`422` `unsupported_kind`).
When the interaction's customer or person changed meanwhile the answer is `409` (`version_conflict`): load it
again and retry. Emits `crm.activity.created`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string (uuid) | yes | The interaction id (comms). |

### Request body

`application/json` (required)

- `body` (string): Note of the activity. (max length 20000)
- `leadId` (string (uuid)): Lead the activity belongs to.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to.
- `subject` (string): Defaults to e.g. „Anruf mit <name or number>“. (max length 255)

Example:

```json
{
  "body": "WLAN im Restaurant fällt aus – Access Point neu gestartet, Ticket angelegt.",
  "subject": "Anruf mit Katrin Stadler"
}
```

### Responses

- **201** The activity recording the interaction (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **422** The interaction is of a kind that cannot be tracked (`unsupported_kind`), or the lead or opportunity does not exist (`invalid_reference`). (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **502** An upstream service (masterdata, VAT check) failed, is switched off or is not configured. (`application/json`)
- **503** CRM has no connection to comms (`comms_unavailable`). (`application/json`)

Fields of the 201 answer:

- `bookedMinutes` (integer, nullable, required, read-only): Work HR booked on the activity (subject `crm:activity:<id>`, worked minus breaks, ADR 0040); filled by `GET /activities/{id}` and the activity list, null there when HR does not answer (never an error) and in answers of writes.
- `createdAt` (string (date-time), required): Creation time.
- `customerNo` (string, required): Customer number of the tenant.
- `id` (string (uuid), required): Id of the activity.
- `kind` (ActivityKind, required): `SYSTEM` entries are history written by the CRM and cannot be created or changed. (one of `NOTE`, `CALL`, `MEETING`, `EMAIL`, `TASK`, `SYSTEM`)
- `meta` (object, required): Details of `SYSTEM` entries (for example the old and new stage); of a tracked interaction `interactionId`, `provider`, `summary` and `transcript` (left out by lists); empty otherwise.
- `subject` (string, required): Subject (one line).
- `tenantName` (string, required): Tenant name.
- `updatedAt` (string (date-time), required): Time of the last change.
- `addressId` (string (uuid)): Masterdata address the activity belongs to; omitted when not set.
- `assigneeEmail` (string): Employee the task is assigned to.
- `body` (string): Omitted when not set (and after anonymisation).
- `campaignId` (string (uuid)): Campaign the activity belongs to; omitted when not set.
- `createdBy` (string): E-mail of the creating person; omitted for system entries.
- `createdByName` (string): Name of the creating person; omitted when not known.
- `doneAt` (string (date-time), read-only): Completion time of a task.
- `doneBy` (string, read-only): Who completed the task.
- `dueAt` (string (date-time)): Due date of a task.
- `interactionId` (string (uuid), read-only): The comms interaction a tracked call or meeting records.
- `leadId` (string (uuid)): Lead the activity belongs to; omitted when not set.
- `opportunityId` (string (uuid)): Opportunity the activity belongs to; omitted when not set.
- `recordName` (string, read-only): Title of the opportunity, else company of the lead the activity belongs to; set by the activity list only.

Example 201 answer:

```json
{
  "assigneeEmail": "lena.vogel@muster-it.example",
  "body": "Frau Gaßner wollte die Freigabe des Budgets mit dem Gesellschafter klären.",
  "bookedMinutes": 25,
  "createdAt": "2026-11-12T16:45:00Z",
  "createdBy": "lena.vogel@muster-it.example",
  "createdByName": "Lena Vogel",
  "customerNo": "99999",
  "dueAt": "2026-11-20T09:00:00Z",
  "id": "1d3f5b7d-9e1a-4c3d-8f5b-9a1c3e5b7d9f",
  "kind": "TASK",
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "meta": {},
  "opportunityId": "7d9f1b3d-5e7a-4c9b-8f1d-5c7e9a1b3d5f",
  "recordName": "WLAN Sudhaus und Lager",
  "subject": "Angebot WLAN Sudhaus nachfassen",
  "tenantName": "DEMO",
  "updatedAt": "2026-11-12T16:45:00Z"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/interactions/3f2b8c1e-7d4a-4e9b-9c2a-5b1d6e8f0a12/activity' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"body":"WLAN im Restaurant fällt aus – Access Point neu gestartet, Ticket angelegt.","subject":"Anruf mit Katrin Stadler"}'
```

# Pipeline

## List the pipeline stages (tenant:crm:read)

`GET /api/crm/v1/stages`

Module: CRM · operationId: `listStages` · Tag: Pipeline · Auth: access token (`Authorization: Bearer <accessToken>`)

The tenant's stages in pipeline order, archived ones included; the defaults (see Model) while the tenant saved none (`default: true`).

### Responses

- **200** Stages (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `default` (boolean, required): The tenant has not saved its own stages; these are the defaults.
- `items` (array of Stage, required): Stages in pipeline order.
  - `archived` (boolean, required): Archived stages cannot be chosen for opportunities.
  - `key` (string, required): Stable key of the stage (stored on opportunities). (max length 64)
  - `label` (string, required): Display name. (max length 100)
  - `phase` (string, required): Phase the stage belongs to. (one of `open`, `won`, `lost`)
  - `position` (integer, required): Order in the pipeline.
  - `probability` (integer, required): Default win probability of an opportunity entering the stage. (max 100)
  - `used` (boolean, required, read-only): Opportunities are in the stage; it can then only be archived, not removed.

Example 200 answer:

```json
{
  "default": false,
  "items": [
    {
      "archived": false,
      "key": "PROSPECTING",
      "label": "Erstkontakt",
      "phase": "open",
      "position": 1,
      "probability": 10,
      "used": true
    },
    {
      "archived": false,
      "key": "QUALIFICATION",
      "label": "Qualifizierung",
      "phase": "open",
      "position": 2,
      "probability": 30,
      "used": true
    },
    {
      "archived": false,
      "key": "PROPOSAL",
      "label": "Angebot",
      "phase": "open",
      "position": 3,
      "probability": 50,
      "used": true
    },
    {
      "archived": false,
      "key": "NEGOTIATION",
      "label": "Verhandlung",
      "phase": "open",
      "position": 4,
      "probability": 75,
      "used": false
    },
    {
      "archived": false,
      "key": "CLOSED_WON",
      "label": "Gewonnen",
      "phase": "won",
      "position": 5,
      "probability": 100,
      "used": true
    },
    {
      "archived": false,
      "key": "CLOSED_LOST",
      "label": "Verloren",
      "phase": "lost",
      "position": 6,
      "probability": 0,
      "used": true
    }
  ]
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/stages' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Replace the pipeline stages (tenant:crm:admin)

`PUT /api/crm/v1/stages`

Module: CRM · operationId: `replaceStages` · Tag: Pipeline · Auth: access token (`Authorization: Bearer <accessToken>`)

Saves the whole list; its order is the order of the pipeline. Every phase needs at least one
active stage and keys must be unique (`400`, `invalid_stages`); a key that opportunities use
cannot be left out, only archived (`400`, `stage_in_use`). The phase of a stage that opportunities use
cannot change (`400`, field `items.<n>.phase`); add a new stage instead. Emits `crm.stages.updated`.

### Request body

`application/json` (required)

- `items` (array of StageInput, required): In pipeline order.
  - `key` (string, required): Stable key of the stage. (max length 64)
  - `label` (string, required): Display name. (max length 100)
  - `phase` (string, required): Phase the stage belongs to. (one of `open`, `won`, `lost`)
  - `archived` (boolean): Archived stages cannot be chosen for opportunities. (default `false`)
  - `probability` (integer): Default win probability of an opportunity entering the stage. (default `0`; max 100)

Example:

```json
{
  "items": [
    {
      "key": "PROSPECTING",
      "label": "Akquise",
      "phase": "open",
      "probability": 10
    },
    {
      "key": "PROPOSAL",
      "label": "Angebot",
      "phase": "open",
      "probability": 50
    },
    {
      "key": "CLOSED_WON",
      "label": "Gewonnen",
      "phase": "won",
      "probability": 100
    },
    {
      "key": "CLOSED_LOST",
      "label": "Verloren",
      "phase": "lost",
      "probability": 0
    }
  ]
}
```

### Responses

- **200** The saved stages (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `default` (boolean, required): The tenant has not saved its own stages; these are the defaults.
- `items` (array of Stage, required): Stages in pipeline order.
  - `archived` (boolean, required): Archived stages cannot be chosen for opportunities.
  - `key` (string, required): Stable key of the stage (stored on opportunities). (max length 64)
  - `label` (string, required): Display name. (max length 100)
  - `phase` (string, required): Phase the stage belongs to. (one of `open`, `won`, `lost`)
  - `position` (integer, required): Order in the pipeline.
  - `probability` (integer, required): Default win probability of an opportunity entering the stage. (max 100)
  - `used` (boolean, required, read-only): Opportunities are in the stage; it can then only be archived, not removed.

Example 200 answer:

```json
{
  "default": false,
  "items": [
    {
      "archived": false,
      "key": "PROSPECTING",
      "label": "Erstkontakt",
      "phase": "open",
      "position": 1,
      "probability": 10,
      "used": true
    },
    {
      "archived": false,
      "key": "QUALIFICATION",
      "label": "Qualifizierung",
      "phase": "open",
      "position": 2,
      "probability": 30,
      "used": true
    },
    {
      "archived": false,
      "key": "PROPOSAL",
      "label": "Angebot",
      "phase": "open",
      "position": 3,
      "probability": 50,
      "used": true
    },
    {
      "archived": false,
      "key": "NEGOTIATION",
      "label": "Verhandlung",
      "phase": "open",
      "position": 4,
      "probability": 75,
      "used": false
    },
    {
      "archived": false,
      "key": "CLOSED_WON",
      "label": "Gewonnen",
      "phase": "won",
      "position": 5,
      "probability": 100,
      "used": true
    },
    {
      "archived": false,
      "key": "CLOSED_LOST",
      "label": "Verloren",
      "phase": "lost",
      "position": 6,
      "probability": 0,
      "used": true
    }
  ]
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/stages' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"items":[{"key":"PROSPECTING","label":"Akquise","phase":"open","probability":10},{"key":"PROPOSAL","label":"Angebot","phase":"open","probability":50},{"key":"CLOSED_WON","label":"Gewonnen","phase":"won","probability":100},{"key":"CLOSED_LOST","label":"Verloren","phase":"lost","probability":0}]}'
```

# Reports

## Pipeline report (tenant:crm:read)

`GET /api/crm/v1/reports/pipeline`

Module: CRM · operationId: `getPipelineReport` · Tag: Reports · Auth: access token (`Authorization: Bearer <accessToken>`)

The open pipeline per stage, the forecast per month (by expected close date, Europe/Berlin), the
pipeline per owner, and win rate, average deal size and days to close of the opportunities closed
between `from` and `to` (default the last 12 months).

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `from` | query | string (date-time) |  |  |
| `to` | query | string (date-time) |  |  |
| `owner` | query | string |  | Only records of this owner (e-mail address), or `me` for the calling person. (max length 255) |

### Responses

- **200** Report (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `averageDaysToClose` (number (double), nullable, required): Average days from creation to close of the won opportunities; `null` without won opportunities.
- `averageDealSize` (number (double), nullable, required): Average won value per won opportunity; `null` without won opportunities.
- `byOwner` (array of object, required): Open pipeline and won value per owner.
  - `count` (integer, required): Open opportunities of the owner.
  - `ownerEmail` (string, required): Empty for opportunities without owner.
  - `value` (number (double), required): Their value.
  - `weighted` (number (double), required): Their value times probability.
  - `wonValue` (number (double), required): Value won in the period.
- `byStage` (array of object, required): Open pipeline per open stage.
  - `count` (integer, required): Open opportunities in the stage.
  - `key` (string, required): Stage key.
  - `label` (string, required): Stage label.
  - `value` (number (double), required): Their value.
  - `weighted` (number (double), required): Value times probability.
- `forecast` (array of object, required): Open and won value per month.
  - `month` (string, required): YYYY-MM (Europe/Berlin).
  - `value` (number (double), required): Open value by expected close date.
  - `weighted` (number (double), required): Open value times probability.
  - `wonValue` (number (double), required): Value won in the month.
- `from` (string (date-time), required): Start of the period.
- `lost` (integer, required): Opportunities lost in the period.
- `to` (string (date-time), required): End of the period.
- `winRate` (number (double), nullable, required): won / (won + lost); `null` without closed opportunities.
- `won` (integer, required): Opportunities won in the period.
- `wonValue` (number (double), required): Value of the opportunities won in the period: the net total of the orders trade reported for an opportunity (newest revision per order, cancelled ones left out), else its own value.

Example 200 answer:

```json
{
  "averageDaysToClose": 38.5,
  "averageDealSize": 13750,
  "byOwner": [
    {
      "count": 4,
      "ownerEmail": "lena.vogel@muster-it.example",
      "value": 39900,
      "weighted": 14350,
      "wonValue": 9600
    },
    {
      "count": 1,
      "ownerEmail": "felix.neumann@muster-it.example",
      "value": 12000,
      "weighted": 3000,
      "wonValue": 0
    }
  ],
  "byStage": [
    {
      "count": 3,
      "key": "PROSPECTING",
      "label": "Erstkontakt",
      "value": 21500,
      "weighted": 2150
    },
    {
      "count": 2,
      "key": "PROPOSAL",
      "label": "Angebot",
      "value": 30400,
      "weighted": 15200
    }
  ],
  "forecast": [
    {
      "month": "2026-12",
      "value": 30400,
      "weighted": 15200,
      "wonValue": 9600
    }
  ],
  "from": "2026-01-01T00:00:00Z",
  "lost": 1,
  "to": "2026-12-31T23:59:59Z",
  "winRate": 0.75,
  "won": 3,
  "wonValue": 41250
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/reports/pipeline' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Campaign report (tenant:crm:read)

`GET /api/crm/v1/reports/campaigns`

Module: CRM · operationId: `getCampaignReport` · Tag: Reports · Auth: access token (`Authorization: Bearer <accessToken>`)

Leads, converted leads, opportunities, won value, cost and ROI of every campaign.

### Responses

- **200** One entry per campaign (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of CampaignReport, required)
  - `campaignId` (string (uuid), required): Id of the campaign.
  - `convertedLeads` (integer, required): Leads of the campaign that were converted.
  - `cost` (number (double), required): Actual cost of the campaign.
  - `leads` (integer, required): Leads of the campaign.
  - `name` (string, required): Name of the campaign.
  - `opportunities` (integer, required): Opportunities of those leads.
  - `roi` (number (double), nullable, required): (wonValue - cost) / cost; `null` while the campaign has no cost.
  - `status` (CampaignStatus, required): (one of `PLANNING`, `ACTIVE`, `COMPLETED`, `CANCELLED`)
  - `wonValue` (number (double), required): Value of those opportunities in a won stage.

Example 200 answer:

```json
{
  "items": [
    {
      "campaignId": "2a4c6e8a-0b2d-4f4a-8c6e-8a0c2e4a6c8e",
      "convertedLeads": 3,
      "cost": 11340,
      "leads": 9,
      "name": "Messe IT-Business Ostbayern",
      "opportunities": 3,
      "roi": 1.522,
      "status": "COMPLETED",
      "wonValue": 28600
    },
    {
      "campaignId": "4c6e8a0c-2d4f-4a6c-8e0a-2c4e6a8c0e2a",
      "convertedLeads": 0,
      "cost": 0,
      "leads": 0,
      "name": "Newsletter Backup-Check",
      "opportunities": 0,
      "roi": null,
      "status": "PLANNING",
      "wonValue": 0
    }
  ]
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/reports/campaigns' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

# Verification

## Score the completeness of contact data (tenant:crm:read)

`POST /api/crm/v1/quality/score`

Module: CRM · operationId: `calculateQualityScore` · Tag: Verification · Auth: access token (`Authorization: Bearer <accessToken>`)

Pure calculation, nothing is stored. Each of five criteria adds 20 points: VAT ID or tax
number; email or phone; complete postal address (street, zip and city); at least one
contact person; website. `breakdown` lists the criteria met, `suggestions` the missing
ones (English texts).

### Request body

`application/json` (required)

- `city` (string): City.
- `companyName` (string): Company name.
- `contactPersons` (array of string): Names of the contact persons.
- `email` (string): E-mail address.
- `phone` (string): Phone number.
- `street` (string): Street with house number.
- `taxNumber` (string): Tax number.
- `vatId` (string): VAT ID.
- `website` (string): Website.
- `zip` (string): Postal code.

Example:

```json
{
  "city": "Mallersdorf-Pfaffenberg",
  "companyName": "Brauerei Gaßner GmbH \u0026 Co. KG",
  "contactPersons": [
    "Eva Gaßner"
  ],
  "email": "eva.gassner@brauerei-gassner.example",
  "phone": "+49 9441 50070",
  "street": "Brauhausstraße 4",
  "vatId": "DE999000231",
  "zip": "84066"
}
```

### Responses

- **200** Score (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)

Fields of the 200 answer:

- `score` (integer, required): Data quality score in steps of 20. (max 100)
- `breakdown` (array of string): Criteria met; `null` when none.
- `suggestions` (array of string): Missing criteria; `null` when all are met.

Example 200 answer:

```json
{
  "breakdown": [
    "VAT ID or Tax Number provided (+20%)",
    "Direct email or phone provided (+20%)",
    "Complete postal address provided (+20%)",
    "Contact persons linked (+20%)"
  ],
  "score": 80,
  "suggestions": [
    "Add company website URL"
  ]
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/quality/score' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"city":"Mallersdorf-Pfaffenberg","companyName":"Brauerei Gaßner GmbH \u0026 Co. KG","contactPersons":["Eva Gaßner"],"email":"eva.gassner@brauerei-gassner.example","phone":"+49 9441 50070","street":"Brauhausstraße 4","vatId":"DE999000231","zip":"84066"}'
```

## Check a VAT identification number (tenant:crm:write)

`POST /api/crm/v1/vat/validate`

Module: CRM · operationId: `validateVatId` · Tag: Verification · Auth: access token (`Authorization: Bearer <accessToken>`)

The ID is cleaned (spaces, dots, dashes) and prefixed with `country` when it lacks a
country code (`GR` becomes `EL`). Then:
- **EU IDs, German ones included,** are checked officially through the masterdata module: a
  simple check asks EU VIES. With `companyName` and `city` (plus optionally `street` and
  `zip`) it is a qualified confirmation by the BZSt, which also compares the company data
  (`isQualified`); it needs the tenant's own VAT ID in the company profile, without it the
  answer is `CHECK_NOT_POSSIBLE`. The BZSt does not confirm German IDs, so German IDs always get
  the simple VIES check (`isQualified: false`), also with company data. The same check of the tenant is answered from a 24-hour cache
  (conclusive results only), so repeating it does not query VIES or BZSt again. When VIES,
  BZSt or the member state cannot be reached, the result is `TECHNICAL_ERROR` or
  `CHECK_NOT_POSSIBLE`.
- **Swiss UIDs** (`CHE` + 9 digits, optionally `MWST`/`TVA`/`IVA`) get a format check only.
- Other countries return `CHECK_NOT_POSSIBLE`.

A result is `200`; check `valid` and `status`. An ID shorter than four characters or a
request the check rejects returns `400`; a check the tenant switched off in the CRM settings
(`vatCheckEnabled: false`) `409` with `code: vat_check_disabled`; an unreachable or
switched-off official check `502`. It needs `tenant:crm:write`: every check queries VIES or
BZSt and is logged in masterdata. With `leadId` the lead must exist in the tenant (`404`) and the
result is stored on it (`vatId`, `vatStatus`, `vatCheckedAt`); an anonymised lead is read-only (`409`, `lead_anonymized`).

### Request body

`application/json` (required)

- `vatId` (string, required): VAT ID with or without country code. (max length 32)
- `city` (string): For a qualified BZSt confirmation (with `companyName`). (max length 128)
- `companyName` (string): For a qualified BZSt confirmation (with `city`). (max length 255)
- `country` (string): Country code used when `vatId` has none. (max length 32)
- `leadId` (string (uuid)): Stores the result on this lead of the tenant (`vatId`, `vatStatus`, `vatCheckedAt`).
- `street` (string): Street for a qualified BZSt confirmation. (max length 255)
- `zip` (string): Postal code for a qualified BZSt confirmation. (max length 16)

Example:

```json
{
  "leadId": "5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f",
  "vatId": "DE999000231"
}
```

### Responses

- **200** Check result (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **404** The record does not exist in the token's tenant. (`application/json`)
- **409** The state of the record (or the tenant's settings) does not allow the request; `code` says why. (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)
- **502** An upstream service (masterdata, VAT check) failed, is switched off or is not configured. (`application/json`)

Fields of the 200 answer:

- `countryCode` (string, required): Country code of the VAT ID.
- `isQualified` (boolean, required): Company data was compared by the BZSt.
- `status` (string, required): Result of the check (the status of the masterdata VAT check). (one of `OFFICIALLY_CONFIRMED`, `PARTIALLY_CONFIRMED`, `OFFICIALLY_NOT_CONFIRMED`, `FORMALLY_VALID_NO_OFFICIAL_CHECK`, `FORMALLY_INVALID`, `CHECK_NOT_POSSIBLE`, `TECHNICAL_ERROR`, `NOT_CHECKED`)
- `statusDisplay` (string, required): German label of `status`.
- `valid` (boolean, required): The VAT ID is valid.
- `vatId` (string, required): The normalised ID that was checked.
- `checkedAt` (string (date-time)): Time of the check (RFC 3339).
- `cityMatch` (BzstMatch): Result of a qualified comparison: `A` matches, `B` does not match, `C` not requested, `D` not provided by the member state. (one of `A`, `B`, `C`, `D`)
- `companyNameMatch` (BzstMatch): Result of a qualified comparison: `A` matches, `B` does not match, `C` not requested, `D` not provided by the member state. (one of `A`, `B`, `C`, `D`)
- `message` (string): German explanation.
- `officialRequestId` (string): Request ID of VIES or the BZSt for your records.
- `statusCode` (string): Detail code (for example `FORMAT_ERROR`, `FORMALLY_VALID`, `CHECK_NOT_POSSIBLE` or a VIES or BZSt status code).
- `streetMatch` (BzstMatch): Result of a qualified comparison: `A` matches, `B` does not match, `C` not requested, `D` not provided by the member state. (one of `A`, `B`, `C`, `D`)
- `validFrom` (string (date)): Validity start reported by the BZSt.
- `validTill` (string (date)): Validity end reported by the BZSt.
- `zipMatch` (BzstMatch): Result of a qualified comparison: `A` matches, `B` does not match, `C` not requested, `D` not provided by the member state. (one of `A`, `B`, `C`, `D`)

Example 200 answer:

```json
{
  "checkedAt": "2026-10-28T10:02:14Z",
  "countryCode": "DE",
  "isQualified": false,
  "message": "Die USt-IdNr. ist laut VIES gültig.",
  "officialRequestId": "WAPIAAAAZ2fK1x9Q",
  "status": "OFFICIALLY_CONFIRMED",
  "statusCode": "VALID",
  "statusDisplay": "Gültig",
  "valid": true,
  "vatId": "DE999000231"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/vat/validate' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"leadId":"5b7d9f1a-3c5e-4a7b-9d1f-3a5c7e9b1d3f","vatId":"DE999000231"}'
```

# Configuration

## Get the CRM module configuration (tenant:crm:read or tenant:settings:read)

`GET /api/crm/v1/config`

Module: CRM · operationId: `getCrmConfig` · Tag: Configuration · Auth: access token (`Authorization: Bearer <accessToken>`)

The CRM settings with every default filled in (without a saved configuration:
`active: false`, `leadAutoScoring: true`, `defaultLeadSource: MANUAL`,
`vatCheckEnabled: true`, `leadRetentionMonths: 0`, no custom fields). The NFON phone book settings are read with `getNfonConfig`.

### Responses

- **200** Configuration (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `active` (boolean): Marks the CRM module as set up for the tenant (`getCrmConfigStatus`); the API does not refuse requests of an inactive module.
- `customFields` (object): The tenant's own fields of leads and opportunities.
  - `lead` (array of CustomFieldDef): Fields of leads.
    - `key` (string, required): Lower-case letters, digits, `-` or `_`.
    - `kind` (string, required): Field type. (one of `text`, `longtext`, `number`, `date`, `datetime`, `bool`, `select`, `multiselect`, `user`, `url`)
    - `label` (string, required): Label shown in forms.
    - `options` (array of object): Choices of `select` and `multiselect` fields (required there).
      - `label` (string, required): Label shown in forms.
      - `value` (string, required): Stored value.
      - `color` (string): Display colour.
    - `required` (boolean): A value is required on write. (default `false`)
  - `opportunity` (array of CustomFieldDef): Fields of opportunities.
    - `key` (string, required): Lower-case letters, digits, `-` or `_`.
    - `kind` (string, required): Field type. (one of `text`, `longtext`, `number`, `date`, `datetime`, `bool`, `select`, `multiselect`, `user`, `url`)
    - `label` (string, required): Label shown in forms.
    - `options` (array of object): Choices of `select` and `multiselect` fields (required there).
      - `label` (string, required): Label shown in forms.
      - `value` (string, required): Stored value.
      - `color` (string): Display colour.
    - `required` (boolean): A value is required on write. (default `false`)
- `defaultLeadSource` (string): Source of new leads created without one. (default `"MANUAL"`; max length 64)
- `leadAutoScoring` (boolean): New leads without a `score` get the data quality score; `false`: 0. (default `true`)
- `leadRetentionMonths` (integer): Months after which a daily job anonymises `LOST` leads and `NEW` / `CONTACTED` leads without change or activity (see Model); 0 is off. (default `0`; max 120)
- `vatCheckEnabled` (boolean): `false` makes `validateVatId` answer `409` (`vat_check_disabled`). (default `true`)

Example 200 answer:

```json
{
  "active": true,
  "customFields": {
    "lead": [
      {
        "key": "branche",
        "kind": "text",
        "label": "Branche"
      }
    ],
    "opportunity": []
  },
  "defaultLeadSource": "MANUAL",
  "leadAutoScoring": true,
  "leadRetentionMonths": 24,
  "vatCheckEnabled": true
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/config' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Save the CRM module configuration (tenant:crm:admin or tenant:settings:write)

`PUT /api/crm/v1/config`

Module: CRM · operationId: `saveCrmConfig` · Tag: Configuration · Auth: access token (`Authorization: Bearer <accessToken>`)

Replaces the CRM settings: fields left out get their default. The NFON phone book
settings stay as they are; invalid custom field definitions are refused with `400`
(`invalid_custom_fields`); a `nfon` object in the body is ignored (use `saveNfonConfig`).

### Request body

`application/json` (required)

- `active` (boolean): Marks the CRM module as set up for the tenant (`getCrmConfigStatus`); the API does not refuse requests of an inactive module.
- `customFields` (object): The tenant's own fields of leads and opportunities.
  - `lead` (array of CustomFieldDef): Fields of leads.
    - `key` (string, required): Lower-case letters, digits, `-` or `_`.
    - `kind` (string, required): Field type. (one of `text`, `longtext`, `number`, `date`, `datetime`, `bool`, `select`, `multiselect`, `user`, `url`)
    - `label` (string, required): Label shown in forms.
    - `options` (array of object): Choices of `select` and `multiselect` fields (required there).
      - `label` (string, required): Label shown in forms.
      - `value` (string, required): Stored value.
      - `color` (string): Display colour.
    - `required` (boolean): A value is required on write. (default `false`)
  - `opportunity` (array of CustomFieldDef): Fields of opportunities.
    - `key` (string, required): Lower-case letters, digits, `-` or `_`.
    - `kind` (string, required): Field type. (one of `text`, `longtext`, `number`, `date`, `datetime`, `bool`, `select`, `multiselect`, `user`, `url`)
    - `label` (string, required): Label shown in forms.
    - `options` (array of object): Choices of `select` and `multiselect` fields (required there).
      - `label` (string, required): Label shown in forms.
      - `value` (string, required): Stored value.
      - `color` (string): Display colour.
    - `required` (boolean): A value is required on write. (default `false`)
- `defaultLeadSource` (string): Source of new leads created without one. (default `"MANUAL"`; max length 64)
- `leadAutoScoring` (boolean): New leads without a `score` get the data quality score; `false`: 0. (default `true`)
- `leadRetentionMonths` (integer): Months after which a daily job anonymises `LOST` leads and `NEW` / `CONTACTED` leads without change or activity (see Model); 0 is off. (default `0`; max 120)
- `vatCheckEnabled` (boolean): `false` makes `validateVatId` answer `409` (`vat_check_disabled`). (default `true`)

Example:

```json
{
  "active": true,
  "customFields": {
    "lead": [
      {
        "key": "branche",
        "kind": "text",
        "label": "Branche"
      }
    ],
    "opportunity": []
  },
  "defaultLeadSource": "MANUAL",
  "leadAutoScoring": true,
  "leadRetentionMonths": 24,
  "vatCheckEnabled": true
}
```

### Responses

- **200** Saved (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `status` (string): (one of `saved`)

Example 200 answer:

```json
{
  "status": "saved"
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/config' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"active":true,"customFields":{"lead":[{"key":"branche","kind":"text","label":"Branche"}],"opportunity":[]},"defaultLeadSource":"MANUAL","leadAutoScoring":true,"leadRetentionMonths":24,"vatCheckEnabled":true}'
```

## Whether the CRM module is active for the tenant (tenant:settings:read)

`GET /api/crm/v1/config/status`

Module: CRM · operationId: `getCrmConfigStatus` · Tag: Configuration · Auth: access token (`Authorization: Bearer <accessToken>`)

### Responses

- **200** Status (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `active` (boolean): Whether the saved configuration is active. `false` without a configuration.

Example 200 answer:

```json
{
  "active": true
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/config/status' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

# NFON telephony

## Send the NFON phone book now (tenant:settings:write)

`POST /api/crm/v1/nfon/sync`

Module: CRM · operationId: `syncNfonPhoneBook` · Tag: NFON telephony · Auth: access token (`Authorization: Bearer <accessToken>`)

Builds the tenant's phone book (see the NFON phone book above) and sends it to comms, which
writes it to NFON in the background; the answer is the run (`entries` sent, numbers left out in
`entryErrors` with action `SKIP`). `full=true` sends it as a full run instead (same as
`syncNfonPhoneBookFull`, answered with `202`). The phone book must be active (`422`
otherwise); while another run of the tenant runs the answer is `409`; without comms `503`.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `full` | query | string |  | `true` runs a full sync. (one of `true`, `false`; default `"false"`) |

### Responses

- **200** Run log (`application/json`)
- **202** `full=true`: the full run was sent (see `syncNfonPhoneBookFull`). (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **409** Another sync of the tenant is running (on any instance, manual or scheduled). (`application/json`)
- **422** The NFON phone book is not active (`not_configured`). (`application/json`)
- **500** The run aborted (contacts or masterdata unreachable, run log not writable), code
`sync_failed`; nothing was sent. `details.log` is the logged run. A failed contact listing never
deletes phone book entries.
 (`application/json`)
- **503** CRM has no connection to comms, so the phone book cannot be sent (`comms_unavailable`). (`application/json`)

Fields of the 200 answer:

- `chunks` (integer, required): Parts the entries were sent in (500 entries each).
- `durationMs` (integer (int64), required): Duration in milliseconds.
- `endTime` (string (date-time), required): End of the run.
- `entries` (integer, required): Phone book entries sent.
- `skipped` (integer, required): Numbers that could not be normalised.
- `startTime` (string (date-time), required): Start of the run.
- `status` (string, required): `SUCCESS`: the phone book was sent to comms; `FAILED`: nothing was sent (`error`). (one of `SUCCESS`, `FAILED`)
- `trigger` (string, required): Started by hand or by a schedule. (one of `MANUAL`, `SCHEDULED`)
- `type` (string, required): `FULL`: comms empties and rebuilds the NFON phone book. (one of `INCREMENTAL`, `FULL`)
- `entryErrors` (array of NfonSyncEntryError): Numbers left out (at most 500 are kept); omitted when none.
  - `action` (string, required): `SKIP`: the number could not be normalised and is not in the phone book. (one of `SKIP`)
  - `message` (string, required): Why the number was left out.
  - `displayName` (string): Name of the contact the number belongs to.
  - `number` (string): The number as stored.
  - `sourceId` (string): The contact the number comes from: `address:<id>`, `contact:<id>` (masterdata) or `lead:<id>`.
- `error` (string): Why the run failed; omitted when it was sent.
- `errors` (array of string): The run-level error; omitted when none.
- `id` (string): Run ID (a decimal number as string).
- `runId` (string (uuid)): The run as comms knows it (a UUIDv7); omitted for a failed run.

Example 200 answer:

```json
{
  "chunks": 1,
  "durationMs": 1834,
  "endTime": "2026-11-18T06:00:01Z",
  "entries": 122,
  "entryErrors": [
    {
      "action": "SKIP",
      "displayName": "Max Muster (Bergmann Bürobedarf KG)",
      "message": "Rufnummer kann nicht in das internationale Format (E.164) gebracht werden",
      "number": "0941/600700 Zentrale",
      "sourceId": "contact:7c9e6679-7425-40de-944b-e07fc1f90ae7"
    }
  ],
  "id": "4711",
  "runId": "01a1c67f-4f22-7d4d-9670-e186b38b7055",
  "skipped": 1,
  "startTime": "2026-11-18T06:00:00Z",
  "status": "SUCCESS",
  "trigger": "SCHEDULED",
  "type": "INCREMENTAL"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/nfon/sync' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Send the NFON phone book as a full run (tenant:settings:write)

`POST /api/crm/v1/nfon/sync/full`

Module: CRM · operationId: `syncNfonPhoneBookFull` · Tag: NFON telephony · Auth: access token (`Authorization: Bearer <accessToken>`)

Sends the tenant's phone book to comms as a full run: comms deletes every entry of the NFON
phone book and recreates it, in the background. The answer is `202` with the sent run. Same
preconditions as `syncNfonPhoneBook` (`422`, `409` while another run of the tenant runs, `503`
without comms).

### Responses

- **202** The full run was sent to comms (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **409** Another sync of the tenant is running (on any instance, manual or scheduled). (`application/json`)
- **422** The NFON phone book is not active (`not_configured`). (`application/json`)
- **500** The run aborted (contacts or masterdata unreachable, run log not writable), code
`sync_failed`; nothing was sent. `details.log` is the logged run. A failed contact listing never
deletes phone book entries.
 (`application/json`)
- **503** CRM has no connection to comms, so the phone book cannot be sent (`comms_unavailable`). (`application/json`)

Fields of the 202 answer:

- `chunks` (integer, required): Parts the entries were sent in (500 entries each).
- `durationMs` (integer (int64), required): Duration in milliseconds.
- `endTime` (string (date-time), required): End of the run.
- `entries` (integer, required): Phone book entries sent.
- `skipped` (integer, required): Numbers that could not be normalised.
- `startTime` (string (date-time), required): Start of the run.
- `status` (string, required): `SUCCESS`: the phone book was sent to comms; `FAILED`: nothing was sent (`error`). (one of `SUCCESS`, `FAILED`)
- `trigger` (string, required): Started by hand or by a schedule. (one of `MANUAL`, `SCHEDULED`)
- `type` (string, required): `FULL`: comms empties and rebuilds the NFON phone book. (one of `INCREMENTAL`, `FULL`)
- `entryErrors` (array of NfonSyncEntryError): Numbers left out (at most 500 are kept); omitted when none.
  - `action` (string, required): `SKIP`: the number could not be normalised and is not in the phone book. (one of `SKIP`)
  - `message` (string, required): Why the number was left out.
  - `displayName` (string): Name of the contact the number belongs to.
  - `number` (string): The number as stored.
  - `sourceId` (string): The contact the number comes from: `address:<id>`, `contact:<id>` (masterdata) or `lead:<id>`.
- `error` (string): Why the run failed; omitted when it was sent.
- `errors` (array of string): The run-level error; omitted when none.
- `id` (string): Run ID (a decimal number as string).
- `runId` (string (uuid)): The run as comms knows it (a UUIDv7); omitted for a failed run.

Example 202 answer:

```json
{
  "chunks": 1,
  "durationMs": 1834,
  "endTime": "2026-11-18T06:00:01Z",
  "entries": 122,
  "entryErrors": [
    {
      "action": "SKIP",
      "displayName": "Max Muster (Bergmann Bürobedarf KG)",
      "message": "Rufnummer kann nicht in das internationale Format (E.164) gebracht werden",
      "number": "0941/600700 Zentrale",
      "sourceId": "contact:7c9e6679-7425-40de-944b-e07fc1f90ae7"
    }
  ],
  "id": "4711",
  "runId": "01a1c67f-4f22-7d4d-9670-e186b38b7055",
  "skipped": 1,
  "startTime": "2026-11-18T06:00:00Z",
  "status": "SUCCESS",
  "trigger": "SCHEDULED",
  "type": "INCREMENTAL"
}
```

### Example request

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/nfon/sync/full' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## List the latest NFON sync runs (tenant:settings:read)

`GET /api/crm/v1/nfon/sync/runs`

Module: CRM · operationId: `listNfonSyncRuns` · Tag: NFON telephony · Auth: access token (`Authorization: Bearer <accessToken>`)

The latest runs of the tenant, newest first, manual and scheduled, with the numbers they left
out (at most 500 per run are kept). The last 200 runs per tenant are kept.

### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `limit` | query | integer |  | Number of runs, 1–100; any other value is `400 invalid`. (default `20`; max 100) |

### Responses

- **200** Runs (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `items` (array of NfonSyncRunLog, required): Runs, newest first.
  - `chunks` (integer, required): Parts the entries were sent in (500 entries each).
  - `durationMs` (integer (int64), required): Duration in milliseconds.
  - `endTime` (string (date-time), required): End of the run.
  - `entries` (integer, required): Phone book entries sent.
  - `skipped` (integer, required): Numbers that could not be normalised.
  - `startTime` (string (date-time), required): Start of the run.
  - `status` (string, required): `SUCCESS`: the phone book was sent to comms; `FAILED`: nothing was sent (`error`). (one of `SUCCESS`, `FAILED`)
  - `trigger` (string, required): Started by hand or by a schedule. (one of `MANUAL`, `SCHEDULED`)
  - `type` (string, required): `FULL`: comms empties and rebuilds the NFON phone book. (one of `INCREMENTAL`, `FULL`)
  - `entryErrors` (array of NfonSyncEntryError): Numbers left out (at most 500 are kept); omitted when none.
    - `action` (string, required): `SKIP`: the number could not be normalised and is not in the phone book. (one of `SKIP`)
    - `message` (string, required): Why the number was left out.
    - `displayName` (string): Name of the contact the number belongs to.
    - `number` (string): The number as stored.
    - `sourceId` (string): The contact the number comes from: `address:<id>`, `contact:<id>` (masterdata) or `lead:<id>`.
  - `error` (string): Why the run failed; omitted when it was sent.
  - `errors` (array of string): The run-level error; omitted when none.
  - `id` (string): Run ID (a decimal number as string).
  - `runId` (string (uuid)): The run as comms knows it (a UUIDv7); omitted for a failed run.

Example 200 answer:

```json
{
  "items": [
    {
      "chunks": 1,
      "durationMs": 1834,
      "endTime": "2026-11-18T06:00:01Z",
      "entries": 122,
      "entryErrors": [
        {
          "action": "SKIP",
          "displayName": "Max Muster (Bergmann Bürobedarf KG)",
          "message": "Rufnummer kann nicht in das internationale Format (E.164) gebracht werden",
          "number": "0941/600700 Zentrale",
          "sourceId": "contact:7c9e6679-7425-40de-944b-e07fc1f90ae7"
        }
      ],
      "id": "4711",
      "runId": "01a1c67f-4f22-7d4d-9670-e186b38b7055",
      "skipped": 1,
      "startTime": "2026-11-18T06:00:00Z",
      "status": "SUCCESS",
      "trigger": "SCHEDULED",
      "type": "INCREMENTAL"
    }
  ]
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/nfon/sync/runs' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## NFON sync status and entry counts (tenant:settings:read)

`GET /api/crm/v1/nfon/sync/status`

Module: CRM · operationId: `getNfonSyncStatus` · Tag: NFON telephony · Auth: access token (`Authorization: Bearer <accessToken>`)

Served from the run log; it never calls comms or NFON. `totalEntries` is the number of
entries of the latest run that was sent. `lastSync` is the most recently logged run,
`lastCheckTime` the start of the latest run, or the time a scheduled run found nothing new.

### Responses

- **200** Status (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `active` (boolean, required): Whether the phone book is active.
- `isSyncing` (boolean, required): A run of the tenant is running on some instance.
- `totalEntries` (integer, required): Entries of the latest run that was sent.
- `lastCheckTime` (string (date-time)): Start of the latest run, or the time a scheduled run found nothing new.
- `lastFullSyncTime` (string (date-time)): Start of the most recent full sync.
- `lastSync` (NfonSyncRunLog)
  - `chunks` (integer, required): Parts the entries were sent in (500 entries each).
  - `durationMs` (integer (int64), required): Duration in milliseconds.
  - `endTime` (string (date-time), required): End of the run.
  - `entries` (integer, required): Phone book entries sent.
  - `skipped` (integer, required): Numbers that could not be normalised.
  - `startTime` (string (date-time), required): Start of the run.
  - `status` (string, required): `SUCCESS`: the phone book was sent to comms; `FAILED`: nothing was sent (`error`). (one of `SUCCESS`, `FAILED`)
  - `trigger` (string, required): Started by hand or by a schedule. (one of `MANUAL`, `SCHEDULED`)
  - `type` (string, required): `FULL`: comms empties and rebuilds the NFON phone book. (one of `INCREMENTAL`, `FULL`)
  - `entryErrors` (array of NfonSyncEntryError): Numbers left out (at most 500 are kept); omitted when none.
    - `action` (string, required): `SKIP`: the number could not be normalised and is not in the phone book. (one of `SKIP`)
    - `message` (string, required): Why the number was left out.
    - `displayName` (string): Name of the contact the number belongs to.
    - `number` (string): The number as stored.
    - `sourceId` (string): The contact the number comes from: `address:<id>`, `contact:<id>` (masterdata) or `lead:<id>`.
  - `error` (string): Why the run failed; omitted when it was sent.
  - `errors` (array of string): The run-level error; omitted when none.
  - `id` (string): Run ID (a decimal number as string).
  - `runId` (string (uuid)): The run as comms knows it (a UUIDv7); omitted for a failed run.

Example 200 answer:

```json
{
  "active": true,
  "isSyncing": false,
  "lastCheckTime": "2026-11-18T06:00:00Z",
  "lastFullSyncTime": "2026-11-15T02:00:00Z",
  "lastSync": {
    "chunks": 1,
    "durationMs": 1834,
    "endTime": "2026-11-18T06:00:01Z",
    "entries": 122,
    "entryErrors": [
      {
        "action": "SKIP",
        "displayName": "Max Muster (Bergmann Bürobedarf KG)",
        "message": "Rufnummer kann nicht in das internationale Format (E.164) gebracht werden",
        "number": "0941/600700 Zentrale",
        "sourceId": "contact:7c9e6679-7425-40de-944b-e07fc1f90ae7"
      }
    ],
    "id": "4711",
    "runId": "01a1c67f-4f22-7d4d-9670-e186b38b7055",
    "skipped": 1,
    "startTime": "2026-11-18T06:00:00Z",
    "status": "SUCCESS",
    "trigger": "SCHEDULED",
    "type": "INCREMENTAL"
  },
  "totalEntries": 122
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/nfon/sync/status' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Get the NFON phone book settings (tenant:settings:read)

`GET /api/crm/v1/nfon/config`

Module: CRM · operationId: `getNfonConfig` · Tag: NFON telephony · Auth: access token (`Authorization: Bearer <accessToken>`)

The `nfon` section of the module configuration. The `lastSync*` fields describe the most
recently started run. The NFON account and its API key are set up in comms.

### Responses

- **200** Settings (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `active` (boolean): The phone book is sent only when active.
- `fullSyncCron` (string): Schedule of the full run (comms empties and rebuilds the NFON phone book), same format. Missing: Sundays at 03:00 (`0 3 * * 0`); empty: no scheduled full run. When both schedules are due, the full run is sent.
- `includeLeads` (boolean): Also put the CRM leads with a phone number into the phone book (after the masterdata contacts). (default `true`)
- `lastSync` (string (date-time), read-only): Start of the most recent run.
- `lastSyncCount` (integer, read-only): Entries the most recent run sent.
- `lastSyncError` (string, read-only): First error of the most recent run.
- `lastSyncStatus` (string, read-only): Status of the most recent run. (one of `SUCCESS`, `FAILED`)
- `syncIntervalCron` (string): Schedule of the regular run: a 5-field cron expression in German time (prefix `CRON_TZ=<zone>` for another zone). Empty: no scheduled regular run; responses leave the field out then. A scheduled run sends only when something changed.

Example 200 answer:

```json
{
  "active": true,
  "fullSyncCron": "0 3 * * 0",
  "includeLeads": true,
  "syncIntervalCron": "* * * * *"
}
```

### Example request

```bash
curl -X GET 'https://api.mbcom.cloud/api/crm/v1/nfon/config' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Save the NFON phone book settings (tenant:settings:write)

`PUT /api/crm/v1/nfon/config`

Module: CRM · operationId: `saveNfonConfig` · Tag: NFON telephony · Auth: access token (`Authorization: Bearer <accessToken>`)

Replaces the `nfon` section of the module configuration; the rest stays unchanged. The
`lastSync*` fields are ignored. A `syncIntervalCron` or `fullSyncCron` that is no 5-field cron
expression is refused with `400`.

### Request body

`application/json` (required)

- `active` (boolean): The phone book is sent only when active.
- `fullSyncCron` (string): Schedule of the full run (comms empties and rebuilds the NFON phone book), same format. Missing: Sundays at 03:00 (`0 3 * * 0`); empty: no scheduled full run. When both schedules are due, the full run is sent.
- `includeLeads` (boolean): Also put the CRM leads with a phone number into the phone book (after the masterdata contacts). (default `true`)
- `lastSync` (string (date-time), read-only): Start of the most recent run.
- `lastSyncCount` (integer, read-only): Entries the most recent run sent.
- `lastSyncError` (string, read-only): First error of the most recent run.
- `lastSyncStatus` (string, read-only): Status of the most recent run. (one of `SUCCESS`, `FAILED`)
- `syncIntervalCron` (string): Schedule of the regular run: a 5-field cron expression in German time (prefix `CRON_TZ=<zone>` for another zone). Empty: no scheduled regular run; responses leave the field out then. A scheduled run sends only when something changed.

Example:

```json
{
  "active": true,
  "fullSyncCron": "0 3 * * 0",
  "includeLeads": true,
  "syncIntervalCron": "* * * * *"
}
```

### Responses

- **200** Saved (`application/json`)
- **400** Invalid input (`invalid`): `field` names the first invalid field, `details.fields` every one (JSON paths for
bodies, parameter names for the query). Some refusals have their own code (`invalid_sort`,
`invalid_stages`, `invalid_custom_fields`, `convert_target_required`, `invalid_csv`, …).
 (`application/json`)
- **401** Missing, invalid or expired token (no body).
- **403** The token lacks the permission (`insufficient permissions`) or has no active tenant.
 (`application/json`)
- **500** Unexpected error; details are only logged. (`application/json`)

Fields of the 200 answer:

- `message` (string): What happened.

Example 200 answer:

```json
{
  "message": "NFON configuration saved successfully"
}
```

### Example request

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/nfon/config' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{"active":true,"fullSyncCron":"0 3 * * 0","includeLeads":true,"syncIntervalCron":"* * * * *"}'
```

