# Billyou API - E-Factura Integration

## Overview

E-Factura is Romania's mandatory electronic invoicing system operated by ANAF (Agentia Nationala de Administrare Fiscala). The Billyou API provides full integration with E-Factura, handling UBL XML generation, ANAF validation, submission, and status tracking.

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

## E-Factura Background

Since January 2024, all B2B transactions between Romanian companies must be reported through E-Factura. The process involves:

1. **Invoice creation** in UBL (Universal Business Language) XML format
2. **XML validation** against ANAF's schema
3. **Submission** to ANAF's SPV (Spatiul Privat Virtual) system
4. **ANAF processing** (validation and acceptance/rejection)
5. **Status polling** to check the result

Billyou handles steps 1-3 automatically and provides endpoints for step 5.

## Requirements

Before submitting invoices to E-Factura:

1. **Romanian client**: The invoice client must be based in Romania (has a Romanian CUI/tax ID)
2. **SPV authorization**: Your organization must have a valid SPV authorization token configured in Billyou
3. **Valid invoice data**: The invoice must contain all fields required by ANAF (tax ID, address, items with VAT, etc.). București addresses must include a sector (ANAF rule BR-RO-100) - the clients API enforces this at write time.

## Submission Flow

```
POST /invoices/:id/efactura/submissions
         |
         v
   Validate invoice
   (client, SPV token, XML)
         |
    +----+----+
    |         |
  Error    202 Accepted
    |         |
    v         v
  Return   Background upload
  error    to ANAF
              |
         +----+----+
         |         |
   "validated"  "rejected"/"failed"
         |         |
         v         v
   Upload index   Error details
   assigned       (retry endpoint for "failed")
```

## Endpoints

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

Submit an invoice to Romania's E-Factura system. This is an **asynchronous** operation:

1. The API validates the invoice (client nationality, SPV token, UBL XML)
2. If validation passes, returns `202 Accepted` with the submission resource
3. The actual ANAF upload continues in the background
4. You must poll `GET /api/efactura/submissions/:id` to check the result

**Example Request**:
```bash
curl -X POST https://app.billyou.ro/api/invoices/68dcc67261bb80850ae1299e/efactura/submissions \
  -H "X-API-Key: bk_user_your_key"
```

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

**Error - Non-Romanian Client** (`400 Bad Request`):
```json
{
  "success": false,
  "errorCode": "NON_ROMANIAN_CLIENT",
  "message": "E-Factura is only available for invoices with Romanian clients"
}
```

**Error - Already Submitted** (`400 Bad Request`):
```json
{
  "success": false,
  "errorCode": "INVOICE_ALREADY_SENT",
  "message": "This invoice has already been submitted to E-Factura"
}
```

**Error - Invalid XML** (`400 Bad Request`):
```json
{
  "success": false,
  "errorCode": "EFACTURA_XML_INVALID",
  "message": "The generated UBL XML failed ANAF validation"
}
```

**Error - SPV Token** (`401 Unauthorized`):
```json
{
  "success": false,
  "errorCode": "SPV_TOKEN_UNAUTHORIZED",
  "message": "SPV authorization token is invalid, expired, or rejected by ANAF"
}
```

**Error - Validation Failed** (`400 Bad Request`):
```json
{
  "success": false,
  "errorCode": "EFACTURA_VALIDATION_FAILED",
  "message": "Invoice XML validation failed",
  "details": {
    "translatedErrors": [
      { "message": "Adresa clientului este incompleta" }
    ]
  }
}
```

### GET /api/efactura/submissions/:id - Get Submission Status

Poll this endpoint after receiving `202 Accepted` from the submission endpoint. The submission ID currently maps to the invoice ID.

**Example Request**:
```bash
curl -X GET https://app.billyou.ro/api/efactura/submissions/68dcc67261bb80850ae1299e \
  -H "X-API-Key: bk_user_your_key"
```

