# Native import

> For AI agents: the index of these docs is at https://referalli.com/docs/llms.txt (every page it lists has a Markdown version like this one).

Load partners, links, coupons, referrals and commission history from your own system with one NDJSON file: row types, fields, commission states, code aliases, the dry-run report and limits.

`POST /v1/import/native` loads another system's data from an NDJSON body: one JSON object per line, each with a `type` of `partner`, `referral`, `commission` or `payout`. It needs an owner or admin session or an API key. The migration walk-through is in the Migrating guide; this page is the contract.

```bash
curl -X POST "https://referalli.com/v1/import/native?dryRun=true" \
  -H "Authorization: Bearer $KEY" -H "content-type: application/x-ndjson" \
  --data-binary @export.ndjson
```

Drop `?dryRun=true` for the real run. The OpenAPI document has a schema per row type (`NativeImportPartnerRow`, `NativeImportReferralRow`, `NativeImportCommissionRow`, `NativeImportPayoutRow`, and `NativeImportRow` for any of them).

## Limits and order

- At most 10,000 non-blank lines and 5 MB per request. More is `413 payload_too_large`.
- Rows are processed partners first, then referrals, commissions and payouts, each group in file order, so a referral, commission or payout may name a partner defined later in the file.
- Every row runs in its own transaction. A row that fails writes nothing and is listed in `errors`; the other rows still load.
- Unknown fields are an error (the row schemas are strict); the error names the fields that row type takes, and the likely one for a common other name (`code` → `coupon`, `name` → `displayName`). `programId` must be a program of your organization. It goes on each row; `?programId=prg_…` sets it for the rows that leave it out.
- A partner's code goes in `coupon` (one or a list) and its name in `displayName`.

## Partner row

