# Billyou API - Invoices

## Overview

The Invoices domain covers the complete invoice lifecycle: creation, PDF generation, payment tracking, email delivery, cancellation, and E-Factura submission. Invoices are the core entity in the Billyou platform.

**Base URL**: `https://app.billyou.ro/api`
**Authentication**: `X-API-Key` header required on all requests.

**Strict request validation**: request bodies reject unknown fields. Sending a property that is not part of the documented schema returns `400 VALIDATION_ERROR` with a message naming the offending property (e.g., `body must NOT have additional properties` with `additionalProperty: "foo"` in the details).

## Invoice Lifecycle

```
Draft -> Published -> unpaid -> partial -> paid
                             -> canceled
```

- **Draft**: Created with `draft: true`. Can be edited and does not consume a series number until published.
- **Published**: Finalized invoice. PDF is generated and a serial number is assigned.

**Payment status values** (`paymentStatus`): `unpaid`, `paid`, `partial`, `canceled`

- **unpaid**: No payments recorded.
- **partial**: Some payments recorded, but less than the invoice total.
- **paid**: All payments received (totalPaid >= totalWithVAT).
- **canceled**: Invoice was cancelled via `POST /invoices/:id/cancel`.

Invoices submitted to E-Factura additionally carry an `spvLifecycleState` field tracking the ANAF SPV lifecycle.

## Invoice Data Model

The public invoice object contains the following fields (internal fields such as `organizationId` and `metadata` are **not** exposed):

| Field | Type | Description |
|---|---|---|
| `_id` | string | Unique identifier (MongoDB ObjectId) |
| `invoiceId` | string | Secondary invoice identifier (UUID) |
| `filename` | string | PDF filename in storage |
| `createdAt` | string | Creation timestamp |
| `paymentStatus` | string | `unpaid`, `paid`, `partial`, or `canceled` |
| `spvLifecycleState` | string | E-Factura (SPV) lifecycle state, when submitted |
| `payments` | array | Recorded payments for this invoice |
| `stornoInvoiceId` | string | ID of the storno (reversal) invoice, if cancelled |
| `data.serialNumber` | string | Human-readable serial number (e.g., "FACT-00123") |
| `data.invoiceDate` | string | Issue date (YYYY-MM-DD) |
| `data.paymentDueDate` | string | Due date (YYYY-MM-DD) |
| `data.currency` | string | Currency code (e.g., "RON", "EUR") |
| `data.exchangeRate` | number | Exchange rate to RON |
| `data.isVAT` | boolean | Whether VAT applies |
| `data.items` | array | Line items with quantities, prices, VAT |
| `data.totals` | object | Computed totals (see below) |
| `data.client` | object | Embedded client snapshot |
| `data.vendor` | object | Embedded vendor (your company) snapshot |
| `data.additionalNotes` | string | Free-text notes |
| `data.language` | string | PDF language: "ro" or "en" |

### Totals Object

```json
{
  "totalWithoutVAT": 1600.00,
  "totalVAT": 336.00,
  "totalWithVAT": 1936.00
}
```

### Line Item Object

```json
{
  "description": "Web Development Services",
  "quantity": 8,
  "unitPrice": 150.00,
  "unitOfMeasure": "hours",
  "VATRate": 21,
  "currency": "RON",
  "exchangeRate": 1,
  "totalWithoutVAT": 1200.00,
  "VATValue": 252.00
}
```

## Romanian VAT Rates

For Romanian clients, VAT rates must be one of **[0, 9, 11, 21]** (Romanian VAT, Law 141/2025):
- **0%** - VAT exempt operations
- **9%** - Reduced rate (kept for specific transitional operations)
- **11%** - Reduced rate (food, medicine, books, accommodation)
- **21%** - Standard rate (most services and goods)

Any other rate on an invoice for a Romanian client is rejected with `400 INVALID_VAT_RATE`.

## Endpoints

### POST /api/invoices - Create Invoice

Create a new invoice or draft. Before creating, you need:
1. A client ID (from `GET /api/clients`)
2. A series ID (from `GET /api/series`) OR a custom serial number

**Serial Number Options** (mutually exclusive):
- `seriesId`: Auto-generates next number from the series (e.g., "FACT-00123")
- `customSerialNumber`: User-defined number (pattern: `^[A-Za-z0-9-_]+$`, max 50 chars)