**Response - Processing** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "68dcc67261bb80850ae1299e",
    "invoiceId": "68dcc67261bb80850ae1299e",
    "status": "processing",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:30:00.000Z"
  }
}
```

**Response - Validated by ANAF** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "5025641742",
    "invoiceId": "68dcc67261bb80850ae1299e",
    "status": "validated",
    "uploadIndex": "5025641742",
    "downloadId": "3130275322",
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:31:00.000Z"
  }
}
```

**Response - Rejected by ANAF** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "5025641742",
    "invoiceId": "68dcc67261bb80850ae1299e",
    "status": "rejected",
    "uploadIndex": "5025641742",
    "error": {
      "code": "SUBMISSION_ERROR",
      "message": "E: [BR-RO-100] ...",
      "details": {
        "errorCode": "BR-RO-100",
        "anafErrors": [{ "code": "BR-RO-100", "message": "E: [BR-RO-100] ..." }],
        "translatedErrors": [{ "rawCode": "BR-RO-100", "rawMessage": "E: [BR-RO-100] ...", "titleEn": "...", "fixEn": "..." }]
      }
    },
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:31:30.000Z"
  }
}
```
`error` on a rejection carries ANAF's reasons once Billyou has read ANAF's rejection message (rejections
from 2026-10-07 on). An older rejection may have no `error`: do not invent a reason; the reasons are
visible in the Billyou app. A rejected invoice must be corrected before it is submitted again.

**Response - Network/System Failure** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "id": "68dcc67261bb80850ae1299e",
    "invoiceId": "68dcc67261bb80850ae1299e",
    "status": "failed",
    "error": {
      "code": "SUBMISSION_ERROR",
      "message": "ANAF service temporarily unavailable. Please retry."
    },
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:31:00.000Z"
  }
}
```

**Response - Upload refused by ANAF** (`200 OK`): the upload never reached an index (for example the
ANAF authorisation has no SPV rights for the company). `error.code` stays `SUBMISSION_ERROR`;
`error.details.errorCode` says why, `anafErrors` carries ANAF's own messages and `translatedErrors`
the explanation and fix in Romanian and English.
```json
{
  "success": true,
  "data": {
    "id": "68dcc67261bb80850ae1299e",
    "invoiceId": "68dcc67261bb80850ae1299e",
    "status": "failed",
    "error": {
      "code": "SUBMISSION_ERROR",
      "message": "Nu exista niciun CIF pentru care sa aveti drept in SPV",
      "details": {
        "errorCode": "ANAF_NO_SPV_RIGHTS",
        "anafErrors": [
          { "code": "ANAF_UPLOAD_REJECTED", "message": "Nu exista niciun CIF pentru care sa aveti drept in SPV" }
        ],
        "translatedErrors": [
          {
            "rawCode": "ANAF_NO_SPV_RIGHTS",
            "titleEn": "The ANAF authorisation has no SPV rights",
            "fixEn": "Authorise again from the e-Invoice menu, with a certificate that has SPV rights for the company."
          }
        ]
      }
    },
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:30:03.000Z"
  }
}
```
Branch on `error.details.errorCode`. `error`, `details` and their fields are optional; new codes may appear.

| `details.errorCode` | What to do |
|---|---|
| `ANAF_NO_SPV_RIGHTS`, `ANAF_NO_SPV_RIGHTS_FOR_CIF`, `SPV_TOKEN_UNAUTHORIZED` | Do not retry. Authorise ANAF again in Billyou with a certificate that has SPV rights for the company. |
| `ANAF_TEMPORARY_ERROR`, `ANAF_TECHNICAL_ERROR` | ANAF fault, nothing filed. Retry with backoff (e.g. 5 min, 15 min, 1 h). |
| `ANAF_DAILY_LIMIT` | Retry the next day. |
| `ANAF_DUPLICATE_UPLOAD` | ANAF already has the invoice. Do not retry. |
| `INVOICE_CANCELED` | The invoice is cancelled. Do not retry. |
| `EFACTURA_UPLOAD_FAILED`, `EFACTURA_UPLOAD_ERROR` | No specific reason. One retry, then contact support. |
| validation rule codes (e.g. `BR-RO-100`) | The invoice data must be corrected first. |

