# Billyou API - Complete Reference

> Auto-generated from the Billyou OpenAPI specification (`openapi-snapshot.json`).
> Do not edit by hand — regenerate with `npm run generate:llm-context` in `frontend-apps/developer-portal`.

## Overview

Billyou is an invoice management API for Romanian businesses. It provides full invoice lifecycle management, PDF generation, payment tracking, client management, Romanian e-Factura (ANAF) integration, e-Transport declarations, webhooks, OAuth 2.0 client-credentials access, and B2B2C partner account provisioning.

**Base URL**: `https://app.billyou.ro/api`
**Authentication**: `X-API-Key` header (or OAuth 2.0 bearer token via `POST /oauth/token`)
**API versioning**: date-based, selected with the `Billyou-Version` header (current version: `2026-03-01`)
**Rate limit**: 60 requests/minute per organization by default (sliding window)

## Authentication

All requests require an API key in the `X-API-Key` header:

```
X-API-Key: bk_user_your_api_key_here
```

API keys use the `bk_user_*` prefix for both sandbox and production environments.
The environment is determined by which environment the key was created in.

Alternatively, OAuth 2.0 client-credentials tokens obtained from `POST /oauth/token` can be sent as `Authorization: Bearer <access_token>`.

## API Versioning

The API is versioned by date. Send the `Billyou-Version` header to pin a version:

```
Billyou-Version: 2026-03-01
```

If the header is omitted, the version pinned to your API key is used, falling back to the latest version. Every response echoes the resolved version in the `Billyou-Version` response header. Deprecated versions add `Deprecation: true` and a `Sunset` header with the retirement date.

## Rate Limits

Requests are rate-limited per organization using a sliding 60-second window (default: **60 requests/minute**, configurable per organization; partner provisioning endpoints default to 600 requests/minute). There is no burst allowance — the sliding window is the only limit.

Rate limit state is returned on every response:

- `X-RateLimit-Limit` — requests allowed per window
- `X-RateLimit-Remaining` — requests left in the current window
- `X-RateLimit-Reset` — Unix timestamp when the window resets
- `Retry-After` — seconds to wait (only on `429` responses, errorCode `RATE_LIMIT_EXCEEDED`)

## Response Format

Success: `{ "success": true, "data": {...}, "meta": {...} }`
Error: `{ "success": false, "errorCode": "CODE", "message": "..." }`

## Endpoints

### Invoices

Invoice management operations including creation, updates, cancellation, and PDF generation. Supports Romanian business rules and VAT compliance.

| Method | Path | Description |
|---|---|---|
| GET | `/invoices` | List invoices with filtering |
| POST | `/invoices` | Create a new invoice or draft |
| POST | `/invoices/branding-preview` | Render a branding-preview invoice PDF |
| GET | `/invoices/saga` | Export issued invoices of a period for Saga |
| GET | `/invoices/{id}` | Get invoice details |
| DELETE | `/invoices/{id}` | Delete an invoice |
| POST | `/invoices/{id}/cancel` | Cancel an invoice |
| POST | `/invoices/{id}/email` | Send invoice by email |
| POST | `/invoices/{id}/finalize` | Convert a proforma invoice to a fiscal invoice |
| GET | `/invoices/{id}/paymentstatus` | Get invoice payment status |
| GET | `/invoices/{id}/pdf` | Get invoice PDF download URL |
| GET | `/invoices/{id}/saga` | Export one issued invoice for Saga |
| POST | `/invoices/{id}/storno` | Issue a storno (reversal) of an invoice |
| GET | `/invoices/{id}/xml` | Get issued invoice e-Factura XML download URL |

#### `GET /invoices` — List invoices with filtering

