## 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'
```
