> ## Documentation Index
> Fetch the complete documentation index at: https://docs.contazen.ro/llms.txt
> Use this file to discover all available pages before exploring further.

# AI-categorize expenses

> Sweep every uncategorized expense in the firm and assign a category from the existing list using AI classification.

## When to use

After bulk-importing expenses (OCR, supplier sync, e-Factura SPV) the `category_id` is often `null`. This endpoint sweeps every such row and assigns a category from the firm's existing list — system defaults plus custom categories, merged. Existing categorizations are never overwritten.

Call repeatedly until `remaining = 0`. Each call processes up to `cap` expenses (a server-side constant returned in the response), so a large backlog can be drained in controlled passes rather than a single long-running request.

## Permissions

Requires `write` permission on expenses.

## Request

<ParamField body="max" type="integer">
  Optional cap on the number of expenses to process this call. The server enforces its own ceiling (`BATCH_MAX_PER_CALL`), so very large values are clamped silently. Omit for "process up to the server cap."
</ParamField>

## Response

```json theme={null}
{
  "data": {
    "processed":   50,
    "categorized": 47,
    "skipped":     2,
    "errors":      1,
    "remaining":   1242,
    "batch_size":  10,
    "cap":         50
  }
}
```

| Field         | Meaning                                                                                           |
| ------------- | ------------------------------------------------------------------------------------------------- |
| `processed`   | Expenses inspected this call.                                                                     |
| `categorized` | Expenses that received a `category_id`.                                                           |
| `skipped`     | Classifier declined to assign a category (low confidence or no obvious match in the firm's list). |
| `errors`      | Per-row failures — logged server-side, retryable on next call.                                    |
| `remaining`   | Uncategorized expenses still queued. **Stop when this hits 0.**                                   |
| `batch_size`  | Expenses per classifier call (informational).                                                     |
| `cap`         | Hard ceiling per invocation (informational).                                                      |

## Driver pattern

```js theme={null}
async function categorizeAll(client) {
  while (true) {
    const { data } = await client.post('/expenses/ai-categorize-batch');
    if (data.remaining === 0) return;
    // Optional: brief pause between passes.
    await new Promise(r => setTimeout(r, 500));
  }
}
```

## Errors

* **401** — missing / invalid bearer token
* **403** — API key lacks `write` permission on expenses
* **502 `ai_unavailable`** — classifier call failed; safe to retry
* **503 `ai_not_configured`** — AI categorization is not enabled on this deployment


## OpenAPI

````yaml POST /expenses/ai-categorize-batch
openapi: 3.1.0
info:
  title: Contazen API
  version: 1.2.0
  description: >
    Build powerful integrations with the Contazen invoicing platform. The
    Contazen API is organized around REST, 

    has predictable resource-oriented URLs, accepts JSON request bodies, returns
    JSON-encoded responses, 

    and uses standard HTTP response codes, authentication, and verbs.


    ## Authentication

    The API uses Bearer token authentication. Include your API key in the
    Authorization header.


    ### Getting your API Key

    1. Log in to your Contazen account

    2. Navigate to Settings > API

    3. Generate or copy your API key (starts with `sk_live_` for production or
    `sk_test_` for testing)


    ### Using the API Key

    Include your API key in the Authorization header:

    ```

    Authorization: Bearer sk_live_YOUR_API_KEY

    ```


    ### Example Request with cURL

    ```bash

    curl --request GET \
      --url https://api.contazen.ro/v1/clients \
      --header 'Authorization: Bearer sk_live_YOUR_API_KEY' \
      --header 'Accept: application/json'
    ```


    ## Rate Limiting

    - 1000 requests per hour per API key

    - 100 create operations per minute per API key


    Rate limit information is included in response headers:

    - `X-RateLimit-Limit`: Maximum requests allowed

    - `X-RateLimit-Remaining`: Requests remaining

    - `X-RateLimit-Reset`: Reset time (Unix timestamp)


    ## Pagination

    All list endpoints return paginated results with the following format:

    ```json

    {
      "success": true,
      "data": {
        "object": "list",
        "data": [...],
        "has_more": true,
        "total": 245,
        "page": 1,
        "per_page": 50,
        "total_pages": 5
      },
      "meta": {
        "version": "v1",
        "request_id": "req_1a2b3c4d",
        "response_time": "23.45ms"
      }
    }

    ```


    ## Multi-Work-Point Access

    API keys belong to a specific work point but can access data from all work
    points

    within the same parent company.


    ## Error Handling

    The API uses conventional HTTP response codes to indicate success or
    failure. 

    In general: 2xx codes indicate success, 4xx codes indicate an error due to
    the 

    information provided, and 5xx codes indicate an error with Contazen's
    servers.


    ## Expanding Nested Objects

    Many endpoints support the `expand` parameter to include related objects in
    the response.

    This follows the Stripe API pattern. For example:

    - `expand[]=lines` - Include invoice line items

    - `expand[]=payments` - Include payment records

    - `expand[]=client` - Include full client object


    ## Localization

    The API supports multiple languages through:

    - `locale` query parameter (en, ro)

    - `Accept-Language` header

    - Default: English
  contact:
    name: Contazen Support
    email: support@contazen.ro
    url: https://contazen.ro
  license:
    name: Proprietary
    url: https://www.contazen.ro/termeni-si-conditii-de-utilizare/
servers:
  - url: https://api.contazen.ro/v1
    description: Production API server
security:
  - bearerAuth: []
tags:
  - name: Authentication
    description: API authentication and test endpoints
  - name: Clients
    description: Manage your customers (B2B and B2C)
  - name: Invoices
    description: Create and manage invoices, proformas, and receipts
  - name: Products
    description: Manage your product and service catalog
  - name: Expenses
    description: Track and manage business expenses
  - name: Expense Categories
    description: Organize expenses with categories
  - name: Suppliers
    description: Manage expense suppliers and vendors
  - name: Settings
    description: API settings and configuration
  - name: Payments
    description: Payments received against invoices
  - name: Receipts
    description: Cash receipts (chitanțe) — standalone or paired with an invoice
  - name: Company Lookup
    description: Romanian company lookup (ANAF / VIES)
  - name: Invoice Series
    description: Manage invoice numbering series
  - name: Bank Accounts
    description: Manage IBAN bank accounts
  - name: E-Factura
    description: Romanian e-invoicing status and configuration
  - name: Supplier Bills
    description: Supplier invoices imported from the ANAF SPV inbox
  - name: VAT Rates
    description: Firm-scoped custom VAT rates on top of the Romanian catalog
  - name: Currencies
    description: Currencies enabled for the firm's bill templates
  - name: Languages
    description: Languages enabled for the firm's bill templates
  - name: Conta
    description: |
      Public ANAF data for the firm's CUI: fiscal profile (TVA scope, RTVAI,
      split TVA, status, e-Factura registration, CAEN) and annual balance
      sheets (cifra de afaceri, profit, capitaluri, datorii, salariați).

      Powered by the public ANAF webservices (no OAuth required for these
      endpoints). The data is cached locally and refreshed on demand via
      the `/sync` actions.
