# Billyou API - Customers (Clients)

## Overview

The Customers domain handles business client management for your organization. Clients are required to create invoices and are the recipients of your invoices. The API supports Romanian business identifiers (CUI, CNP) and standard European VAT IDs.

**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.

## Client Data Model

| Field | Type | Description |
|---|---|---|
| `_id` | string | Unique identifier (MongoDB ObjectId) |
| `name` | string | Business name (e.g., "SC Example SRL") |
| `taxId` | string | Tax identification number (CUI, CNP, or EU VAT ID) |
| `tradeRegistryNumber` | string | Trade registry number (e.g., "J40/1234/2020") |
| `address` | object | Nested address object (see below) |
| `address.street` | string | Street address |
| `address.city` | string | City |
| `address.county` | string | County/Judet |
| `address.postalCode` | string | Postal code |
| `address.sector` | string | Sector (required for București addresses, see below) |
| `address.country` | string | Country (default: "România") |
| `IBAN` | string | Bank account IBAN |
| `contactEmails` | string[] | Contact email addresses |
| `contact` | string | Contact person name |
| `phone` | string | Phone number |
| `bank` | string | Bank name |
| `hasSelfBillingContract` | boolean | Client allows self-billing (Autofacturare) |
| `createdAt` | string | Creation timestamp |
| `updatedAt` | string | Last update timestamp |

Note on response shapes: `GET /api/clients/:id` (and the create/update responses, which return the persisted client) include the nested `address` object; for backward compatibility the flat fields (`city`, `county`, `sector`, `postalCode`, `country`) also appear at the top level. Items in the `GET /api/clients` list are returned in the flat storage shape, where `address` is the street line string.

## Romanian Tax Identifiers

### CUI (Cod Unic de Inregistrare) - Business Tax ID

The CUI is Romania's unique business identification number, issued by the Trade Registry.

**Format**:
- 2-10 digits (e.g., "12345678")
- May be prefixed with "RO" for VAT-registered companies (e.g., "RO12345678")
- Uses a Luhn-like checksum algorithm with weights `[7, 5, 3, 2, 1, 7, 5, 3, 2]`

**Validation**:
- Strip the "RO" prefix if present
- Must be numeric (2-10 digits)
- Checksum validation ensures the CUI is legitimate

**Examples**:
- `"12345678"` - Standard CUI
- `"RO12345678"` - CUI with VAT prefix
- `"1234567890"` - 10-digit CUI

### CNP (Cod Numeric Personal) - Personal Identification Number

The CNP is Romania's 13-digit personal identification number for individuals (PFA - Persoana Fizica Autorizata).

**Format**: 13 digits with structure: `SAALLZZJJNNNC`
- `S`: Sex/century digit (1-8)
- `AA`: Year of birth (last 2 digits)
- `LL`: Month of birth (01-12)
- `ZZ`: Day of birth (01-31)
- `JJ`: County code (01-52)
- `NNN`: Sequential number (001-999)
- `C`: Checksum digit

**Validation**: Uses weights `[2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9]`

### EU VAT IDs

For non-Romanian EU clients, provide the VAT ID with country prefix:
- `"DE123456789"` - Germany
- `"FR12345678901"` - France
- `"IT12345678901"` - Italy

## București Addresses Require a Sector (IMPORTANT)

Romania's e-Factura system (ANAF rule **BR-RO-100**) rejects any invoice whose party address is in the city of București but does not specify which of the city's six sectors it belongs to. București is administratively divided into sectors 1-6, and ANAF treats the sector as the mandatory "county subdivision" for the capital.

To stop this from surfacing later as an opaque ANAF rejection, the Billyou API enforces the rule **at client creation and update time**:

- If `address.city` is București (matched diacritic-insensitively: "București", "Bucuresti", "bucurești" all count), then `address.sector` is required.
- The sector is valid when its first digit is 1-6. Accepted formats: `"Sectorul 3"`, `"Sector 3"`, `"S3"`, or just `"3"`.
- Only the **city** triggers the rule. A town near the capital with `county: "București"` but a different city (e.g., `city: "Voluntari"`) does **not** need a sector.
- On `PUT /api/clients/:id`, the rule is re-checked only when the update touches `address.city` or `address.sector`. Partial updates to unrelated fields (e.g., phone only) are not blocked.

**Violation response** (`400 Bad Request`):
```json
{
  "success": false,
  "errorCode": "MISSING_BUCHAREST_SECTOR",
  "message": "Bucharest addresses require address.sector (e.g. \"Sectorul 3\") for e-Factura submission."
}
```