| Field | Notes |
| --- | --- |
| `type` | `"partner"` |
| `programId` | Required. The partner is enrolled in this program. |
| `externalRef` | Required, 1-256 characters. Your id for the partner; later rows name the partner by it. |
| `email` | Required for a partner Referalli does not have yet. An existing partner with that email and no `externalRef` gets this `externalRef`. One that already has a different `externalRef` (the same person in another product's program, in an org shared by products) keeps it, and is enrolled in this program with this `externalRef` as their id here: rows, events and lookups for this program find them by either. A product can use the same `externalRef` for the person in all its programs. An enrollment that has no id of its own yet gets this one. It's an error only when they're already in this program under another id, and an `externalRef` always means one person in the org. `created.enrollments` counts the program enrollments made, including an existing partner joining this program. |
| `displayName` | Optional. Defaults to the email. |
| `coupon` | One code or an array, 2-64 characters of `A-Z a-z 0-9 -`. |
| `links` | Up to 100 of `{code, label, status, cookieWindowDays, commission: {bps}, destinationUrl}`. `code` is 1-64 characters of `A-Za-z0-9-`; `status` is `active` or `disabled`; `cookieWindowDays` 1-180; `commission.bps` 0-10000. |
| `key` | Optional idempotency key, see below. |

A partner already known by `externalRef` is reused (and enrolled in the program if it was not).

## Referral row

| Field | Notes |
| --- | --- |
| `type` | `"referral"` |
| `programId`, `partnerExternalRef`, `customerRef` | Required. The partner must exist. |
| `referredAt` | ISO 8601 timestamp with offset. Required unless `signedUpAt` is sent. |
| `signedUpAt` | Alias of `referredAt`; `referredAt` wins when both are sent. |
| `matchedVia` | Optional, only `"import"`. |
| `payBounties` | Optional, only `false`. |
| `key` | Optional. |

The referral is stored as active, matched manually (so attribution replay never recomputes it), with its window ending `referredAt` plus the program's sign-up-to-conversion days. A customer who already has a live referral in the program with the same partner counts as `existing`; with another partner it is an error.

### Bounties and referee rewards

Imported referrals are inserted directly and publish no event, so no sign-up bounty, no referee reward (including mirror rewards) and no webhook fires for them, whether or not you send `payBounties: false`. History is never re-paid.

### First-earning rules

A rule with `recurring: {"type": "first_earning_payment_after_referral"}` pays on the first payment that earns. An imported commission line that names the referral's `customerRef`, with any state, counts as that earning, so the referral's next real payment does not earn again as the first. A commission row without `customerRef` is not linked to a referral and does not count. Imported commissions do not create payment records, so for the other recurring types (`one_time`, `months`) the referral's next real payment is still seen as its first payment.

## Commission row

| Field | Notes |
| --- | --- |
| `type` | `"commission"` |
| `programId`, `partnerExternalRef` | Required. The partner must exist. |
| `customerRef` | Optional. Links the line to that customer's referral in the program, if there is one. |
| `amountMinor` | Required positive integer, minor units. |
| `currency` | Required 3 letters; stored lower case. |
| `state` | Required, see below. |
| `holdUntil` | ISO timestamp. For `pending`, `held`, `approved`. |
| `paidAt` | ISO timestamp. For `paid` only; defaults to the time of the import. |
| `payoutRef` | Your payout id, 1-200 characters. For `paid` only. |
| `baseMinor` | Optional integer, the amount the commission was computed on. |
| `orderRef` | Optional. The order's invoice or charge ref: a later `refund` or `dispute` billing event whose `invoiceRef` or `metadata.chargeRef` equals it follows this line. Needs `grossMinor`. |
| `grossMinor` | Positive integer, what the customer paid for the order. Needs `orderRef`. |
| `bps` | 0-10000, the commission share of `baseMinor`. Needs `orderRef` and `baseMinor`. |
| `strictlyBelowBase` | Optional boolean; see below. Needs `orderRef` and `baseMinor`. |
| `reference` | Optional, 1-200 characters. Your id for the line; kept in the line's memo as `imported:native:<reference>`. |
| `key` | Optional. |

`paidAt` or `payoutRef` on another state, `holdUntil` on `paid` or `reversed`, and `held` without `holdUntil` are row errors.

### States

All lines are written as ledger events, never updated. Nothing is published, so no webhook and no merchant-credit settlement runs.

| `state` | Written | Result |
| --- | --- | --- |
| `pending` | `earned` (hold until `holdUntil`, else now) | Pending; approves like any line once the hold ends. |
| `held` | same as `pending` | Same as `pending`, but `holdUntil` is required. |
| `approved` | `earned`, then `approved` | Approved, unpaid: included in the partner's next payout run. |
| `paid` | `earned`, `approved`, `paid` (timestamp `paidAt`) | Paid. |
| `reversed` | `earned`, then `reversed` for `-amountMinor` | Net zero, kept for history. |

`baseMinor` and `payoutRef` are stored on the earned line, and `payoutRef` also on the `paid` event (columns `base_minor`, `payout_ref`). The ledger invariant (everything earned equals pending plus approved plus paid) holds after every state.

### Refunds and disputes after the import

A line with `orderRef`, `grossMinor`, `baseMinor` and `bps` is re-priced by later generic billing events (`POST /v1/billing/events` or any billing connector) on that order, exactly like a billed line. The import records the order as a paid `import` billing event, so the refund is matched instead of parked. With `realisedBase = baseMinor x (grossMinor - refunded) / grossMinor`:

- Commission is `bps` of `realisedBase`; with `strictlyBelowBase: true` it is at most `realisedBase - 1` (the commission stays strictly below its base), and a full refund gives 0.
- Any `dispute` sets it to 0.
- The difference to what the line still holds is one `reversed` event (never an update). The line's earned amount is never raised, and re-sending a refund (same provider event id) or one that leaves the target unchanged writes nothing.
- Example: `baseMinor` 1000, `bps` 3000, `grossMinor` 10000, `amountMinor` 300. A refund of 4000 makes it 180 (reversal -120); a later dispute makes it 0 (reversal -180).
- A line with `orderRef` but no `bps` and `baseMinor` is clawed back pro rata, like any billed line.
- A reversal of a line already `paid` is recorded the same way a native paid-line reversal is: the line's paid net drops and the merchant recovers it; Referalli has no payout offset to apply, and the line is not paid again.

A line with a `paid` event is excluded from payout runs, so a paid line is never paid again. An imported `paid` line does not create a Referalli payout record; `payoutRef` is your reference to the one on your side.

## Payout row

Records a payout you made before Referalli. Import it after its commissions (rows are processed in that order); commissions name it in `payoutRef`, equal to the payout's `providerRef`, and the payout's `lineIds` are the partner's lines with that `payoutRef`.

| Field | Notes |
| --- | --- |
| `type` | `"payout"` |
| `programId`, `partnerExternalRef` | Required. The partner must exist. |
| `amountMinor` | Required positive integer, `currency` 3 letters. |
| `paidAt` | Required ISO timestamp (stored as `sentAt`). |
| `status` | `paid`, `failed` or `reversed` (stored as `sent`, `failed`, `reversed`). |
| `provider` | Required, e.g. `stripe_connect` (stored as the payout's `rail`). |
| `providerRef` | Required, your transfer id (`railRef`). Row identity is `key`, else `payout:<provider>:<providerRef>`. |

The payout appears in `GET /v1/payouts` (filter `partnerId`) and the partner portal with `imported: true` and no `runId`. Payout runs never include it or its lines (paid lines already carry a `paid` event, whatever the payout's status). A dry run counts `created.payouts`.

To record a later failure or reversal, `POST /v1/payouts/{id}/status` with `{"status": "failed" | "reversed", "reason"?}` (imported payouts only; owner, admin or finance). A provider `failed` webhook that matches the transfer by `railRef` does the same for `failed`. This only records status: the lines stay paid and Referalli never pays them again, because you settled them outside Referalli.

## Idempotency and resuming

A row is identified by, in order: its `key`; for a commission, `commission:<programId>:<reference>`; otherwise the SHA-256 of the row's JSON. A row seen before is skipped and counted in `duplicates`, except a `partner` row: it runs again (it's idempotent), so it can add this program's `externalRef` to an enrollment that lacks it, and still counts as a duplicate. Rows are recorded only by a real run, in the same transaction as their data, and only when they succeed. So:

- Re-sending the same file is safe and resumable: finished rows are `duplicates`, failed rows are tried again. Fix the failed lines in place and re-send; a changed row without a `key` has a new hash and counts as new.
- With a `key`, an edited row is still treated as already imported. Use `key` only when the row must never be applied twice.
- A `reference` identifies a commission by itself: the same `reference` in the same program is a duplicate even if the amount changed.
- The standard `Idempotency-Key` header also works: the same key and body within 24 hours returns the first response without running again. A dry run never records anything.

## Codes and aliases

Link codes and coupon codes are unique per organization, across all programs, ignoring case. Link codes are stored lower case.

- A code the same partner already holds in the same program is `existing`, nothing changes.
- A code held by anyone else (another partner, or the same partner in another program) is a collision. The row is created under `<code>-<program slug>`, then `<code>-<program slug>-2`, `-3`, and so on (lower case, trimmed to 64 characters), and the spelling you sent is saved as an alias of it, per program.
- The holder that was there first keeps the plain spelling.
- An alias resolves when the request names the program (`couponCode` with `programId`, `/go` or `?via=` on the program's link domain, `?program=<slug>`, the lead form with `?program=`), and everywhere when only one program holds that spelling. Aliases of disabled links are skipped.
- Two partners in the same program importing the same colliding spelling: the second row fails (one alias per spelling per program) and is listed in `errors`.

## Response

```json
{
  "dryRun": true,
  "rows": 3,
  "created": { "partners": 1, "links": 1, "coupons": 1, "referrals": 1, "commissions": 1, "aliases": 0 },
  "duplicates": 0,
  "existing": 0,
  "collisions": [
    { "kind": "coupon", "programId": "prg_…", "partnerExternalRef": "usr_42", "code": "SAVE10", "proposed": "save10-prog-b", "resolved": false }
  ],
  "errors": [
    { "line": 7, "row": 7, "error": "no partner with externalRef usr_99" }
  ]
}
```

- `rows`: non-blank lines in the body.
- `created`: counts of what was created (a dry run: what would be). `aliases` counts old spellings kept for renamed codes.
- `duplicates`: rows skipped as already imported. `existing`: links, coupons and referrals that already existed unchanged.
- `collisions`: one entry per renamed code. `code` is what you sent, `proposed` is what was created, `resolved` is `false` on a dry run and `true` once written.
- `errors`: one per failed row. `line` is the 1-based line of the body (blank lines count), `row` is the same number. `error` joins schema problems as `path: message; …`, or says `not valid JSON`. A failed row's counts are not included in `created`.

A dry run runs the same row checks and writes nothing, so it reports the errors a real run would. It tracks the partners and codes it would have created, so renames inside the file are reported too.

The real run is audited as `import.native`.

---

## For AI agents

- This page for a human reader: https://referalli.com/docs/native-import
- The whole space as one Markdown file: https://referalli.com/docs/llms-full.txt
- Live search + fetch over MCP: https://referalli.com/docs/_api/public/orgs/07f432f4-34b9-46a7-aaad-c0e395d2e4f9/spaces/2bf4f614-3630-4fbf-85f9-5ecafa6b7d97/mcp
  - Install (Claude CLI): `claude mcp add referalli --transport http https://referalli.com/docs/_api/public/orgs/07f432f4-34b9-46a7-aaad-c0e395d2e4f9/spaces/2bf4f614-3630-4fbf-85f9-5ecafa6b7d97/mcp`

This Markdown is the same content the page renders — safe to quote and to ground answers in.