Retrieve a paginated list of invoices with optional filtering by date range, payment status, and client.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | no | Page number for pagination Default: `1` Example: `1` (min 1) |
| `limit` | integer | no | Number of items per page Default: `20` Example: `20` (min 1, max 100) |
| `startDate` | string (date) | no |  |
| `endDate` | string (date) | no |  |
| `paymentStatus` | string | no | Filter by payment status: 'unpaid' (no payments), 'paid' (fully paid), 'partial' (partially paid), or 'canceled'. Enum: `"unpaid"`, `"paid"`, `"partial"`, `"canceled"` Example: `"paid"` |
| `clientId` | string | no | Filter by specific client ID Example: `"60f7b1b9c9e7b4a1e8d1c2b4"` (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "invoices": [
      {
        "_id": "60f7b1b9c9e7b4a1e8d1c2c1",
        "invoiceId": "fdd6976e-9c10-48de-b890-882160f814f1",
        "filename": "a7ac356d-c952-411c-bbc6-41914ae160e4.pdf",
        "createdAt": "2025-01-15T10:30:00.000Z",
        "paymentStatus": "unpaid",
        "data": {
          "serialNumber": "FACT-00123",
          "invoiceDate": "2025-01-15",
          "paymentDueDate": "2025-02-14",
          "totals": {
            "totalWithoutVAT": 1600,
            "totalVAT": 304,
            "totalWithVAT": 1904
          },
          "client": {
            "name": "SC Example SRL",
            "taxId": "12345678"
          },
          "vendor": {
            "name": "Your Company SRL",
            "taxIdentificationNumber": "98765432"
          }
        }
      }
    ],
    "pagination": {
      "total": 15,
      "page": 1,
      "limit": 20,
      "pages": 1
    }
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /invoices` — Create a new invoice or draft

Create a new invoice or draft for a client with specified services.

**Before Testing**:
1. Get your client ID: Use GET /api/clients to list clients
2. Get your series ID: Use GET /api/series to list invoice series (OR provide a custom serial number)
3. Replace the example `clientId` and `seriesId` with your actual values

**Serial Number Options** (mutually exclusive):
- `seriesId`: Auto-generates next invoice number from series (e.g., "INV-2025-00001")
- `customSerialNumber`: User-defined invoice number (e.g., "CUSTOM-INV-2025-001")

**Draft Mode**: Set `draft: true` to create a draft invoice that can be edited before publishing.

**Language**: Specify "ro" for Romanian (default) or "en" for English PDF generation.

**Romanian county (e-Factura)**: a published (non-draft, non-proforma) invoice is refused with `400` when a Romanian party's county is not one ANAF can code — `EFACTURA_INVALID_COUNTY` for the client (fix the client record) or `EFACTURA_INVALID_VENDOR_COUNTY` for your company address; `details` carries `field` and `value`. Accepted: a county name in any case, with or without diacritics ("Iași", "IASI"), or its ISO 3166-2 code ("IS", "RO-IS"); a city or village ("Purcareni") is not a county. București addresses take the code from the city. A blank county is not refused here.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `clientId` | string | yes | MongoDB ObjectId of the client Example: `"60f7b1b9c9e7b4a1e8d1c2b4"` (pattern `^[0-9a-fA-F]{24}$`) |
| `seriesId` | string | no | Invoice series ID (MongoDB ObjectId). Get available series from GET /api/series endpoint. Mutually exclusive with customSerialNumber. Example: `"60f7b1b9c9e7b4a1e8d1c2b5"` (pattern `^[0-9a-fA-F]{24}$`) |
| `customSerialNumber` | string | no | Custom invoice number (alphanumeric, hyphens, underscores only). Mutually exclusive with seriesId. Example: `"CUSTOM-INV-2025-001"` (min length 1, max length 50, pattern `^[A-Za-z0-9-_]+$`) |
| `draft` | boolean | no | If true, creates a draft invoice that can be edited before publishing. Drafts do not consume series numbers until published. Default: `false` Example: `false` |
| `issueDate` | string (date) | yes | Invoice issue date (ISO 8601 format) Example: `"2024-01-15"` |
| `dueDate` | string (date) | no | Payment due date (ISO 8601 format) Example: `"2024-02-14"` |
| `deliveryDate` | string (date) | no | Actual delivery / supply date (e-Factura BT-72, ISO 8601 format). When provided, the e-Factura XML emits cac:Delivery/cac:ActualDeliveryDate. Example: `"2024-01-14"` |
| `currency` | string | no | ISO 4217 currency code the invoice is priced in (e.g. RON, EUR, USD). Defaults to RON. Item prices and totals are expressed in this currency. Default: `"RON"` Example: `"EUR"` (pattern `^[A-Za-z]{3}$`) |
| `exchangeRate` | number | no | Exchange rate as RON per 1 unit of `currency`. Required when currency is not RON; ignored (forced to 1) for RON. The app uses it to compute the RON total (total × exchangeRate) and e-factura emits the mandatory RON tax total from it (ANAF rule BR-53). Example: `4.9772` |
| `services` | object[] | yes | List of services/products on the invoice (min items 1, max items 50) |
| `services[].description` | string | yes | Item/service name. Maximum 100 characters (ANAF e-factura rule BR-RO-L100). (min length 1, max length 100) |
| `services[].quantity` | number | yes | (min 0.01) |
| `services[].unitPrice` | number | yes | (min 0) |
| `services[].vatRate` | number | yes | VAT rate percentage (e.g., 21 for 21%). For Romanian clients, this must be one of [0, 9, 11, 21] (Romanian VAT, Law 141/2025). For an ordinary sale this is all you need — the tax category is inferred as 'S' (standard). A 0% line requires an explicit taxCategory (see below). |
| `services[].unitOfMeasure` | string | no | Unit of measure (default: 'buc' - pieces) Example: `"buc"` (max length 10) |
| `services[].taxCategory` | string | no | EN 16931 VAT category (v2026-08-01+). OPTIONAL — omit for ordinary sales (inferred 'S'). Use to disambiguate a 0% line: 'S' standard, 'AE' reverse charge (taxare inversă), 'Z' zero-rated, 'E' exempt (also send vatExemptionCode), 'O' outside scope of VAT. Enum: `"S"`, `"AE"`, `"Z"`, `"E"`, `"O"` |
| `services[].vatExemptionCode` | string | no | EN 16931 exemption reason code (VATEX-EU-*). Required when taxCategory is 'E'. Examples: 'VATEX-EU-132' (intra-community supply), 'VATEX-EU-G' (export outside EU), 'VATEX-EU-D' (travel-agent margin), 'VATEX-EU-F' (second-hand margin). |
| `services[].discount` | object | no | Optional per-line discount, applied to the net BEFORE VAT (v2026-08-01+). |
| `services[].discount.type` | string | yes | 'percentage' (0–100) or a fixed 'amount' in the invoice currency. Enum: `"percentage"`, `"amount"` |
| `services[].discount.value` | number | yes | (min 0) |
| `notes` | string | no | Additional notes or payment terms Example: `"Payment due in 30 days"` (max length 1000) |
| `language` | string | no | Invoice PDF language (ro=Romanian, en=English) Enum: `"ro"`, `"en"` Default: `"ro"` Example: `"en"` |
| `documentType` | string | no | Document type. Use "proforma" to create a non-fiscal proforma invoice (FACTURĂ PROFORMĂ). Use POST /:id/finalize to convert it to a fiscal invoice. Defaults to "invoice". Enum: `"invoice"`, `"proforma"` Default: `"invoice"` Example: `"invoice"` |
| `isSelfBilling` | boolean | no | If true, creates an autofacturare (self-billing) invoice where the organization is the buyer and the client is the seller. Default: `false` |
| `selfBillingDetails` | object | no | Required if isSelfBilling is true. Contains the contract details for self-billing. |
| `selfBillingDetails.contractNumber` | string | yes | The number of the self-billing contract. |
| `selfBillingDetails.contractDate` | string (date) | yes | The date of the self-billing contract (ISO 8601 format). |

Example request:

```json
{
  "clientId": "60f7b1b9c9e7b4a1e8d1c2b4",
  "seriesId": "60f7b1b9c9e7b4a1e8d1c2b5",
  "issueDate": "2025-01-15",
  "dueDate": "2025-02-14",
  "services": [
    {
      "description": "Web Development Services",
      "quantity": 8,
      "unitPrice": 150,
      "unitOfMeasure": "hours",
      "vatRate": 21
    },
    {
      "description": "Project Management",
      "quantity": 4,
      "unitPrice": 100,
      "unitOfMeasure": "hours",
      "vatRate": 21
    }
  ],
  "notes": "Payment due in 30 days. Bank transfer preferred.",
  "language": "ro"
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /invoices/branding-preview` — Render a branding-preview invoice PDF

Render a **sample** invoice PDF with the supplied partner branding theme applied.

The invoice content is a fixed, hardcoded Romanian sample — it contains NO real customer data and reads nothing from your account. Only the branding theme (preset, accent colour, logo placement, footer) is taken from the request body. Omit `theme` to render the default Billyou branding.

The response is the PDF binary (`Content-Type: application/pdf`), served inline for embedding in a live preview.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `theme` | object | no |  |
| `theme.schemaVersion` | integer | yes | Enum: `1` |
| `theme.preset` | string | yes | Enum: `"classic"`, `"modern"` |
| `theme.accentColor` | string | no | Hex accent colour, e.g. '#2563eb'. (max length 7) |
| `theme.logoPlacement` | string | no | Enum: `"top-left"`, `"top-center"` |
| `theme.footer` | object | yes |  |
| `theme.footer.mode` | string | yes | Enum: `"billyou"`, `"none"`, `"partner"` |
| `theme.footer.text` | string | no | (max length 120) |
| `theme.footer.url` | string | no | (max length 2048) |

Example request:

```json
{
  "theme": {
    "schemaVersion": 1,
    "preset": "classic",
    "accentColor": "string",
    "logoPlacement": "top-left",
    "footer": {
      "mode": "billyou",
      "text": "string",
      "url": "string"
    }
  }
}
```

**Response** (`200`)

```json
"string"
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /invoices/saga` — Export issued invoices of a period for Saga

Issued invoices in the **Saga C** import format (Saga → Diverse → Import date). The company is the supplier (<FurnizorCIF>), so Saga files them under **Ieșiri**. Storno invoices are included (negative quantities); proformas, drafts and cancelled invoices are not.

Dates are taken on the Romanian (Europe/Bucharest) calendar. Amounts are in the invoice currency; for foreign-currency invoices the BNR rate is stated in FacturaInformatiiSuplimentare. See also the app's "Export Saga" button, which produces the same file.

The period is inclusive and at most 366 days.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `startDate` | string | yes | First invoice date (YYYY-MM-DD) (pattern `^\d{4}-\d{2}-\d{2}$`) |
| `endDate` | string | yes | Last invoice date (YYYY-MM-DD) (pattern `^\d{4}-\d{2}-\d{2}$`) |
| `download` | boolean | no | true: respond with the XML file (Content-Disposition attachment) instead of JSON Default: `false` |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "fileName": "F_44540371_IESIRI-2026-09-01-2026-09-30_04.10.2026.xml",
    "contentType": "application/xml",
    "content": "string",
    "exported": 0,
    "skipped": [
      {
        "id": "string",
        "number": "string",
        "reason": "string"
      }
    ],
    "truncated": true
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 422 | — | Nothing exportable in the period, or the organization has no fiscal code |
| 500 | `INTERNAL_ERROR` | An internal error occurred |
| 504 | — | The export took too long |

#### `GET /invoices/{id}` — Get invoice details

Retrieve detailed information for a specific invoice by its ID.

**Testing**: Replace the example invoice ID with an actual invoice ID from your account. You can get invoice IDs by:
1. Creating a new invoice with POST /api/invoices
2. Listing invoices with GET /api/invoices

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "_id": "60f7b1b9c9e7b4a1e8d1c2c1",
    "invoiceId": "fdd6976e-9c10-48de-b890-882160f814f1",
    "filename": "a7ac356d-c952-411c-bbc6-41914ae160e4.pdf",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "paymentStatus": "unpaid",
    "data": {
      "isVAT": true,
      "currency": "RON",
      "exchangeRate": 1,
      "invoiceDate": "2025-01-15",
      "paymentDueDate": "2025-02-14",
      "paymentDueOption": "custom",
      "items": [
        {
          "description": "Web Development Services",
          "quantity": 8,
          "unitPrice": 150,
          "unitOfMeasure": "hours",
          "VATRate": 21,
          "currency": "RON",
          "exchangeRate": 1,
          "totalWithoutVAT": 1200,
          "VATValue": 252
        },
        {
          "description": "Project Management",
          "quantity": 4,
          "unitPrice": 100,
          "unitOfMeasure": "hours",
          "VATRate": 21,
          "currency": "RON",
          "exchangeRate": 1,
          "totalWithoutVAT": 400,
          "VATValue": 84
        }
      ],
      "totals": {
        "totalWithoutVAT": 1600,
        "totalVAT": 336,
        "totalWithVAT": 1936
      },
      "client": {
        "_id": "60f7b1b9c9e7b4a1e8d1c2b4",
        "name": "SC Example SRL",
        "taxId": "12345678",
        "tradeRegistryNumber": "J40/1234/2020",
        "contactEmails": [
          "contact@example.ro"
        ],
        "address": "Strada Exemplu nr. 123",
        "city": "București",
        "county": "București",
        "postalCode": "010101",
        "country": "România",
        "IBAN": "RO49AAAA1B31007593840000",
        "phone": "+40123456789"
      },
      "vendor": {
        "_id": "60f7b1b9c9e7b4a1e8d1c2b3",
        "name": "Your Company SRL",
        "taxIdentificationNumber": "98765432",
        "tradeRegistryNumber": "J40/5678/2020"
      },
      "additionalNotes": "Payment due in 30 days. Bank transfer preferred.",
      "language": "ro",
      "serialNumber": "FACT-00123"
    }
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `DELETE /invoices/{id}` — Delete an invoice

Delete an invoice. Only the last invoice in a series can be deleted. Invoices with payments or submitted to E-Factura cannot be deleted.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "deleted": true,
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `NOT_LAST_IN_SERIES` | Only the last invoice in series can be deleted. Use cancellation for other invoices. |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /invoices/{id}/cancel` — Cancel an invoice

Cancel an invoice. This creates a cancellation document and marks the invoice as cancelled.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "cancelled": true,
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 409 | — | The document is a proforma, which is not a fiscal document and cannot be cancelled (delete it instead) |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /invoices/{id}/email` — Send invoice by email

Send an invoice access link to a specified email address with custom subject and message. The recipient must be authorized in the client's contact list.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `to` | string (email) | yes | Recipient email address Example: `"client@example.ro"` |
| `subject` | string | yes | Email subject line Example: `"Factura FACT125 - SC Example SRL"` (min length 1, max length 200) |
| `body` | string | yes | Email message body Example: `"Vă transmitem factura în anexă. Mulțumim!"` (min length 1, max length 2000) |
| `language` | string | no | Email language Enum: `"ro"`, `"en"` Default: `"ro"` Example: `"ro"` |
| `addToContacts` | boolean | no | Add recipient email to client contact list if not present Default: `false` Example: `false` |

Example request:

```json
{
  "to": "client@example.ro",
  "subject": "Factura FACT125 - SC Example SRL",
  "body": "Vă transmitem factura în anexă. Mulțumim!",
  "language": "ro",
  "addToContacts": false
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /invoices/{id}/finalize` — Convert a proforma invoice to a fiscal invoice

Convert a proforma invoice (FACTURĂ PROFORMĂ) into a binding fiscal invoice on a separate fiscal series.

The proforma is NOT deleted — it is marked with the resulting fiscal invoice ID. The fiscal invoice will include a note referencing the proforma serial number.

**Serial Number Options** (mutually exclusive, one required):
- `seriesId`: Auto-generates next number from a fiscal invoice series
- `customSerialNumber`: User-defined fiscal invoice number

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Proforma invoice ID (MongoDB ObjectId) (pattern `^[0-9a-fA-F]{24}$`) |

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `seriesId` | string | no | Fiscal invoice series ID. Mutually exclusive with customSerialNumber. Example: `"60f7b1b9c9e7b4a1e8d1c2b5"` (pattern `^[0-9a-fA-F]{24}$`) |
| `customSerialNumber` | string | no | Custom fiscal invoice number. Mutually exclusive with seriesId. Example: `"FACT-2025-001"` (min length 1, max length 50, pattern `^[A-Za-z0-9-_]+$`) |

Example request:

```json
{
  "seriesId": "60f7b1b9c9e7b4a1e8d1c2b5",
  "customSerialNumber": "FACT-2025-001"
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "serialNumber": "FACT-00123",
    "isDraft": false,
    "originProformaId": "60f7b1b9c9e7b4a1e8d1c2b9",
    "originProformaSerialNumber": "PROF-0001"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | — | Validation error (not a proforma, missing series config) |
| 409 | — | Proforma already converted |

#### `GET /invoices/{id}/paymentstatus` — Get invoice payment status

Retrieve detailed payment information for an invoice including amounts paid, remaining balance, and payment history.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /invoices/{id}/pdf` — Get invoice PDF download URL

Get a presigned download URL for the invoice PDF.

The response contains a presigned S3 URL that can be used directly to download the PDF file.

The URL is valid for 10 minutes (600 seconds).

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "downloadUrl": "https://s3.eu-central-1.amazonaws.com/bucket/vizualizare/invoice.pdf?X-Amz-...",
    "filename": "factura_FACT-00123.pdf",
    "expiresIn": 600
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /invoices/{id}/saga` — Export one issued invoice for Saga

Issued invoices in the **Saga C** import format (Saga → Diverse → Import date). The company is the supplier (<FurnizorCIF>), so Saga files them under **Ieșiri**. Storno invoices are included (negative quantities); proformas, drafts and cancelled invoices are not.

Dates are taken on the Romanian (Europe/Bucharest) calendar. Amounts are in the invoice currency; for foreign-currency invoices the BNR rate is stated in FacturaInformatiiSuplimentare. See also the app's "Export Saga" button, which produces the same file.

The file holds this one invoice and is named F_<CIF>_<invoice number>_<invoice date>.xml, as Saga's manual names single invoices.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `download` | boolean | no | true: respond with the XML file (Content-Disposition attachment) instead of JSON Default: `false` |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "fileName": "F_44540371_IESIRI-2026-09-01-2026-09-30_04.10.2026.xml",
    "contentType": "application/xml",
    "content": "string",
    "exported": 0,
    "skipped": [
      {
        "id": "string",
        "number": "string",
        "reason": "string"
      }
    ],
    "truncated": true
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 422 | — | The invoice cannot be exported to Saga (proforma, cancelled, inconsistent) or the organization has no fiscal code |
| 500 | `INTERNAL_ERROR` | An internal error occurred |
| 504 | — | The export took too long |

#### `POST /invoices/{id}/storno` — Issue a storno (reversal) of an invoice

Creates a storno: a fiscal reversal that is the exact negative of the original invoice and references it. The server computes the negation — send only the original invoice id plus optional issueDate / seriesId / customSerialNumber / reason. Create-only: submit the storno to e-Factura separately.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `issueDate` | string (date) | no | Reversal date (YYYY-MM-DD). Defaults to today. |
| `seriesId` | string | no | Series for the storno. Defaults to the original invoice's series. Mutually exclusive with customSerialNumber. (pattern `^[0-9a-fA-F]{24}$`) |
| `customSerialNumber` | string | no | Explicit serial number for the storno. Mutually exclusive with seriesId. (min length 1, max length 50) |
| `reason` | string | no | Optional free-text reason, recorded on the storno. (max length 500) |

Example request:

```json
{
  "issueDate": "2026-03-01",
  "seriesId": "string",
  "customSerialNumber": "string",
  "reason": "string"
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c9",
    "serialNumber": "FACT-00126",
    "originalInvoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "isDraft": false
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 409 | — | The invoice has already been reversed |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /invoices/{id}/xml` — Get issued invoice e-Factura XML download URL

Get a presigned download URL for the e-Factura UBL XML of an issued invoice — the same XML that is submitted to ANAF.

The response contains a presigned S3 URL that can be used directly to download the XML file. The URL is valid for 10 minutes (600 seconds).

The XML is available as soon as the invoice exists — no e-Factura submission is required. If it has not been generated yet it is generated on demand and cached, so the first call may take slightly longer.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "downloadUrl": "https://s3.eu-central-1.amazonaws.com/bucket/efactura/invoice.xml?X-Amz-...",
    "invoiceNumber": "FACT-00123",
    "filename": "efactura_FACT-00123.xml",
    "expiresIn": 600
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

### Clients

Client and customer management with Romanian business validation including CUI/CNP verification and address management.

| Method | Path | Description |
|---|---|---|
| GET | `/clients` | List clients with search |
| POST | `/clients` | Create a new client |
| GET | `/clients/{id}` | Get client by ID |
| PUT | `/clients/{id}` | Update client information |
| DELETE | `/clients/{id}` | Delete a client |

#### `GET /clients` — List clients with search

Retrieve a paginated list of clients with optional search by name, email, or registration number.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | no | Page number for pagination Default: `1` Example: `1` (min 1) |
| `limit` | integer | no | Number of items per page Default: `20` Example: `20` (min 1, max 100) |
| `search` | string | no | Search term for client name, email, or registration number (max length 200) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /clients` — Create a new client

Add a new business client to your organization with contact and address information.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | yes | Client business name (min length 1, max length 200) |
| `taxId` | string | yes | Tax identification number (Romanian CUI/CNP, US EIN, or EU VAT ID) (min length 1, max length 50) |
| `tradeRegistryNumber` | string | no | Trade registry number (e.g., J40/1234/2020) (max length 50) |
| `address` | object | yes | Client address information |
| `address.street` | string | no | Street address (max length 200) |
| `address.city` | string | yes | City (min length 1, max length 100) |
| `address.county` | string | yes | Romanian county (județ): its name, any case, with or without diacritics ("Iași", "IASI"), or its ISO 3166-2 code ("IS", "RO-IS") — not a city or village. Published invoices for a Romanian client whose county is not recognised are refused with 400 EFACTURA_INVALID_COUNTY. Free text for non-Romanian addresses. (min length 1, max length 100) |
| `address.postalCode` | string | no | Postal code (max length 20) |
| `address.sector` | string | no | București sector, e.g. "Sectorul 3" or "3" (1-6). Required for București addresses (ANAF e-Factura rule BR-RO-100). (max length 10) |
| `address.country` | string | yes | Country Default: `"România"` (min length 1, max length 100) |
| `IBAN` | string | no | Bank account IBAN (max length 50) |
| `contactEmails` | string (email)[] | no | Contact email addresses |
| `contact` | string | no | Contact person name (max length 200) |
| `phone` | string | no | Contact phone number (max length 50) |
| `bank` | string | no | Bank name (max length 200) |
| `swift` | string | no | SWIFT/BIC code (ISO 9362, 8 or 11 chars). Optional; used for international payments and shown on the invoice PDF when present. (max length 11) |
| `hasSelfBillingContract` | boolean | no | Indicates whether this client has a contract that allows self-billing (Autofacturare) |

Example request:

```json
{
  "name": "SC Example SRL",
  "taxId": "12345678",
  "tradeRegistryNumber": "J40/1234/2020",
  "address": {
    "street": "Strada Exemplu nr. 123",
    "city": "București",
    "county": "București",
    "postalCode": "010101",
    "sector": "Sectorul 1",
    "country": "România"
  },
  "IBAN": "RO49AAAA1B31007593840000",
  "swift": "BTRLRO22",
  "contactEmails": [
    "contact@example.ro"
  ],
  "phone": "+40123456789"
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /clients/{id}` — Get client by ID

Retrieve a single client's information by their ID.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `PUT /clients/{id}` — Update client information

Update an existing client's information. All fields are optional.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | no | Client business name (min length 1, max length 200) |
| `taxId` | string | no | Tax identification number (CUI/CNP) (max length 50) |
| `tradeRegistryNumber` | string | no | Trade registry number (max length 50) |
| `address` | object | no | Address information |
| `address.street` | string | no | Street name and number (max length 200) |
| `address.city` | string | no | City (max length 100) |
| `address.county` | string | no | Romanian county (județ): its name, any case, with or without diacritics ("Iași", "IASI"), or its ISO 3166-2 code ("IS", "RO-IS") — not a city or village. Published invoices for a Romanian client whose county is not recognised are refused with 400 EFACTURA_INVALID_COUNTY. Free text for non-Romanian addresses. (max length 100) |
| `address.postalCode` | string | no | Postal code (max length 20) |
| `address.sector` | string | no | București sector, e.g. "Sectorul 3" or "3" (1-6). Required for București addresses (ANAF e-Factura rule BR-RO-100). (max length 10) |
| `address.country` | string | no | Country (max length 100) |
| `IBAN` | string | no | Bank account IBAN (max length 50) |
| `contactEmails` | string (email)[] | no | Contact email addresses |
| `contact` | string | no | Contact person name (max length 200) |
| `phone` | string | no | Contact phone number (max length 50) |
| `bank` | string | no | Bank name (max length 200) |
| `swift` | string | no | SWIFT/BIC code (ISO 9362, 8 or 11 chars). Optional; used for international payments and shown on the invoice PDF when present. (max length 11) |
| `hasSelfBillingContract` | boolean | no | Indicates whether this client has a contract that allows self-billing (Autofacturare) |

Example request:

```json
{
  "name": "string",
  "taxId": "string",
  "tradeRegistryNumber": "string",
  "address": {
    "street": "string",
    "city": "string",
    "county": "string",
    "postalCode": "string",
    "sector": "string",
    "country": "string"
  },
  "IBAN": "string",
  "contactEmails": [
    "string"
  ],
  "contact": "string",
  "phone": "string",
  "bank": "string",
  "swift": "string",
  "hasSelfBillingContract": true
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `DELETE /clients/{id}` — Delete a client

Delete a client. Clients with existing invoices cannot be deleted - delete or cancel all invoices first.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "deleted": true,
    "clientId": "60f7b1b9c9e7b4a1e8d1c2b4"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `CLIENT_HAS_INVOICES` | Cannot delete a client with existing invoices. Delete or cancel all invoices first. |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

### Payments

Payment tracking and management including partial payments, payment history, and status monitoring.

| Method | Path | Description |
|---|---|---|
| GET | `/invoices/{id}/payments` | List payments with filtering |
| POST | `/invoices/{id}/payments` | Record a new payment |
| DELETE | `/invoices/{id}/payments/{paymentId}` | Delete a payment |
| GET | `/payments` | List payments with filtering |
| DELETE | `/payments/{id}` | Delete a payment |

#### `GET /invoices/{id}/payments` — List payments with filtering

Retrieve a paginated list of payments with optional filtering by date range and invoice.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes |  |

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | no | Page number for pagination Default: `1` Example: `1` (min 1) |
| `limit` | integer | no | Number of items per page Default: `20` Example: `20` (min 1, max 100) |
| `startDate` | string (date) | no |  |
| `endDate` | string (date) | no |  |
| `invoiceId` | string | no | Filter payments for specific invoice Example: `"60f7b1b9c9e7b4a1e8d1c2b3"` (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /invoices/{id}/payments` — Record a new payment

Record a payment for an invoice. The payment amount will be added to the invoice's total paid amount.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes |  |

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `amount` | number | yes | Payment amount Example: `500` (min 0.01) |
| `paymentDate` | string (date-time) | yes | Date when payment was made (accepts both date and datetime formats) Example: `"2024-01-20T10:30:00.000Z"` |
| `paymentMethod` | string | no | Method of payment Enum: `"cash"`, `"bank_transfer"`, `"card"`, `"check"`, `"other"` Example: `"bank_transfer"` |
| `currency` | string | no | Payment currency (defaults to RON) Default: `"RON"` Example: `"RON"` |
| `exchangeRate` | number | no | Exchange rate to RON (required for non-RON currencies) Example: `4.97` (min 0) |
| `reference` | string | no | Payment reference (e.g. transaction ID, check number) Example: `"TXN123456"` (max length 200) |
| `notes` | string | no | Additional payment notes Example: `"Transfer bancar - ref: TXN123456"` (max length 500) |

Example request:

```json
{
  "amount": 500,
  "paymentDate": "2024-01-20",
  "paymentMethod": "bank_transfer",
  "currency": "EUR",
  "exchangeRate": 4.97,
  "reference": "TXN123456",
  "notes": "Transfer bancar - ref: TXN123456"
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "amount": 500,
    "paymentMethod": "bank_transfer",
    "paymentDate": "2024-01-20T10:30:00.000Z",
    "paymentStatus": "paid"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `DELETE /invoices/{id}/payments/{paymentId}` — Delete a payment

Delete a payment by its ID. The system will find the invoice containing this payment and recalculate the invoice status after the payment is removed.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Payment ID to delete (or invoice ID for the nested /invoices/:id/payments/:paymentId route) Example: `"68dcd51b9746176fdc513710"` |
| `paymentId` | string | yes | Payment ID to delete (nested /invoices/:id/payments/:paymentId route) Example: `"68dcd51b9746176fdc513710"` |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /payments` — List payments with filtering

Retrieve a paginated list of payments with optional filtering by date range and invoice.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | no | Page number for pagination Default: `1` Example: `1` (min 1) |
| `limit` | integer | no | Number of items per page Default: `20` Example: `20` (min 1, max 100) |
| `startDate` | string (date) | no |  |
| `endDate` | string (date) | no |  |
| `invoiceId` | string | no | Filter payments for specific invoice Example: `"60f7b1b9c9e7b4a1e8d1c2b3"` (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `DELETE /payments/{id}` — Delete a payment

Delete a payment by its ID. The system will find the invoice containing this payment and recalculate the invoice status after the payment is removed.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Payment ID to delete (or invoice ID for the nested /invoices/:id/payments/:paymentId route) Example: `"68dcd51b9746176fdc513710"` |
| `paymentId` | string | yes | Payment ID to delete (nested /invoices/:id/payments/:paymentId route) Example: `"68dcd51b9746176fdc513710"` |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

### Series

Invoice series configuration and numbering management for Romanian invoice requirements.

| Method | Path | Description |
|---|---|---|
| GET | `/series` | Get series configuration |
| POST | `/series` | Create new series |
| GET | `/series/{id}` | Get series by ID |
| DELETE | `/series/{id}` | Delete series |

#### `GET /series` — Get series configuration

Retrieve the invoice series configuration for the organization

**Response** (`200`)

```json
{
  "success": true,
  "data": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "prefix": "FACT",
      "suffix": "",
      "currentNumber": 125,
      "year": 2024,
      "type": "invoice"
    },
    {
      "_id": "507f1f77bcf86cd799439012",
      "prefix": "CHIT",
      "suffix": "",
      "currentNumber": 45,
      "year": 2024,
      "type": "receipt"
    }
  ]
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /series` — Create new series

Create a new invoice/receipt series configuration

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `prefix` | string | yes | Series prefix (e.g., 'FACT', 'INV') Example: `"FACT"` (min length 1, max length 20) |
| `suffix` | string | no | Optional series suffix Example: `""` (max length 20) |
| `year` | number | yes | Year for the series Example: `2025` (min 2020, max 2099) |
| `type` | string | yes | Type of document series Enum: `"invoice"`, `"receipt"`, `"proforma"` Example: `"invoice"` |
| `startNumber` | number | no | Starting number for the series (default: 0) Example: `0` (min 0) |

Example request:

```json
{
  "prefix": "FACT",
  "suffix": "",
  "year": 2025,
  "type": "invoice",
  "startNumber": 0
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {
    "_id": "507f1f77bcf86cd799439011",
    "prefix": "FACT",
    "suffix": "",
    "currentNumber": 125,
    "year": 2024,
    "type": "invoice"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /series/{id}` — Get series by ID

Retrieve a specific invoice series configuration by its ID

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Series ID to retrieve Example: `"507f1f77bcf86cd799439011"` |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "_id": "507f1f77bcf86cd799439011",
    "prefix": "FACT",
    "suffix": "",
    "currentNumber": 125,
    "year": 2024,
    "type": "invoice"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `DELETE /series/{id}` — Delete series

Delete an invoice/receipt series. Series can only be deleted if no invoices are using it.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Series ID to delete Example: `"507f1f77bcf86cd799439011"` |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "message": "Series successfully deleted"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

### Webhooks

Webhook endpoint management and delivery tracking.

| Method | Path | Description |
|---|---|---|
| POST | `/webhooks/deliveries/{id}/retry` | Retry webhook delivery |
| GET | `/webhooks/endpoints` | List webhook endpoints |
| POST | `/webhooks/endpoints` | Create a webhook endpoint |
| GET | `/webhooks/endpoints/{id}` | Get webhook endpoint |
| PUT | `/webhooks/endpoints/{id}` | Update webhook endpoint |
| DELETE | `/webhooks/endpoints/{id}` | Delete webhook endpoint |
| GET | `/webhooks/endpoints/{id}/deliveries` | List webhook deliveries |
| GET | `/webhooks/endpoints/{id}/secret` | Reveal webhook endpoint signing secret |
| POST | `/webhooks/endpoints/{id}/test` | Test webhook endpoint |
| GET | `/webhooks/event-types` | List available event types |

#### `POST /webhooks/deliveries/{id}/retry` — Retry webhook delivery

Retry a failed webhook delivery. The delivery will be re-queued for immediate delivery.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b4",
    "endpoint_id": "string",
    "event_type": "invoice.issued",
    "status": "success",
    "status_code": 200,
    "request_body": {},
    "response_body": "string",
    "response_time_ms": 250,
    "attempt_count": 1,
    "next_retry_at": "2026-03-01T10:00:00.000Z",
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-15T10:00:00Z"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /webhooks/endpoints` — List webhook endpoints

Retrieve a paginated list of webhook endpoints for your organization.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | integer | no | Maximum number of items to return (1-100) Default: `10` Example: `25` (min 1, max 100) |
| `starting_after` | string | no | Resource ID to paginate after (returns items created after this ID) Example: `"60f7b1b9c9e7b4a1e8d1c2b3"` (pattern `^[0-9a-fA-F]{24}$`) |
| `ending_before` | string | no | Resource ID to paginate before (returns items created before this ID) Example: `"60f7b1b9c9e7b4a1e8d1c2b3"` (pattern `^[0-9a-fA-F]{24}$`) |
| `is_active` | boolean | no | Filter by active/inactive status |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "data": [
      {
        "id": "60f7b1b9c9e7b4a1e8d1c2b3",
        "url": "https://example.com/webhooks/billyou",
        "description": "Production webhook endpoint",
        "events": [
          "invoice.issued",
          "invoice.paid"
        ],
        "is_active": true,
        "created_at": "2026-01-15T10:00:00Z",
        "updated_at": "2026-01-15T10:00:00Z"
      }
    ],
    "has_more": true,
    "total_count": 42
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /webhooks/endpoints` — Create a webhook endpoint

Create a new webhook endpoint to receive event notifications. The signing secret is returned only once on creation — store it securely.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string (uri) | yes | The URL that will receive webhook event POST requests. Must be HTTPS. Example: `"https://example.com/webhooks/billyou"` |
| `description` | string | no | An optional description for the endpoint Example: `"Production webhook endpoint"` (max length 500) |
| `events` | string[] | yes | List of event types this endpoint should subscribe to (min items 1) |

Example request:

```json
{
  "url": "https://example.com/webhooks/billyou",
  "description": "Production webhook endpoint",
  "events": [
    "invoice.issued",
    "invoice.paid",
    "customer.created"
  ]
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "url": "https://example.com/webhooks/billyou",
    "description": "Production webhook endpoint",
    "events": [
      "invoice.issued",
      "invoice.paid"
    ],
    "is_active": true,
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-15T10:00:00Z",
    "secret": "whsec_a1b2c3d4e5f6..."
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /webhooks/endpoints/{id}` — Get webhook endpoint

Retrieve a single webhook endpoint by its ID.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "url": "https://example.com/webhooks/billyou",
    "description": "Production webhook endpoint",
    "events": [
      "invoice.issued",
      "invoice.paid"
    ],
    "is_active": true,
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-15T10:00:00Z"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `PUT /webhooks/endpoints/{id}` — Update webhook endpoint

Update an existing webhook endpoint. All fields are optional — only provided fields will be updated.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string (uri) | no | The URL that will receive webhook event POST requests Example: `"https://example.com/webhooks/billyou"` |
| `description` | string | no | An optional description for the endpoint Example: `"Updated production webhook endpoint"` (max length 500) |
| `events` | string[] | no | List of event types this endpoint should subscribe to (min items 1) |
| `is_active` | boolean | no | Whether the endpoint is active and will receive events Example: `true` |

Example request:

```json
{
  "url": "https://example.com/webhooks/billyou",
  "description": "Updated production webhook endpoint",
  "events": [
    "invoice.issued",
    "invoice.paid"
  ],
  "is_active": true
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2b3",
    "url": "https://example.com/webhooks/billyou",
    "description": "Production webhook endpoint",
    "events": [
      "invoice.issued",
      "invoice.paid"
    ],
    "is_active": true,
    "created_at": "2026-01-15T10:00:00Z",
    "updated_at": "2026-01-15T10:00:00Z"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `DELETE /webhooks/endpoints/{id}` — Delete webhook endpoint

Delete a webhook endpoint. This will stop all event deliveries to this endpoint.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "string",
    "deleted": true
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /webhooks/endpoints/{id}/deliveries` — List webhook deliveries

Retrieve a paginated list of webhook deliveries for a specific endpoint.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | integer | no | Maximum number of items to return (1-100) Default: `10` Example: `25` (min 1, max 100) |
| `starting_after` | string | no | Resource ID to paginate after (returns items created after this ID) Example: `"60f7b1b9c9e7b4a1e8d1c2b3"` (pattern `^[0-9a-fA-F]{24}$`) |
| `ending_before` | string | no | Resource ID to paginate before (returns items created before this ID) Example: `"60f7b1b9c9e7b4a1e8d1c2b3"` (pattern `^[0-9a-fA-F]{24}$`) |
| `status` | string | no | Filter deliveries by status Enum: `"pending"`, `"success"`, `"failed"` |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "data": [
      {
        "id": "60f7b1b9c9e7b4a1e8d1c2b4",
        "endpoint_id": "string",
        "event_type": "invoice.issued",
        "status": "success",
        "status_code": 200,
        "request_body": {},
        "response_body": "string",
        "response_time_ms": 250,
        "attempt_count": 1,
        "next_retry_at": "2026-03-01T10:00:00.000Z",
        "created_at": "2026-01-15T10:00:00Z",
        "updated_at": "2026-01-15T10:00:00Z"
      }
    ],
    "has_more": true,
    "total_count": 42
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /webhooks/endpoints/{id}/secret` — Reveal webhook endpoint signing secret

Retrieve the signing secret for a webhook endpoint. Use this to verify webhook signatures.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "string",
    "secret": "string",
    "created_at": "string"
  }
}
```

#### `POST /webhooks/endpoints/{id}/test` — Test webhook endpoint

Send a test event to a webhook endpoint to verify connectivity. The test delivery is recorded in the delivery log.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | (pattern `^[0-9a-fA-F]{24}$`) |

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `event_type` | string | no | The event type to simulate for the test delivery Enum: `"invoice.issued"`, `"invoice.paid"`, `"invoice.canceled"`, `"invoice.storno.issued"`, `"invoice.efactura_sent"`, `"invoice.efactura_accepted"`, `"invoice.efactura_rejected"`, `"invoice.efactura_received"`, `"customer.created"`, `"customer.updated"`, `"customer.deleted"`, `"expense.created_from_efactura"`, `"etransport.declaration.processed"`, `"etransport.declaration.rejected"`, `"account.provisioned"`, `"account.activated"`, `"account.subscribed"` Default: `"invoice.issued"` Example: `"invoice.issued"` |

Example request:

```json
{
  "event_type": "invoice.issued"
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "success": true,
    "status_code": 200,
    "response_time_ms": 250,
    "response_body": "string"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /webhooks/event-types` — List available event types

Retrieve a list of all available webhook event types with descriptions and categories.

**Response** (`200`)

```json
{
  "success": true,
  "data": [
    {
      "type": "invoice.issued",
      "description": "string",
      "category": "Invoices"
    }
  ]
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

### E-Factura

Romanian government e-Factura integration.

| Method | Path | Description |
|---|---|---|
| GET | `/efactura/received` | List received E-Factura invoices |
| GET | `/efactura/received/{id}` | Get received E-Factura invoice |
| GET | `/efactura/received/{id}/xml` | Download received E-Factura XML |
| GET | `/efactura/submissions/{id}` | Get E-Factura submission status |
| POST | `/efactura/submissions/{id}/retry` | Retry a failed E-Factura submission |
| GET | `/efactura/submissions/{id}/xml` | Download issued E-Factura XML |
| POST | `/invoices/{id}/efactura/submissions` | Submit invoice to ANAF E-Factura system |

#### `GET /efactura/received` — List received E-Factura invoices

Retrieve a paginated list of invoices received via the E-Factura system (SPV inbox).

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | no | Page number for pagination Default: `1` Example: `1` (min 1) |
| `limit` | integer | no | Number of items per page Default: `20` Example: `20` (min 1, max 100) |
| `status` | string | no | Filter by processing status Enum: `"pending"`, `"saved"`, `"failed"` |

**Response** (`200`)

```json
{
  "success": true,
  "data": [
    {
      "uploadIndex": "string",
      "downloadId": "string",
      "invoiceNumber": "string",
      "vendorCIF": "string",
      "issueDate": "string",
      "paymentDueDate": "string",
      "valueWithoutVAT": 0,
      "VATValue": 0,
      "totalValue": 0,
      "currency": "string",
      "status": "pending"
    }
  ],
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /efactura/received/{id}` — Get received E-Factura invoice

Retrieve a specific received E-Factura invoice by its download ID.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Download ID of the received invoice |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "uploadIndex": "string",
    "downloadId": "string",
    "invoiceNumber": "string",
    "vendorCIF": "string",
    "issueDate": "string",
    "paymentDueDate": "string",
    "valueWithoutVAT": 0,
    "VATValue": 0,
    "totalValue": 0,
    "currency": "string",
    "status": "pending",
    "stats": {
      "queuedAt": "string",
      "processStartedAt": "string",
      "processedAt": "string"
    }
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /efactura/received/{id}/xml` — Download received E-Factura XML

Get a presigned download URL for the raw XML of a received E-Factura invoice.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Download ID of the received invoice |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "downloadUrl": "string",
    "invoiceNumber": "string",
    "filename": "string"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /efactura/submissions/{id}` — Get E-Factura submission status

Get status by Invoice ID (acting as Submission ID currently)

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Submission ID (currently maps to Invoice ID) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "string",
    "invoiceId": "string",
    "uploadIndex": "string",
    "downloadId": "string",
    "status": "pending",
    "createdAt": "string",
    "updatedAt": "string",
    "error": {
      "code": "string",
      "message": "string",
      "details": {
        "errorCode": "string",
        "anafErrors": [
          {
            "code": "string",
            "message": "string"
          }
        ],
        "translatedErrors": [
          {}
        ]
      }
    }
  }
}
```

#### `POST /efactura/submissions/{id}/retry` — Retry a failed E-Factura submission

Retry a previously failed E-Factura submission. Only submissions with retryable statuses (`upload-failed`, `nok-retryable`, `failed`) can be retried.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Submission ID (currently maps to Invoice ID) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /efactura/submissions/{id}/xml` — Download issued E-Factura XML

Get a presigned download URL for the e-Factura UBL XML of an issued invoice (submission) — the same XML that is submitted to ANAF. This is the issued-invoice counterpart of `GET /efactura/received/{id}/xml`.

The submission ID is the invoice ID. The XML is available as soon as the invoice exists — no e-Factura submission is required; it is generated on demand and cached on first request.

The presigned URL is valid for 10 minutes (600 seconds).

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Submission ID (currently equals the Invoice ID) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "downloadUrl": "https://s3.eu-central-1.amazonaws.com/bucket/efactura/invoice.xml?X-Amz-...",
    "invoiceNumber": "FACT-00123",
    "filename": "efactura_FACT-00123.xml",
    "expiresIn": 600
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /invoices/{id}/efactura/submissions` — Submit invoice to ANAF E-Factura system

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes |  |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "string",
    "invoiceId": "string",
    "uploadIndex": "string",
    "downloadId": "string",
    "status": "pending",
    "createdAt": "string",
    "updatedAt": "string",
    "error": {
      "code": "string",
      "message": "string",
      "details": {
        "errorCode": "string",
        "anafErrors": [
          {
            "code": "string",
            "message": "string"
          }
        ],
        "translatedErrors": [
          {}
        ]
      }
    },
    "simulation": true,
    "validationErrors": [
      {
        "code": "string",
        "message": "string",
        "severity": "string"
      }
    ]
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

### E-Transport

E-Transport declaration management. Submit transport declarations to ANAF, track their status, and receive webhook notifications when ANAF assigns a UIT code.

| Method | Path | Description |
|---|---|---|
| GET | `/etransport/declarations` | List transport declarations |
| POST | `/etransport/declarations` | Submit transport declaration |
| POST | `/etransport/declarations/validate` | Validate transport declaration |
| GET | `/etransport/declarations/{id}` | Get transport declaration |

#### `GET /etransport/declarations` — List transport declarations

Return all e-Transport declarations for the authenticated organization.

**Response** (`200`)

```json
{
  "success": true,
  "data": [
    {
      "id": "string",
      "declarationType": "NOTIFICATION",
      "status": "pending",
      "uploadIndex": "string",
      "uitCode": "string",
      "createdAt": "2026-03-01T10:00:00.000Z",
      "updatedAt": "2026-03-01T10:00:00.000Z"
    }
  ]
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /etransport/declarations` — Submit transport declaration

Submit a new e-Transport declaration to ANAF. Performs pre-flight validation before the real submission. Returns immediately with declarationId; poll GET /:id or await webhook for final UIT code.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `declarationType` | string | yes | Type of transport declaration Enum: `"NOTIFICATION"`, `"CONFIRMATION"`, `"DELETION"` |
| `declarationData` | object \\| object | yes | Full declaration input per @billyou/etransport spec |

Example request:

```json
{
  "declarationType": "NOTIFICATION",
  "declarationData": {}
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /etransport/declarations/validate` — Validate transport declaration

Validate a declaration against ANAF business rules without creating a record. Uses ANAF testMode=1. Use this before submitting to catch errors early.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `declarationType` | string | yes | Type of transport declaration Enum: `"NOTIFICATION"`, `"CONFIRMATION"`, `"DELETION"` |
| `declarationData` | object \\| object | yes | Full declaration input per @billyou/etransport spec |

Example request:

```json
{
  "declarationType": "NOTIFICATION",
  "declarationData": {}
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "valid": true,
    "errors": [
      {
        "code": "string",
        "field": "string",
        "message": "string"
      }
    ]
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /etransport/declarations/{id}` — Get transport declaration

Get a single e-Transport declaration by ID. Returns current status and UIT code once ANAF has processed the declaration.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Declaration ID |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "string",
    "declarationType": "NOTIFICATION",
    "status": "pending",
    "uploadIndex": "string",
    "uitCode": "string",
    "createdAt": "2026-03-01T10:00:00.000Z",
    "updatedAt": "2026-03-01T10:00:00.000Z"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

### OAuth

| Method | Path | Description |
|---|---|---|
| GET | `/oauth/clients` | List your OAuth clients |
| POST | `/oauth/clients` | Create an OAuth client |
| DELETE | `/oauth/clients/{clientId}` | Delete an OAuth client (revokes its live tokens) |
| POST | `/oauth/clients/{clientId}/rotate` | Rotate an OAuth client secret |
| GET | `/oauth/clients/{clientId}/usage` | Usage analytics for an OAuth client |
| POST | `/oauth/token` | OAuth 2.0 token endpoint (client credentials grant) |

#### `GET /oauth/clients` — List your OAuth clients

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | no | Default: `1` (min 1) |
| `limit` | integer | no | Default: `20` (min 1, max 100) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "clients": [
      {
        "id": "string",
        "client_id": "bk_id_a1b2c3d4e5f6a1b2c3d4e5f6",
        "name": "Acme Integration",
        "is_active": true,
        "last_used_at": "2026-03-01T10:00:00.000Z",
        "created_at": "2026-03-01T10:00:00.000Z",
        "updated_at": "2026-03-01T10:00:00.000Z"
      }
    ],
    "pagination": {}
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /oauth/clients` — Create an OAuth client

Creates a client_id + client_secret scoped to your organization. The client_secret is returned exactly once.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | yes | (min length 1, max length 256) |

Example request:

```json
{
  "name": "string"
}
```

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `DELETE /oauth/clients/{clientId}` — Delete an OAuth client (revokes its live tokens)

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `clientId` | string | yes | Public client_id (bk_id_…) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {},
  "meta": {
    "total": 0,
    "page": 0,
    "limit": 0
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /oauth/clients/{clientId}/rotate` — Rotate an OAuth client secret

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `clientId` | string | yes | Public client_id (bk_id_…) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "id": "string",
    "client_id": "bk_id_a1b2c3d4e5f6a1b2c3d4e5f6",
    "name": "Acme Integration",
    "is_active": true,
    "last_used_at": "2026-03-01T10:00:00.000Z",
    "created_at": "2026-03-01T10:00:00.000Z",
    "updated_at": "2026-03-01T10:00:00.000Z",
    "client_secret": "bk_cs_…"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /oauth/clients/{clientId}/usage` — Usage analytics for an OAuth client

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `clientId` | string | yes | Public client_id (bk_id_…) |

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `startDate` | string (date-time) | no |  |
| `endDate` | string (date-time) | no |  |

**Response** (`200`)

```json
{
  "success": true,
  "data": {}
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /oauth/token` — OAuth 2.0 token endpoint (client credentials grant)

Exchanges a client_id + client_secret for a short-lived Bearer access token. Accepts application/x-www-form-urlencoded or application/json. Public endpoint.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `grant_type` | string | no |  |
| `client_id` | string | no |  |
| `client_secret` | string | no |  |

Example request:

```json
{
  "grant_type": "string",
  "client_id": "string",
  "client_secret": "string"
}
```

**Response** (`200`)

```json
{
  "access_token": "bk_at_…",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | — | Invalid request (RFC 6749 error) |
| 401 | — | Client authentication failed (RFC 6749 error) |

### Partner

| Method | Path | Description |
|---|---|---|
| GET | `/partner/accounts` | List provisioned accounts |
| POST | `/partner/accounts` | Provision an end-customer account |
| GET | `/partner/accounts/{id}` | Get a provisioned account |
| POST | `/partner/efactura/auth-sessions` | Start a white-label ANAF e-Factura authorization session |
| GET | `/plans` | List plans available to your partner organization |

#### `GET /partner/accounts` — List provisioned accounts

Retrieve a paginated list of the end-customer accounts your partner organization has provisioned.

**Query parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | no | Page number for pagination Default: `1` Example: `1` (min 1) |
| `limit` | integer | no | Number of items per page Default: `20` Example: `20` (min 1, max 100) |

**Response** (`200`)

```json
{
  "success": true,
  "data": [
    {
      "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
      "name": "string",
      "cui": "string",
      "cnp": "string",
      "firstName": "string",
      "lastName": "string",
      "accountType": "company",
      "provisionedByPartnerOrgId": "string",
      "createdVia": "string",
      "createdAt": "2026-03-01T10:00:00.000Z"
    }
  ],
  "meta": {
    "total": 42,
    "page": 1,
    "limit": 20
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /partner/accounts` — Provision an end-customer account

Provision a new trial end-customer account on behalf of your partner organization. Provide either a CUI (for companies) or a CNP (for individuals), but not both. Returns the new organization ID and a production API key scoped to that account.

Example request:

```json
{
  "email": "owner@example.com",
  "firstName": "Ion",
  "lastName": "Popescu",
  "cui": "RO12345678",
  "companyName": "Example SRL",
  "address": {
    "city": "Bucuresti",
    "county": "Bucuresti",
    "completeAddress": "Strada Exemplu 10, Bucuresti"
  },
  "locale": "ro"
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {
    "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
    "apiKey": "bk_user_live_a1b2c3...",
    "activationStatus": "invite_sent"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 409 | `ORG_EXISTS` | An organization with this tax ID already exists. |
| 429 | `RATE_LIMIT_EXCEEDED` | You have exceeded the allowed request limit |
| 500 | `INTERNAL_ERROR` | An internal error occurred |
| 503 | `PROVISIONING_TIMEOUT` | The provisioning request timed out but may still have succeeded. It is safe to retry — accounts are de-duplicated by tax ID. |

#### `GET /partner/accounts/{id}` — Get a provisioned account

Retrieve a single end-customer account your partner organization provisioned, by its organization ID.

**Path parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | The provisioned organization ID. (pattern `^[0-9a-fA-F]{24}$`) |

**Response** (`200`)

```json
{
  "success": true,
  "data": {
    "organizationId": "60f7b1b9c9e7b4a1e8d1c2b3",
    "name": "string",
    "cui": "string",
    "cnp": "string",
    "firstName": "string",
    "lastName": "string",
    "accountType": "company",
    "provisionedByPartnerOrgId": "string",
    "createdVia": "string",
    "createdAt": "2026-03-01T10:00:00.000Z"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `POST /partner/efactura/auth-sessions` — Start a white-label ANAF e-Factura authorization session

Returns a one-time authorizeUrl to redirect the end-user's browser to. The end-user authorizes on ANAF and is returned to your registered returnUri with a status. Requires the target organization to be one you provisioned, and returnUri to be in your connect.anafReturnUris allow-list.

**Request body** (`application/json`)

| Field | Type | Required | Description |
|---|---|---|---|
| `organizationId` | string | yes | A child organization you provisioned. (pattern `^[0-9a-fA-F]{24}$`) |
| `returnUri` | string (uri) | yes | Partner-owned https URL to return to (must exactly match a connect.anafReturnUris entry). |

Example request:

```json
{
  "organizationId": "string",
  "returnUri": "string"
}
```

**Response** (`201`)

```json
{
  "success": true,
  "data": {
    "authorizeUrl": "https://api.billyou.ro/api/partner/efactura/authorize?session=…"
  }
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 400 | `VALIDATION_ERROR` | The provided data is invalid |
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 404 | `NOT_FOUND` | The requested resource was not found |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

#### `GET /plans` — List plans available to your partner organization

Retrieve the subscription plans your partner organization is allowed to offer end-customers. The catalog is curated by your partner_config.allowedPlans — if it is empty (not yet configured), no plans are returned.

**Response** (`200`)

```json
{
  "success": true,
  "data": [
    {
      "id": "prod_ABC123",
      "name": "Pro",
      "prices": [
        {
          "id": "price_ABC123",
          "currency": "ron",
          "interval": "month"
        }
      ]
    }
  ]
}
```

**Errors**

| HTTP | Error code | Description |
|---|---|---|
| 401 | `UNAUTHORIZED` | API key is invalid or missing |
| 403 | `FORBIDDEN` | You do not have permission to access this resource |
| 500 | `INTERNAL_ERROR` | An internal error occurred |

## Error Codes

| Code | HTTP | Description |
|---|---|---|
| `CLIENT_HAS_INVOICES` | 400 | Cannot delete a client with existing invoices. Delete or cancel all invoices first. |
| `FORBIDDEN` | 403 | You do not have permission to access this resource |
| `INTERNAL_ERROR` | 500 | An internal error occurred |
| `NOT_FOUND` | 404 | The requested resource was not found |
| `NOT_LAST_IN_SERIES` | 400 | Only the last invoice in series can be deleted. Use cancellation for other invoices. |
| `ORG_EXISTS` | 409 | An organization with this tax ID already exists. |
| `PROVISIONING_TIMEOUT` | 503 | The provisioning request timed out but may still have succeeded. It is safe to retry — accounts are de-duplicated by tax ID. |
| `RATE_LIMIT_EXCEEDED` | 429 | You have exceeded the allowed request limit |
| `UNAUTHORIZED` | 401 | API key is invalid or missing |
| `VALIDATION_ERROR` | 400 | The provided data is invalid |

## Machine-Readable Spec

- OpenAPI 3.0 snapshot: [/llm-context/openapi-snapshot.json](/llm-context/openapi-snapshot.json)
- Live spec: `https://app.billyou.ro/api/docs/json`

---

*For domain-specific walkthroughs, see:*
- [Invoices](/llm-context/billyou-invoices.md)
- [Customers](/llm-context/billyou-customers.md)
- [E-Factura](/llm-context/billyou-efactura.md)
- [E-Transport](/llm-context/billyou-etransport.md)
- [Webhooks](/llm-context/billyou-webhooks.md)
- [Partners](/llm-context/billyou-partners.md)
- [OAuth](/llm-context/billyou-oauth.md)
- [Connect](/llm-context/billyou-connect.md)