**Fix**: add the sector to the address, e.g. `"address": { "city": "București", "county": "București", "sector": "Sectorul 3", "country": "România" }`.

## Endpoints

### POST /api/clients - Create Client

Add a new business client to your organization.

**Request Body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | Yes | Business name (1-200 chars) |
| `taxId` | string | Yes | Tax ID: CUI, CNP, or EU VAT ID (1-50 chars) |
| `tradeRegistryNumber` | string | No | Trade registry number (max 50 chars) |
| `address` | object | Yes | Address information |
| `address.street` | string | No | Street address (max 200 chars) |
| `address.city` | string | Yes | City (1-100 chars) |
| `address.county` | string | Yes | County/Judet (1-100 chars) |
| `address.postalCode` | string | No | Postal code (max 20 chars) |
| `address.sector` | string | Conditional | Sector 1-6; **required when city is București** (max 10 chars) |
| `address.country` | string | Yes | Country (default: "România", max 100 chars) |
| `IBAN` | string | No | Bank account IBAN (max 50 chars) |
| `contactEmails` | string[] | No | Contact email addresses |
| `contact` | string | No | Contact person name (max 200 chars) |
| `phone` | string | No | Phone number (max 50 chars) |
| `bank` | string | No | Bank name (max 200 chars) |
| `hasSelfBillingContract` | boolean | No | Client has a self-billing (Autofacturare) contract |

Unknown fields are rejected with `400 VALIDATION_ERROR`. A duplicate `taxId` within your organization is rejected with `409 CLIENT_DUPLICATE_TAX_ID`.

**Example - Romanian Business (SRL, București)**:
```bash
curl -X POST https://app.billyou.ro/api/clients \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "SC Digital Solutions SRL",
    "taxId": "RO12345678",
    "tradeRegistryNumber": "J40/1234/2020",
    "address": {
      "street": "Bulevardul Unirii nr. 45, Bl. A3, Sc. 2, Et. 4, Ap. 12",
      "city": "București",
      "county": "București",
      "postalCode": "030167",
      "sector": "Sectorul 3",
      "country": "România"
    },
    "IBAN": "RO49AAAA1B31007593840000",
    "contactEmails": ["contabilitate@digitalsolutions.ro", "manager@digitalsolutions.ro"],
    "contact": "Ion Popescu",
    "phone": "+40721234567",
    "bank": "Banca Transilvania"
  }'
```

**Example - Romanian Individual (PFA)**:
```bash
curl -X POST https://app.billyou.ro/api/clients \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Popescu Ion PFA",
    "taxId": "1850315400123",
    "address": {
      "street": "Strada Lalelelor nr. 10",
      "city": "Cluj-Napoca",
      "county": "Cluj",
      "postalCode": "400000",
      "country": "România"
    },
    "contactEmails": ["ion.popescu@gmail.com"],
    "phone": "+40740123456"
  }'
```

**Example - EU Client (Germany)**:
```bash
curl -X POST https://app.billyou.ro/api/clients \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "TechGmbH Berlin",
    "taxId": "DE123456789",
    "address": {
      "street": "Friedrichstrasse 123",
      "city": "Berlin",
      "county": "Berlin",
      "postalCode": "10117",
      "country": "Germany"
    },
    "contactEmails": ["billing@techgmbh.de"],
    "IBAN": "DE89370400440532013000",
    "bank": "Commerzbank"
  }'
```

**Response** (`201 Created`) - returns the persisted client:
```json
{
  "success": true,
  "data": {
    "_id": "60f7b1b9c9e7b4a1e8d1c2b4",
    "clientId": "60f7b1b9c9e7b4a1e8d1c2b4",
    "name": "SC Digital Solutions SRL",
    "taxId": "RO12345678",
    "tradeRegistryNumber": "J40/1234/2020",
    "address": {
      "street": "Bulevardul Unirii nr. 45, Bl. A3, Sc. 2, Et. 4, Ap. 12",
      "city": "București",
      "county": "București",
      "sector": "Sectorul 3",
      "postalCode": "030167",
      "country": "România"
    },
    "IBAN": "RO49AAAA1B31007593840000",
    "contactEmails": ["contabilitate@digitalsolutions.ro", "manager@digitalsolutions.ro"],
    "contact": "Ion Popescu",
    "phone": "+40721234567",
    "bank": "Banca Transilvania"
  }
}
```

### GET /api/clients - List Clients

Retrieve a paginated list of clients with optional text search.

**Query Parameters**:

| Parameter | Type | Description |
|---|---|---|
| `page` | integer | Page number (default: 1) |
| `limit` | integer | Items per page (default: 20, max: 100) |
| `search` | string | Search by name, email, or registration number (max 200 chars) |

**Example - Search by name**:
```bash
curl -X GET "https://app.billyou.ro/api/clients?search=Digital&page=1&limit=10" \
  -H "X-API-Key: bk_user_your_key"
```

**Response** (`200 OK`) - `data` is the array of clients; pagination lives in top-level `meta`:
```json
{
  "success": true,
  "data": [
    {
      "_id": "60f7b1b9c9e7b4a1e8d1c2b4",
      "name": "SC Digital Solutions SRL",
      "taxId": "RO12345678",
      "tradeRegistryNumber": "J40/1234/2020",
      "address": "Bulevardul Unirii nr. 45, Bl. A3, Sc. 2, Et. 4, Ap. 12",
      "city": "București",
      "county": "București",
      "sector": "Sectorul 3",
      "postalCode": "030167",
      "country": "România",
      "IBAN": "RO49AAAA1B31007593840000",
      "contactEmails": ["contabilitate@digitalsolutions.ro"],
      "contact": "Ion Popescu",
      "phone": "+40721234567",
      "bank": "Banca Transilvania"
    }
  ],
  "meta": {
    "total": 1,
    "page": 1,
    "limit": 10
  }
}
```

Note: list items use the flat storage shape (`address` is the street string). Fetch a single client for the nested `address` object.

### GET /api/clients/:id - Get Client

Retrieve a specific client by ID.

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

**Response** (`200 OK`):
```json
{
  "success": true,
  "data": {
    "_id": "60f7b1b9c9e7b4a1e8d1c2b4",
    "clientId": "60f7b1b9c9e7b4a1e8d1c2b4",
    "name": "SC Digital Solutions SRL",
    "taxId": "RO12345678",
    "tradeRegistryNumber": "J40/1234/2020",
    "address": {
      "street": "Bulevardul Unirii nr. 45, Bl. A3, Sc. 2, Et. 4, Ap. 12",
      "city": "București",
      "county": "București",
      "sector": "Sectorul 3",
      "postalCode": "030167",
      "country": "România"
    },
    "IBAN": "RO49AAAA1B31007593840000",
    "contactEmails": ["contabilitate@digitalsolutions.ro", "manager@digitalsolutions.ro"],
    "contact": "Ion Popescu",
    "phone": "+40721234567",
    "bank": "Banca Transilvania",
    "createdAt": "2025-01-10T08:00:00.000Z",
    "updatedAt": "2025-01-10T08:00:00.000Z"
  }
}
```

### PUT /api/clients/:id - Update Client

Update an existing client. This is a **true partial update**: all fields are optional and only provided fields are changed. Returns `404 CLIENT_NOT_FOUND` if the client does not exist.

**Request Body**: Same fields as Create Client, but all are optional. The address is a **nested `address` object**, exactly like the create endpoint (not flat fields).

| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | No | Business name |
| `taxId` | string | No | Tax ID |
| `tradeRegistryNumber` | string | No | Registry number |
| `address` | object | No | Nested address object (partial - send only the parts you change) |
| `address.street` | string | No | Street address |
| `address.city` | string | No | City |
| `address.county` | string | No | County |
| `address.postalCode` | string | No | Postal code |
| `address.sector` | string | No | Sector (required if the update sets city to București) |
| `address.country` | string | No | Country |
| `IBAN` | string | No | IBAN |
| `contactEmails` | string[] | No | Email addresses |
| `contact` | string | No | Contact person |
| `phone` | string | No | Phone |
| `bank` | string | No | Bank name |
| `hasSelfBillingContract` | boolean | No | Self-billing contract flag |

**Note**: If the update sets `address.city` to București without a valid `address.sector`, the request fails with `400 MISSING_BUCHAREST_SECTOR` (see the sector section above).

**Example - Update contact info**:
```bash
curl -X PUT https://app.billyou.ro/api/clients/60f7b1b9c9e7b4a1e8d1c2b4 \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "phone": "+40740987654",
    "contactEmails": ["new-contact@digitalsolutions.ro"],
    "IBAN": "RO12BRDE445SV00012345",
    "bank": "BRD Groupe Societe Generale"
  }'
```

**Example - Move the client to a București address**:
```bash
curl -X PUT https://app.billyou.ro/api/clients/60f7b1b9c9e7b4a1e8d1c2b4 \
  -H "X-API-Key: bk_user_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "address": {
      "street": "Calea Dorobanti nr. 15",
      "city": "București",
      "county": "București",
      "sector": "Sectorul 1",
      "postalCode": "010551",
      "country": "România"
    }
  }'
```