Providing both returns `400 INVALID_SERIAL_CONFIG`. Publishing (non-draft) without either returns `400 MISSING_SERIAL_CONFIG`.

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `clientId` | string | Yes | Client ObjectId |
| `seriesId` | string | No | Series ObjectId (mutually exclusive with customSerialNumber) |
| `customSerialNumber` | string | No | Custom invoice number |
| `draft` | boolean | No | Create as draft (default: false) |
| `issueDate` | string | Yes | Issue date (YYYY-MM-DD) |
| `dueDate` | string | No | Due date (YYYY-MM-DD) |
| `services` | array | Yes | Line items (1-50) |
| `services[].description` | string | Yes | Item description (1-100 chars, ANAF rule BR-RO-L100) |
| `services[].quantity` | number | Yes | Quantity (min: 0.01) |
| `services[].unitPrice` | number | Yes | Unit price (min: 0) |
| `services[].vatRate` | number | Yes | VAT percentage (Romanian clients: 0, 9, 11, or 21) |
| `services[].unitOfMeasure` | string | No | Unit (default: "buc") |
| `notes` | string | No | Additional notes (max 1000 chars) |
| `language` | string | No | PDF language: "ro" (default) or "en" |

Unknown fields anywhere in the body are rejected with `400 VALIDATION_ERROR`.

**Example - Standard Invoice**:
```bash
curl -X POST https://app.billyou.ro/api/invoices \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "60f7b1b9c9e7b4a1e8d1c2b4",
    "seriesId": "507f1f77bcf86cd799439011",
    "issueDate": "2025-03-15",
    "dueDate": "2025-04-14",
    "services": [
      {
        "description": "Servicii dezvoltare software - luna martie",
        "quantity": 160,
        "unitPrice": 50.00,
        "unitOfMeasure": "ore",
        "vatRate": 21
      },
      {
        "description": "Licenta software lunar",
        "quantity": 1,
        "unitPrice": 200.00,
        "unitOfMeasure": "buc",
        "vatRate": 21
      }
    ],
    "notes": "Plata prin transfer bancar in contul RO49AAAA1B31007593840000. Termen: 30 zile.",
    "language": "ro"
  }'
```

**Response** (`201 Created`):
```json
{
  "success": true,
  "data": {
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "serialNumber": "FACT-00126"
  }
}
```

**Example - Draft Invoice**:
```bash
curl -X POST https://app.billyou.ro/api/invoices \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "60f7b1b9c9e7b4a1e8d1c2b4",
    "draft": true,
    "issueDate": "2025-03-15",
    "services": [
      {
        "description": "Consulting services",
        "quantity": 10,
        "unitPrice": 100.00,
        "vatRate": 21
      }
    ]
  }'
```

**Example - Custom Serial Number**:
```bash
curl -X POST https://app.billyou.ro/api/invoices \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "clientId": "60f7b1b9c9e7b4a1e8d1c2b4",
    "customSerialNumber": "CUSTOM-INV-2025-001",
    "issueDate": "2025-03-15",
    "dueDate": "2025-04-14",
    "services": [
      {
        "description": "Design services",
        "quantity": 1,
        "unitPrice": 2500.00,
        "vatRate": 21
      }
    ]
  }'
```

### GET /api/invoices - List Invoices

Retrieve a paginated list of invoices with optional filtering.

**Query Parameters**:

| Parameter | Type | Description |
|---|---|---|
| `page` | integer | Page number (default: 1) |
| `limit` | integer | Items per page (default: 20, max: 100) |
| `paymentStatus` | string | Filter: `unpaid`, `paid`, `partial`, `canceled` |
| `clientId` | string | Filter by client ObjectId |
| `startDate` | string | From date (YYYY-MM-DD) |
| `endDate` | string | Until date (YYYY-MM-DD) |

**Example - Filter by payment status and date range**:
```bash
curl -X GET "https://app.billyou.ro/api/invoices?paymentStatus=paid&startDate=2025-01-01&endDate=2025-03-31&limit=50" \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```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": "paid",
        "data": {
          "serialNumber": "FACT-00123",
          "invoiceDate": "2025-01-15",
          "paymentDueDate": "2025-02-14",
          "totals": {
            "totalWithoutVAT": 1600,
            "totalVAT": 336,
            "totalWithVAT": 1936
          },
          "client": {
            "name": "SC Example SRL",
            "taxId": "12345678"
          }
        }
      }
    ],
    "pagination": {
      "total": 15,
      "page": 1,
      "limit": 50,
      "pages": 1
    }
  }
}
```

### GET /api/invoices/:id - Get Invoice

Retrieve full details for a specific invoice including all line items, client snapshot, and vendor data. The public shape includes `paymentStatus`, `spvLifecycleState`, `payments`, and `stornoInvoiceId`; it does **not** include `organizationId`, `metadata`, or a top-level `client` field (the client snapshot lives under `data.client`).

**Example**:
```bash
curl -X GET https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1 \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```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",
    "payments": [],
    "data": {
      "isVAT": true,
      "currency": "RON",
      "exchangeRate": 1,
      "invoiceDate": "2025-01-15",
      "paymentDueDate": "2025-02-14",
      "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"
      },
      "vendor": {
        "_id": "60f7b1b9c9e7b4a1e8d1c2b3",
        "name": "Your Company SRL",
        "taxIdentificationNumber": "98765432",
        "tradeRegistryNumber": "J40/5678/2020"
      },
      "additionalNotes": "Payment due in 30 days.",
      "language": "ro",
      "serialNumber": "FACT-00123"
    }
  }
}
```