For any other code, `translatedErrors[].actor` says who must act: `user` (do not retry), `anaf` (retry later),
`billyou` (contact support). For `rawCode: "ANAF_UNKNOWN"`, show `rawMessage` as is.
The invoice's age never blocks a submission: an invoice past its 5-working-day deadline can still be sent.

**Response - No Submission Found** (`404 Not Found`):
```json
{
  "success": false,
  "errorCode": "SUBMISSION_NOT_FOUND",
  "message": "Submission not found for this ID"
}
```

### POST /api/efactura/submissions/:id/retry - Retry a Failed Submission

Retry a previously failed E-Factura submission. Only submissions in a retryable state (`failed`, or rejected as retryable by ANAF) can be retried; others return `400 SUBMISSION_NOT_RETRYABLE`.

```bash
curl -X POST https://app.billyou.ro/api/efactura/submissions/68dcc67261bb80850ae1299e/retry \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`202 Accepted`): the submission resource, same shape as the status endpoint.

**Error** (`400 Bad Request`):
```json
{
  "success": false,
  "errorCode": "SUBMISSION_NOT_RETRYABLE",
  "message": "Submission cannot be retried in current status: validated. Only failed or rejected-retryable submissions can be retried."
}
```

## Status Values

| Status | Description | Next Action |
|---|---|---|
| `pending` | Submission created, upload not yet started | Poll again in 5-10 seconds |
| `processing` | Upload is in progress | Poll again in 5-10 seconds |
| `uploaded` | Uploaded to ANAF SPV, awaiting ANAF processing | Poll again in 5-10 seconds |
| `validated` | Successfully accepted by ANAF | Done. `uploadIndex` is the ANAF reference number |
| `rejected` | ANAF rejected the invoice (reasons in `error`, see above) | Correct the invoice, then submit it again. Do not retry it unchanged |
| `failed` | The upload did not reach ANAF | Act on `error.details.errorCode` (see above); retry only where it says so |

Always address a submission by the **invoice id**. `data.id` becomes ANAF's upload index once there is one.
Submit an invoice once: while ANAF holds it (`spvLifecycleState` `uploaded-to-spv`, `spv-validation` or
`validated` on `GET /api/invoices/:id`) a new submission is refused with `400 INVOICE_ALREADY_SENT`.

## Polling Strategy

After receiving `202 Accepted`, implement a polling loop:

```typescript
async function waitForEfacturaResult(invoiceId: string): Promise<any> {
  const maxAttempts = 30;
  const pollIntervalMs = 5000; // 5 seconds

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const result = await billyouRequest(
      "GET",
      `/efactura/submissions/${invoiceId}`
    );

    const status = result.data.status;

    if (status === "validated") {
      console.log(`E-Factura accepted. Upload index: ${result.data.uploadIndex}`);
      return result.data;
    }

    if (status === "rejected") {
      console.error(`E-Factura rejected: ${result.data.error?.message}`);
      return result.data;
    }

    if (status === "failed") {
      console.warn(`Upload failed: ${result.data.error?.message}`);
      // Retryable - use POST /efactura/submissions/:id/retry
      return result.data;
    }

    // Status is "pending", "processing" or "uploaded" - wait and poll again
    await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
  }

  throw new Error("E-Factura polling timed out after maximum attempts");
}
```

**Recommended polling parameters**:
- **Initial delay**: 3 seconds (ANAF typically takes 5-30 seconds)
- **Poll interval**: 5 seconds
- **Maximum attempts**: 30 (2.5 minutes total)
- **Exponential backoff**: Optional, but recommended for long waits
- **Upper limit**: ANAF can take hours. If a submission is still `processing` after 24 hours, stop polling and
  read `GET /api/invoices/:id` → `spvLifecycleState` (`validated` = accepted); otherwise contact support.
  Do not resubmit.

## Sandbox E-Factura Behavior

In sandbox mode, E-Factura behavior depends on the `efacturaMode` setting:

### smart_mock (Default)

- Validates the invoice locally against the same rules ANAF uses
- Returns realistic mock responses without contacting ANAF
- Returns the final result **synchronously** (`200 OK` with `simulation: true`) - no polling needed
- Useful for integration testing without ANAF credentials

**Behavior**:
- Valid invoices: Returns `status: "validated"` with a mock `uploadIndex`
- Invalid invoices: Returns `status: "rejected"` with a `validationErrors` array of realistic ANAF error messages
- No network calls to ANAF

### full_test

- Submits to ANAF's test environment
- Requires valid ANAF test credentials configured
- Behaves identically to production E-Factura flow (async, `202 Accepted` + polling)
- Useful for end-to-end testing with ANAF

## Common E-Factura Errors

### NON_ROMANIAN_CLIENT

The invoice client does not have a Romanian tax ID (CUI). E-Factura is only for invoices between Romanian businesses (B2B within Romania).

**Fix**: Ensure the client's `taxId` is a valid Romanian CUI (optionally prefixed with "RO").

### INVOICE_ALREADY_SENT

ANAF already has this invoice, or is deciding on it (`spvLifecycleState` `uploaded-to-spv`, `spv-validation` or
`validated`). Each invoice is submitted once; poll the existing submission instead.

**Fix**: After a rejection the corrected invoice can be submitted again. To change an invoice ANAF accepted,
issue a storno and a new invoice.

### EFACTURA_XML_INVALID

The UBL XML generated from the invoice data failed ANAF's schema validation. This typically means missing or invalid fields.

**Common causes**:
- Missing client address fields (city, county, country)
- București address without a sector (BR-RO-100)
- Invalid tax ID format
- Missing VAT information
- Invalid currency or amounts

**Fix**: Ensure all required invoice and client fields are populated with valid data.

### SPV_TOKEN_UNAUTHORIZED

The SPV (Spatiul Privat Virtual) authorization token is missing, expired, or was rejected by ANAF.

**Common causes**:
- SPV token has expired (tokens expire periodically)
- SPV authorization was not configured for your organization
- ANAF rejected the token during validation

**Fix**: Re-authorize your SPV token through the Billyou dashboard or contact support.

### EFACTURA_VALIDATION_FAILED

The invoice failed validation during the E-Factura submission process. The response may include `details.translatedErrors` with human-readable messages.

**Fix**: Correct the reported fields and retry. If the error persists with no details, contact support.

## Complete Workflow Example

```typescript
const API_KEY = "bk_user_your_api_key";
const BASE_URL = "https://app.billyou.ro/api";

