# Leads and opportunities (CRM)

The CRM keeps a tenant's sales pipeline: **leads** (prospects), **opportunities** (possible deals) in a configurable
pipeline of **stages**, **activities** and campaigns. Customers themselves are master data
[addresses](/guides/masterdata): a lead becomes a customer by **conversion**. Everything below is under
`https://api.mbcom.cloud/api/crm/v1`; every operation is in the [CRM reference](/reference/crm).

| Step | Operations | Permission |
|---|---|---|
| Capture leads | [`findLeadDuplicates`](/reference/crm/findLeadDuplicates), [`createLead`](/reference/crm/createLead), [`updateLead`](/reference/crm/updateLead), [`listLeads`](/reference/crm/listLeads) | write: `tenant:crm:write`, read: `tenant:crm:read` |
| Convert | [`convertLead`](/reference/crm/convertLead) | `tenant:crm:write` |
| Pipeline | [`listStages`](/reference/crm/listStages), [`createOpportunity`](/reference/crm/createOpportunity), [`updateOpportunity`](/reference/crm/updateOpportunity), [`listOpportunities`](/reference/crm/listOpportunities) | `tenant:crm:read` / `tenant:crm:write` |
| History | [`createActivity`](/reference/crm/createActivity), [`listActivities`](/reference/crm/listActivities) | `tenant:crm:write` / `tenant:crm:read` |
| Sales documents | [`listOpportunityDocuments`](/reference/crm/listOpportunityDocuments) | `tenant:crm:read` |

Requests are **not idempotent** (only `importLeads` and `sendContactMail` take an `Idempotency-Key`): a retried
`POST` creates a second record, so check before you create again after a timeout. `PUT` on leads and opportunities
is a **partial update** – only the fields you send change; `null` counts as not sent, an empty string empties a text
field. There is no `version`: for the same field the last write wins.

## Capture a lead

A lead needs `company` and `contactName`; it starts in status `NEW`.

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/leads' \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' \
  -d '{
    "company": "Muster Haustechnik GmbH",
    "contactName": "Erika Musterfrau",
    "email": "erika.musterfrau@muster-haustechnik.example",
    "phone": "+49 30 1234567",
    "source": "WEBSITE",
    "consent": true,
    "consentSource": "Kontaktformular"
  }'
```

**Duplicates:** a lead with the same normalised company name or e-mail address as an existing lead or master data
address answers **409** `duplicate_lead` with the `candidates` (and `masterdataUnavailable: true` when only leads
could be searched). Show them to a person, or link to the existing record; send `force: true` only when the lead is
really new. [`findLeadDuplicates`](/reference/crm/findLeadDuplicates) (`?company=…&email=…`) runs the same check
before you create.

- Without `ownerEmail` the calling person owns the lead – with a service account key, set it to the sales person.
- `customFields` are validated against the tenant's field definitions (`400 invalid_custom_fields`); read them from
  [`getCrmConfig`](/reference/crm/getCrmConfig).
- `score` (0–100) is calculated when the tenant has lead scoring on; a score you send wins for that write.

Work the lead through `NEW → CONTACTED → QUALIFIED` (or `LOST`) with [`updateLead`](/reference/crm/updateLead).
`CONVERTED` is reached only by conversion (`400 lead_convert_required` otherwise). Record calls, meetings, mails and
notes as activities ([`createActivity`](/reference/crm/createActivity) with `leadId`, `opportunityId` or `addressId`).
A tenant can anonymise old leads automatically; an anonymised lead is read-only (`409 lead_anonymized`).

## Convert a lead

[`convertLead`](/reference/crm/convertLead) turns a qualified lead into a customer: it links the lead to a master data
address (`convertedAddressId`), sets `CONVERTED` and can create the first opportunity in the same step. Send
**exactly one** of:

- `addressId` – the lead is an existing customer (an unknown address is **422**), or
- `createAddress` – master data creates the company address (status `INTERESSENT`, the lead's contact as contact
  person).

```bash
curl -X POST 'https://api.mbcom.cloud/api/crm/v1/leads/5f1c…/convert' \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' \
  -d '{
    "createAddress": { "companyName": "Muster Haustechnik GmbH", "street": "Musterweg 5", "zip": "12345", "city": "Musterstadt", "country": "DE" },
    "opportunity": { "title": "Wartungsvertrag Standorte Süd", "value": 24000, "stageKey": "QUALIFICATION" }
  }'
```

The answer is the converted lead with the created `opportunity`. Neither or both targets are **400**
`convert_target_required`; the opportunity is checked before master data is called, so a wrong `stageKey`
(`400 unknown_stage`) or custom field creates nothing. A lead is converted once: a second call – also a parallel one –
answers **409** `lead_converted`. A retry after a timeout reuses the address created for the lead, so it is safe.
**502** means master data could not be reached: retry later.

## Move opportunities through the pipeline

Stages are tenant configuration: read them with [`listStages`](/reference/crm/listStages) instead of hard-coding
keys. Each stage has a `key`, a `label`, a default `probability` and a `phase` – `open`, `won` or `lost` – which is
what your logic should rely on; archived stages cannot be chosen. A tenant that never changed them has `PROSPECTING`,
`QUALIFICATION`, `PROPOSAL`, `NEGOTIATION`, `CLOSED_WON` and `CLOSED_LOST`.

[`createOpportunity`](/reference/crm/createOpportunity) needs a `title`; `leadId` and `addressId` link it (both are
checked, `422` otherwise), `stage` defaults to the first open stage, `probability` to the stage's, `value` to 0. Move
it with [`updateOpportunity`](/reference/crm/updateOpportunity):

```bash
curl -X PUT 'https://api.mbcom.cloud/api/crm/v1/opportunities/8a2d…' \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' \
  -d '{"stage": "CLOSED_LOST", "lostReason": "Budget verschoben"}'
```

- A stage change without `probability` takes the stage's probability and writes a `SYSTEM` activity (the history).
- Entering a won or lost stage sets `closedAt` (leaving it clears it); a lost stage needs `lostReason`
  (**422** `lost_reason_required`). An unknown or archived stage is **400** `unknown_stage`.
- **Offers and orders win opportunities:** a [trade](/guides/trade) offer or order with the opportunity's
  `opportunityId` shows up in [`listOpportunityDocuments`](/reference/crm/listOpportunityDocuments); an offer that
  becomes `ACCEPTED` or a new order moves an open opportunity to the tenant's first won stage. A rejected or expired
  offer is only noted – a person decides whether the deal is lost.

[`listOpportunities`](/reference/crm/listOpportunities) filters by `stage`, `phase`, `addressId`, `leadId`, `owner`
(`me` or an e-mail) and expected close date, and pages by cursor like every CRM list (`limit` 1–200, `cursor`, keep
`sort` and filters; see [Pagination](/guides/pagination)). [`getPipelineReport`](/reference/crm/getPipelineReport)
sums the open pipeline per stage, month and owner.

## Events

To push CRM changes to your system, a [flow](/guides/flows) can start on
`crm.lead.created`, `crm.lead.converted`, `crm.opportunity.created`, `crm.opportunity.won`, `crm.opportunity.lost`
and others (the flows catalogue lists them) and deliver them to your [webhook](/guides/webhooks) channel. They carry
ids and key fields (status, stage, value): read the record for the rest.