### DELETE /api/invoices/:id - Delete Invoice

Delete an invoice. Constraints:
- Only the **last invoice in a series** can be deleted (`NOT_LAST_IN_SERIES`)
- Invoices with recorded **payments** cannot be deleted (`INVOICE_HAS_PAYMENTS`)
- Invoices **submitted to E-Factura** cannot be deleted (`EFACTURA_SUBMITTED`)

**Example**:
```bash
curl -X DELETE https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1 \
  -H "X-API-Key: bk_user_your_key"
```

**Success** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "deleted": true,
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1"
  }
}
```

**Error** (`400 Bad Request`):
```json
{
  "success": false,
  "errorCode": "NOT_LAST_IN_SERIES",
  "message": "Only the last invoice in a series can be deleted"
}
```

### POST /api/invoices/:id/cancel - Cancel Invoice

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

```bash
curl -X POST https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1/cancel \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "cancelled": true,
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1"
  }
}
```

### GET /api/invoices/:id/pdf - Download PDF

Get a presigned URL to download the invoice PDF. The URL expires after 10 minutes (600 seconds).

```bash
curl -X GET https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1/pdf \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```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
  }
}
```

**TypeScript usage**:
```typescript
const result = await billyouRequest("GET", `/invoices/${invoiceId}/pdf`);
const pdfResponse = await fetch(result.data.downloadUrl);
const pdfBuffer = await pdfResponse.arrayBuffer();
// Save to file or send to client
```

### GET /api/invoices/:id/paymentstatus - Payment Status

Retrieve payment details for an invoice.

```bash
curl -X GET https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1/paymentstatus \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "totalAmount": 1936.00,
    "totalPaid": 500.00,
    "remainingAmount": 1436.00,
    "isPaid": false,
    "isPartiallyPaid": true,
    "paymentStatus": "partial",
    "dueDate": "2025-02-14",
    "isOverdue": false,
    "payments": [
      {
        "amount": 500.00,
        "date": "2025-01-20T10:30:00.000Z",
        "type": "bank_transfer"
      }
    ]
  }
}
```

### POST /api/invoices/:id/payments - Record Payment

Record a payment for an invoice. The only way to create a payment is via this nested route — there is **no** top-level payment-creation endpoint.

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `amount` | number | Yes | Payment amount (min: 0.01) |
| `paymentDate` | string | Yes | Payment date (date or datetime) |
| `paymentMethod` | string | No | `cash`, `bank_transfer`, `card`, `check`, `other` |
| `currency` | string | No | Payment currency (default: "RON") |
| `exchangeRate` | number | No | Exchange rate to RON (required for non-RON currencies) |
| `reference` | string | No | Payment reference (max 200 chars) |
| `notes` | string | No | Additional notes (max 500 chars) |

```bash
curl -X POST https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1/payments \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": 500.00,
    "paymentDate": "2025-04-01",
    "paymentMethod": "bank_transfer",
    "reference": "TXN789",
    "notes": "Plata partiala - ref TXN789"
  }'
```

**Response** (`201 Created`):
```json
{
  "success": true,
  "data": {
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "amount": 500.00,
    "paymentMethod": "bank_transfer",
    "paymentDate": "2025-04-01",
    "paymentStatus": "partial"
  }
}
```

Related routes: `GET /api/invoices/:id/payments` lists payments for an invoice; `DELETE /api/invoices/:id/payments/:paymentId` removes a payment and recalculates the invoice status.

### POST /api/invoices/:id/email - Send Email

Send an invoice access link to a recipient. The recipient must be authorized in the client's contact list (or use `addToContacts` to add them).

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `to` | string | Yes | Recipient email |
| `subject` | string | Yes | Email subject (1-200 chars) |
| `body` | string | Yes | Email message (1-2000 chars) |
| `language` | string | No | "ro" (default) or "en" |
| `addToContacts` | boolean | No | Add to client contacts (default: false) |

```bash
curl -X POST https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1/email \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "contabilitate@example.ro",
    "subject": "Factura FACT-00123 - SC Example SRL",
    "body": "Buna ziua,\n\nVa transmitem factura FACT-00123 in valoare de 1,936.00 RON.\n\nVa multumim!",
    "language": "ro"
  }'
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {}
}
```

### POST /api/invoices/:id/efactura/submissions - Submit to E-Factura