**Response** (`200 OK`) - returns the updated client (same shape as GET /api/clients/:id).

**Error** (`404 Not Found`):
```json
{
  "success": false,
  "errorCode": "CLIENT_NOT_FOUND",
  "message": "Client not found."
}
```

### DELETE /api/clients/:id - Delete Client

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

```bash
curl -X DELETE https://app.billyou.ro/api/clients/60f7b1b9c9e7b4a1e8d1c2b4 \
  -H "X-API-Key: bk_user_your_key"
```

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

**Error** (`400 Bad Request`) - Client has invoices:
```json
{
  "success": false,
  "errorCode": "CLIENT_HAS_INVOICES",
  "message": "Cannot delete client with existing invoices. Delete or cancel all invoices first."
}
```

## Romanian Address Format

Romanian addresses typically follow this structure:

```
Strada/Bulevardul [Name] nr. [Number], Bl. [Block], Sc. [Staircase], Et. [Floor], Ap. [Apartment]
City, County PostalCode
Romania
```

**Example**:
```
Bulevardul Unirii nr. 45, Bl. A3, Sc. 2, Et. 4, Ap. 12
București, Sectorul 3, 030167
România
```

**Bucharest specifics**: Bucharest is divided into 6 sectors (1-6). When the city is București, the `address.sector` field is **required** (ANAF e-Factura rule BR-RO-100) - see the dedicated section above. Accepted formats include `"Sectorul 3"`, `"Sector 3"`, and `"3"`.

**County codes**: Romania has 41 counties (judete) plus Bucharest municipality. Common ones:
- `București` (Bucharest - capital)
- `Cluj` (Cluj-Napoca)
- `Timiș` (Timisoara)
- `Iași` (Iasi)
- `Constanța` (Constanta)
- `Brașov` (Brasov)

## Romanian IBAN Format

Romanian IBANs follow the format: `RO` + 2 check digits + 4 letter bank code + 16 alphanumeric characters.

**Pattern**: `RO[0-9]{2}[A-Z]{4}[A-Z0-9]{16}`

**Examples**:
- `RO49AAAA1B31007593840000` - Standard format
- `RO12BRDE445SV00012345` - BRD bank
- `RO66BTRL00000000012345` - Banca Transilvania

## Common Workflows

### Create Client and Invoice

```typescript
// 1. Create the client
const client = await billyouRequest("POST", "/clients", {
  name: "SC Logistica Express SRL",
  taxId: "RO87654321",
  tradeRegistryNumber: "J12/5678/2023",
  address: {
    street: "Calea Victoriei nr. 100",
    city: "București",
    county: "București",
    sector: "Sectorul 1", // required: city is București (ANAF BR-RO-100)
    postalCode: "010093",
    country: "România",
  },
  contactEmails: ["facturi@logistica-express.ro"],
  IBAN: "RO49AAAA1B31007593840000",
  bank: "ING Bank",
});

// 2. Create an invoice for this client
const invoice = await billyouRequest("POST", "/invoices", {
  clientId: client.data._id,
  seriesId: "507f1f77bcf86cd799439011",
  issueDate: "2025-03-15",
  dueDate: "2025-04-14",
  services: [
    {
      description: "Transport marfa Bucuresti - Cluj",
      quantity: 5,
      unitPrice: 800.00,
      unitOfMeasure: "curse",
      vatRate: 21,
    },
  ],
  language: "ro",
});
```

### Search and Update Client

```typescript
// Search for clients matching "Digital"
const results = await billyouRequest("GET", "/clients?search=Digital");
const client = results.data[0]; // data is the array; pagination is in results.meta

// Update their banking information (partial update - nested address untouched)
await billyouRequest("PUT", `/clients/${client._id}`, {
  IBAN: "RO66BTRL00000000054321",
  bank: "Banca Transilvania",
});
```

## Error Codes

| Code | HTTP | Description |
|---|---|---|
| `VALIDATION_ERROR` | 400 | Invalid request body (missing required fields, invalid format, unknown fields) |
| `MISSING_BUCHAREST_SECTOR` | 400 | București address without a valid sector 1-6 (ANAF BR-RO-100) |
| `CLIENT_HAS_INVOICES` | 400 | Cannot delete client with existing invoices |
| `UNAUTHORIZED` | 401 | API key is invalid or missing |
| `CLIENT_NOT_FOUND` | 404 | Client not found |
| `CLIENT_DUPLICATE_TAX_ID` | 409 | A client with this tax ID already exists in your organization |