async function billyouRequest(method: string, path: string, body?: object) {
  const response = await fetch(`${BASE_URL}${path}`, {
    method,
    headers: {
      "X-API-Key": API_KEY,
      "Content-Type": "application/json",
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  return response.json();
}

async function createAndSubmitEfactura() {
  // 1. Create a Romanian client (city is Bucuresti, so sector is required)
  const client = await billyouRequest("POST", "/clients", {
    name: "SC Constructii Moderne SRL",
    taxId: "RO45678901",
    tradeRegistryNumber: "J40/9876/2022",
    address: {
      street: "Strada Mihai Eminescu nr. 50",
      city: "București",
      county: "București",
      sector: "Sectorul 2",
      postalCode: "010517",
      country: "România",
    },
    IBAN: "RO49AAAA1B31007593840000",
    contactEmails: ["facturi@constructii-moderne.ro"],
  });

  // 2. Create the invoice
  const invoice = await billyouRequest("POST", "/invoices", {
    clientId: client.data._id,
    seriesId: "507f1f77bcf86cd799439011",
    issueDate: "2025-03-15",
    dueDate: "2025-04-14",
    services: [
      {
        description: "Servicii consultanta tehnica constructii",
        quantity: 40,
        unitPrice: 200.00,
        unitOfMeasure: "ore",
        vatRate: 21,
      },
      {
        description: "Raport evaluare structurala cladire",
        quantity: 1,
        unitPrice: 5000.00,
        unitOfMeasure: "buc",
        vatRate: 21,
      },
    ],
    notes: "Plata prin transfer bancar. Termen: 30 zile calendaristice.",
    language: "ro",
  });

  console.log(`Invoice created: ${invoice.data.serialNumber}`);

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

  if (!submission.success) {
    console.error(`E-Factura submission failed: ${submission.errorCode}`);
    return;
  }

  console.log("Invoice submitted to E-Factura. Polling for status...");

  // 4. Poll for result
  let attempts = 0;
  while (attempts < 30) {
    await new Promise(r => setTimeout(r, 5000));
    attempts++;

    const status = await billyouRequest(
      "GET",
      `/efactura/submissions/${invoice.data.invoiceId}`
    );

    console.log(`Attempt ${attempts}: status = ${status.data.status}`);

    if (status.data.status === "validated") {
      console.log(`E-Factura accepted! Upload index: ${status.data.uploadIndex}`);
      return;
    }

    if (status.data.status === "rejected") {
      console.error(`E-Factura rejected: ${status.data.error?.message}`);
      return;
    }

    if (status.data.status === "failed") {
      const code = status.data.error?.details?.errorCode;
      // Retry only ANAF-side faults; everything else needs the user to act.
      if (["ANAF_TEMPORARY_ERROR", "ANAF_TECHNICAL_ERROR"].includes(code)) {
        console.warn(`ANAF fault (${code}) - retrying via the retry endpoint`);
        await billyouRequest(
          "POST",
          `/efactura/submissions/${invoice.data.invoiceId}/retry`
        );
      } else {
        console.error(`Upload failed (${code}): ${status.data.error?.message}`);
        return;
      }
    }
  }

  console.error("Polling timed out");
}
```

## Webhook Events

You can receive real-time notifications for E-Factura events via webhooks:

| Event Type | Description |
|---|---|
| `invoice.efactura_sent` | Invoice was submitted to ANAF |
| `invoice.efactura_accepted` | ANAF accepted the invoice |
| `invoice.efactura_rejected` | ANAF rejected the invoice |

See the [Webhooks reference](/llm-context/billyou-webhooks.md) for setup details.

## Error Codes Summary

| Code | HTTP | Retryable | Description |
|---|---|---|---|
| `NON_ROMANIAN_CLIENT` | 400 | No | Client is not Romanian |
| `INVOICE_ALREADY_SENT` | 400 | No | Already submitted to E-Factura |
| `EFACTURA_XML_INVALID` | 400 | No | XML validation failed |
| `EFACTURA_VALIDATION_FAILED` | 400 | No | Invoice failed validation |
| `EFACTURA_LOCAL_VALIDATION_FAILED` | 400 | No | Invoice failed e-Factura validation (see `details.translatedErrors`) |
| `EFACTURA_INCOMPLETE_VENDOR_ADDRESS` / `_CLIENT_ADDRESS`, `EFACTURA_*_SECTOR` | 400 | No | Vendor or client address incomplete |
| `SPV_TOKEN_UNAUTHORIZED` | 401 or 400 | No | SPV token missing, invalid or expired |
| `SUBMISSION_NOT_FOUND` | 404 | No | No submission exists for this ID |
| `SUBMISSION_NOT_RETRYABLE` | 400 | No | Submission is not in a retryable state |
| `EFACTURA_UPLOAD_FAILED` | 500 | Yes | Server-side upload error |