Submit an invoice to Romania's E-Factura system. This is an async process. See the [E-Factura reference](/llm-context/billyou-efactura.md) for full details.

```bash
curl -X POST https://app.billyou.ro/api/invoices/60f7b1b9c9e7b4a1e8d1c2c1/efactura/submissions \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`202 Accepted`):
```json
{
  "success": true,
  "data": {
    "id": "60f7b1b9c9e7b4a1e8d1c2c1",
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "status": "processing",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:30:00.000Z"
  }
}
```

### GET /api/efactura/submissions/:id - E-Factura Submission Status

Poll the status of an E-Factura submission (the submission ID currently maps to the invoice ID).

```bash
curl -X GET https://app.billyou.ro/api/efactura/submissions/60f7b1b9c9e7b4a1e8d1c2c1 \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "5025641742",
    "invoiceId": "60f7b1b9c9e7b4a1e8d1c2c1",
    "status": "validated",
    "uploadIndex": "5025641742",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:31:00.000Z"
  }
}
```

Status values: `pending`, `processing`, `uploaded`, `validated`, `rejected`, `failed`.

## Series Management

Invoices use series to auto-generate sequential serial numbers. See the full API reference for series CRUD endpoints.

**Key points**:
- A series defines: prefix (e.g., "FACT"), year, type (invoice/receipt/proforma)
- Creating an invoice with `seriesId` auto-increments the series counter
- Using `customSerialNumber` bypasses the series system entirely
- Series cannot be deleted if invoices reference them

## Common Workflows

### Create and Send an Invoice

```typescript
// 1. Create the invoice
const invoice = await billyouRequest("POST", "/invoices", {
  clientId: "60f7b1b9c9e7b4a1e8d1c2b4",
  seriesId: "507f1f77bcf86cd799439011",
  issueDate: "2025-03-15",
  dueDate: "2025-04-14",
  services: [
    { description: "Development", quantity: 160, unitPrice: 50, vatRate: 21, unitOfMeasure: "ore" }
  ],
  language: "ro"
});

// 2. Send by email
await billyouRequest("POST", `/invoices/${invoice.data.invoiceId}/email`, {
  to: "client@example.ro",
  subject: `Factura ${invoice.data.serialNumber}`,
  body: "Va transmitem factura atasata. Multumim!"
});

// 3. Submit to E-Factura (Romanian clients only)
const efactura = await billyouRequest(
  "POST",
  `/invoices/${invoice.data.invoiceId}/efactura/submissions`
);

// 4. Poll for E-Factura status
let status;
do {
  await new Promise(r => setTimeout(r, 5000)); // wait 5 seconds
  status = await billyouRequest("GET", `/efactura/submissions/${invoice.data.invoiceId}`);
} while (["pending", "processing", "uploaded"].includes(status.data.status));

console.log(`E-Factura status: ${status.data.status}`);
```

### Record a Payment and Check Status

```typescript
// Record partial payment (payments are always created under an invoice)
await billyouRequest("POST", `/invoices/${invoiceId}/payments`, {
  amount: 500.00,
  paymentDate: "2025-04-01",
  paymentMethod: "bank_transfer",
  notes: "Partial payment - ref TXN789"
});

// Check payment status
const paymentStatus = await billyouRequest(
  "GET",
  `/invoices/${invoiceId}/paymentstatus`
);

console.log(`Remaining: ${paymentStatus.data.remainingAmount} RON`);
```

## Error Codes

| Code | HTTP | Description |
|---|---|---|
| `VALIDATION_ERROR` | 400 | Invalid request body or parameters (including unknown fields) |
| `INVALID_VAT_RATE` | 400 | VAT rate not in [0, 9, 11, 21] for a Romanian client |
| `MISSING_SERIAL_CONFIG` | 400 | Neither seriesId nor customSerialNumber provided for a published invoice |
| `INVALID_SERIAL_CONFIG` | 400 | Both seriesId and customSerialNumber provided |
| `NOT_LAST_IN_SERIES` | 400 | Cannot delete; not the last invoice in series |
| `INVOICE_HAS_PAYMENTS` | 400 | Cannot delete; invoice has recorded payments |
| `EFACTURA_SUBMITTED` | 400 | Cannot delete; invoice was submitted to E-Factura |
| `INVOICE_NOT_FOUND` | 404 | Invoice not found |
| `ORGANIZATION_NOT_FOUND` | 404 | Organization record could not be resolved |
| `NON_ROMANIAN_CLIENT` | 400 | E-Factura requires a Romanian client |
| `INVOICE_ALREADY_SENT` | 400 | Invoice already submitted to E-Factura |
| `EFACTURA_XML_INVALID` | 400 | Generated XML failed ANAF validation |
| `SPV_TOKEN_UNAUTHORIZED` | 401 | SPV authorization token is invalid/expired |