paths:
  /expenses/ai-categorize-batch:
    post:
      tags:
        - Expenses
      summary: AI-categorize uncategorized expenses
      description: |
        Sweep every uncategorized expense in the firm and assign a category
        from the firm's existing list (system + custom). Expenses are
        batched server-side (`batch_size` per classifier call) and the run
        caps at `cap` total expenses per invocation, so a large backlog can
        be drained in controlled passes — call repeatedly until
        `remaining = 0`.

        The endpoint is idempotent: only expenses with `category_id IS NULL`
        are touched, so re-running picks up newly created uncategorized
        rows without re-classifying old ones.

        Returns `503 ai_not_configured` on deployments where AI
        categorization is not enabled.
      operationId: aiCategorizeExpensesBatch
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                max:
                  type: integer
                  description: |
                    Optional override for the per-call cap. The server still
                    enforces its own `BATCH_MAX_PER_CALL` ceiling, so very
                    large values are silently clamped.
      responses:
        '200':
          description: Batch run summary
          content:
            application/json:
              schema:
                type: object
                properties:
                  processed:
                    type: integer
                    description: Expenses inspected this call.
                  categorized:
                    type: integer
                    description: Expenses that received a category.
                  skipped:
                    type: integer
                    description: >-
                      Classifier declined to assign a category (low confidence
                      or no match).
                  errors:
                    type: integer
                    description: Per-row failures (logged server-side).
                  remaining:
                    type: integer
                    description: >-
                      Uncategorized expenses still in the queue. Call again
                      until 0.
                  batch_size:
                    type: integer
                    description: Expenses per classifier call (server constant).
                  cap:
                    type: integer
                    description: Hard ceiling per invocation (server constant).
        '502':
          description: Classifier unavailable (transient — safe to retry)
        '503':
          description: AI categorization not enabled on this deployment
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Use your API key (sk_live_xxx or sk_test_xxx)

````