openapi: 3.1.0

# Project variables for API configuration
x-project-variables:
  baseUrl:
    default: https://api.contazen.ro/v1
    description: Base URL for API requests
    enum:
      - https://api.contazen.ro/v1
  apiKey:
    default: Bearer YOUR_API_KEY
    description: Authorization header with Bearer token
    example: Bearer sk_live_YOUR_API_KEY

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

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.

security:
  - bearerAuth: []

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Use your API key (sk_live_xxx or sk_test_xxx)
      
  schemas:
    SuccessResponse:
      type: object
      properties:
        success:
          type: boolean
          default: true
        data:
          type: object
        meta:
          $ref: '#/components/schemas/ResponseMeta'
          
    ErrorResponse:
      type: object
      required:
        - success
        - error
      properties:
        success:
          type: boolean
          default: false
        error:
          type: object
          required:
            - message
            - type
            - code
          properties:
            message:
              type: string
              description: Human-readable error message
            type:
              type: string
              enum:
                - api_error
                - authentication_error
                - invalid_request_error
                - rate_limit_error
                - permission_error
                - validation_error
            code:
              type: string
              description: Machine-readable error code
            param:
              type: string
              description: The parameter that caused the error
            doc_url:
              type: string
              format: uri
              description: URL to relevant documentation
        meta:
          $ref: '#/components/schemas/ResponseMeta'
          
    ResponseMeta:
      type: object
      properties:
        version:
          type: string
          default: v1
        request_id:
          type: string
          format: uuid
          description: Unique request identifier for debugging
        response_time:
          type: string
          example: "23.45ms"
          
    PaginationMeta:
      type: object
      properties:
        object:
          type: string
          default: list
        has_more:
          type: boolean
        total:
          type: integer
        page:
          type: integer
        per_page:
          type: integer
        total_pages:
          type: integer
          
    Client:
      type: object
      required:
        - id
        - object
        - name
      properties:
        id:
          type: string
          description: Unique identifier (CzUid)
          example: "cli_1a2b3c4d5e"
        object:
          type: string
          default: client
        name:
          type: string
          description: Client name
        email:
          type: string
          format: email
          nullable: true
        phone:
          type: string
          nullable: true
        cui:
          type: string
          description: Tax identification number (CIF/CUI)
          nullable: true
        cui_prefix:
          type: string
          description: Country prefix for CUI (e.g., RO)
          nullable: true
        rc:
          type: string
          description: Trade register number
          nullable: true
        client_type:
          type: string
          enum: [b2b, b2c]
          description: "`b2b` for companies, `b2c` for individuals"
        address:
          type: string
          nullable: true
        city:
          type: string
          nullable: true
        county:
          type: string
          nullable: true
        country:
          type: string
          nullable: true
        postal_code:
          type: string
          nullable: true
        iban:
          type: string
          nullable: true
        bank:
          type: string
          nullable: true
        contact_person:
          type: string
          nullable: true
        created_at:
          type: integer
          description: Unix timestamp
        updated_at:
          type: integer
          nullable: true
          description: Unix timestamp (currently always null)
        metadata:
          type: object
          description: |
            Aggregated counters. Shape depends on the endpoint:
            - **List** (`GET /clients`): `{ invoices_count, total_invoiced }` — pre-computed
              via the `with_totals` join so every list item has the numbers needed for the
              dashboard view.
            - **Detail / create / update** (`GET /clients/{id}`, `POST`, `PUT`):
              `{ invoices_count, unpaid_total }` — computed per request against snapshots.
          properties:
            invoices_count:
              type: integer
            total_invoiced:
              type: number
              description: Sum of fiscal invoices issued to this client (list view only).
            unpaid_total:
              type: number
              description: Remaining unpaid balance (detail view only).
        stats:
          type: object
          description: Present only on detailed responses (`GET /clients/{id}`, `POST`, `PUT`).
          properties:
            total_invoiced:
              type: number
            total_collected:
              type: number
            avg_payment_days:
              type: integer
              nullable: true
              description: Average days between issue and payment on paid invoices. `null` if no paid invoices.
            last_payment:
              type: object
              nullable: true
              properties:
                date:
                  type: integer
                  nullable: true
                  description: Unix timestamp
                amount: { type: number }
                currency: { type: string, nullable: true }
                bill_id: { type: string, nullable: true, description: Invoice CzUid }
                bill_number: { type: string, nullable: true }
            monthly_series:
              type: array
              description: Last 6 months of invoiced vs. collected amounts, oldest first.
              items:
                type: object
                properties:
                  label: { type: string, example: "Mar 2026" }
                  year: { type: integer }
                  month: { type: integer }
                  invoiced: { type: number }
                  collected: { type: number }

    ClientList:
      type: object
      allOf:
        - $ref: '#/components/schemas/PaginationMeta'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Client'
                
    ClientCreateRequest:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 255
        email:
          type: string
          format: email
        phone:
          type: string
        cui:
          type: string
          description: Tax identification number
        cui_prefix:
          type: string
        rc:
          type: string
          description: Trade register number
        address:
          type: string
        city:
          type: string
          description: For București, include the sector (e.g. "București, Sector 1").
        county:
          type: string
        country:
          type: string
          default: RO
        postal_code:
          type: string
        iban:
          type: string
        bank:
          type: string
          description: Bank name
        contact_person:
          type: string
          
    ClientUpdateRequest:
      type: object
      description: All fields optional — only provided fields are updated.
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 255
        email:
          type: string
          format: email
        phone:
          type: string
        cui:
          type: string
        cui_prefix:
          type: string
        rc:
          type: string
        address:
          type: string
        city:
          type: string
        county:
          type: string
        country:
          type: string
        postal_code:
          type: string
        iban:
          type: string
        bank:
          type: string
          description: Bank name
        contact_person:
          type: string

    Invoice:
      type: object
      required:
        - id
        - object
        - number
        - series
        - date
        - total
      properties:
        id:
          type: string
          description: Unique identifier (CzUid)
          example: "inv_1a2b3c4d5e"
        object:
          type: string
          default: invoice
        number:
          type: string
        series:
          type: string
        full_number:
          type: string
          description: Combined series and number
        date:
          type: string
          format: date
        due_date:
          type: string
          format: date
        client_id:
          type: string
        client:
          $ref: '#/components/schemas/Client'
        currency:
          type: string
          default: RON
        exchange_rate:
          type: number
          description: Exchange rate to RON if foreign currency
        subtotal:
          type: number
          description: Total without VAT
        vat_amount:
          type: number
          description: Total VAT amount
        total:
          type: number
          description: Total including VAT
        subtotal_ron:
          type: number
          description: Subtotal in RON (for foreign currency invoices)
        vat_amount_ron:
          type: number
          description: VAT amount in RON (for foreign currency invoices)
        total_ron:
          type: number
          description: Total in RON (for foreign currency invoices)
        items:
          type: array
          items:
            $ref: '#/components/schemas/InvoiceItem'
        payments:
          type: array
          items:
            $ref: '#/components/schemas/Payment'
        is_paid:
          type: boolean
          description: Payment status (excludes voided invoices)
        paid_at:
          type: string
          format: date
        is_void:
          type: boolean
        voided_at:
          type: string
          format: date-time
        void_reason:
          type: string
        is_draft:
          type: boolean
        is_storno:
          type: boolean
          description: True if this is a storno (reversal) invoice
        storno_for:
          type: string
          description: CzUid of the original invoice if this is a storno
        document_type:
          type: string
          enum:
            - fiscal
            - proforma
            - receipt
        payment_method:
          type: string
        notes:
          type: string
        observations:
          type: string
        efactura_enabled:
          type: boolean
          description: Whether e-Factura submission is enabled
        efactura_status:
          type: string
          enum: [pending, submitted, accepted, rejected, error]
        efactura_submission_id:
          type: string
        created_at:
          type: string
          format: date-time
        modified_at:
          type: string
          format: date-time
          
    InvoiceList:
      type: object
      allOf:
        - $ref: '#/components/schemas/PaginationMeta'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Invoice'
            totals:
              type: object
              description: Aggregated totals for all invoices matching the filters
              properties:
                subtotal:
                  type: number
                  format: float
                  example: 1380871.63
                  description: Total amount without VAT
                vat:
                  type: number
                  format: float
                  example: 192519.84
                  description: Total VAT amount
                total:
                  type: number
                  format: float
                  example: 1573391.47
                  description: Total amount including VAT
                paid:
                  type: number
                  format: float
                  example: 1450000.00
                  description: Total amount of paid invoices
                unpaid:
                  type: number
                  format: float
                  example: 123391.47
                  description: Total amount of unpaid invoices
                
    InvoiceItem:
      type: object
      required:
        - description
        - quantity
        - price
      properties:
        id:
          type: integer
          description: Line item ID
        product_id:
          type: string
          description: Product CzUid if linked to catalog
        description:
          type: string
        description_extended:
          type: string
          description: Extended description or notes
        quantity:
          type: number
        price:
          type: number
          description: Unit price without VAT
        vat_rate:
          type: number
          default: 19
          enum: [0, 5, 9, 11, 19, 21]
        vat_key:
          type: integer
          description: VAT key for special exemptions (auto-determined from vat_rate)
        unit:
          type: string
          default: buc
        ubl_um:
          type: string
          description: UBL unit of measure code for e-Factura
          default: H87
        ubl_nc:
          type: string
          description: Combined Nomenclature code for e-Factura
        ubl_cpv:
          type: string
          description: Common Procurement Vocabulary code for e-Factura
        subtotal:
          type: number
          description: Line total without VAT
        vat_amount:
          type: number
          description: Line VAT amount
        total:
          type: number
          description: Line total including VAT
        save_as_product:
          type: boolean
          description: Whether to save this item as a product in catalog
          
    Payment:
      type: object
      properties:
        id:
          type: string
          description: Unique payment identifier (CzUid)
        object:
          type: string
          example: payment
        amount:
          type: number
          description: Payment amount
        currency:
          type: string
        date:
          type: string
          format: date
          nullable: true
        type:
          type: string
          enum: [receipt, bank_order, card, cheque, promissory_note, other, fiscal_receipt]
        type_description:
          type: string
          description: Localized payment type description
        reference:
          type: string
          nullable: true
          description: Reference number
        invoice:
          type: object
          nullable: true
          properties:
            id:
              type: string
            number:
              type: string
            total:
              type: number
            currency:
              type: string
        receipt:
          type: object
          nullable: true
          description: |
            Linked chitanță document, when this payment was emitted via one.
            Mobile clients use `receipt.id` to deep-link to the receipt editor.
          properties:
            id:
              type: string
              description: Receipt CzUid
            number:
              type: string
              description: Formatted receipt number (e.g. "C-001")
        client:
          type: object
          nullable: true
          properties:
            id:
              type: string
            name:
              type: string
        created_at:
          type: integer
          description: Unix timestamp

    PaymentTotals:
      type: object
      description: |
        SQL-aggregated sums over the entire filtered set (not just the loaded
        page). Amounts are expressed in the firm's accounting currency.
      properties:
        total:
          type: number
          description: Sum of all matching payments
        numerar:
          type: number
          description: Sum of `receipt` (cash) payments
        transfer:
          type: number
          description: Sum of `bank_order` payments
        card:
          type: number
          description: Sum of `card` payments
        bon_fiscal:
          type: number
          description: Sum of `fiscal_receipt` payments
        other:
          type: number
          description: Sum of `other`, `cheque`, and `promissory_note` payments
        count:
          type: integer
          description: Number of payments matching the filter
        currency:
          type: string
          description: Firm accounting currency (ISO code)

    Receipt:
      type: object
      description: A chitanță (cash receipt) document.
      properties:
        id:
          type: string
          description: Receipt CzUid
        object:
          type: string
          example: receipt
        receipt_number:
          type: string
          description: Formatted number (e.g. "C-001")
        amount:
          type: number
        amount_without_vat:
          type: number
        amount_vat:
          type: number
        currency:
          type: string
        date:
          type: string
          format: date
          nullable: true
        observations:
          type: string
          nullable: true
        language:
          type: string
          nullable: true
        is_draft:
          type: boolean
        is_deleted:
          type: boolean
        exchange_rate:
          type: number
          nullable: true
          description: Currency exchange rate (only when `currency` differs from firm accounting currency)
        exchange_currency:
          type: string
          nullable: true
          description: Target currency the exchange rate converts to
        type:
          type: string
          enum: [receipt, bank_order, card, fiscal_receipt, other]
          description: |
            Payment method type. Only present on list rows. Standalone
            chitanțe (no linked invoice) default to `receipt` (numerar).
        client:
          type: object
          properties:
            id:
              type: string
              nullable: true
            name:
              type: string
        invoice:
          type: object
          nullable: true
          properties:
            id:
              type: string
            number:
              type: string
            total:
              type: number
            currency:
              type: string
            is_paid:
              type: boolean
        payment:
          type: object
          nullable: true
          description: |
            Linked FirmBillPayment row when the chitanță is paired with an
            invoice. Standalone chitanțe (no invoice) have `payment: null`.
          properties:
            id:
              type: string
            object:
              type: string
              example: payment
            amount:
              type: number
            amount_without_vat:
              type: number
            amount_vat:
              type: number
            currency:
              type: string
            date:
              type: string
              format: date
              nullable: true
            type:
              type: string
              enum: [receipt, bank_order, card, fiscal_receipt, other]
            type_description:
              type: string
            exchange_rate:
              type: number
              nullable: true
            exchange_currency:
              type: string
              nullable: true
            invoice:
              type: object
              nullable: true
              properties:
                id:
                  type: string
                number:
                  type: string
            client:
              type: object
              properties:
                id:
                  type: string
                  nullable: true
                name:
                  type: string
            created_at:
              type: integer
        created_at:
          type: integer
        updated_at:
          type: integer
          nullable: true

    ReceiptCreateRequest:
      type: object
      required:
        - client_id
        - amount
      description: |
        Create a chitanță. When `invoice_id` is supplied, a linked
        `FirmBillPayment` row is created and the invoice's paid state is
        recomputed. Standalone chitanțe (no invoice) default to type
        `receipt` (numerar).
      properties:
        client_id:
          type: string
          description: Client CzUid (also accepts `clientId`)
        invoice_id:
          type: string
          description: Optional invoice CzUid to pair this chitanță with
        amount:
          type: number
          description: Total amount
        currency:
          type: string
          default: RON
        payment_date:
          type: string
          description: Date in `YYYY-MM-DD` or `DD-MM-YYYY` (defaults to today)
        observations:
          type: string
          description: Free-text note. Falls back to "Încasare factură {nr}" or "Încasare" when omitted.
        type:
          type: string
          enum: [receipt, numerar, cash, bank_order, transfer, op, card, fiscal_receipt, bon_fiscal, other]
          default: receipt
          description: Payment method (alias-tolerant). Only used when `invoice_id` is set.
        language:
          type: string
          default: ro
        number_id:
          type: string
          description: Chitanță series CzUid. Defaults to firm's primary chitanță series.
        exchange_rate:
          type: number
          description: Required when `currency` differs from firm accounting currency.

    ReceiptUpdateRequest:
      type: object
      description: |
        All fields optional. Same shape as create; `client_id` may be omitted
        and the existing client is preserved.
      properties:
        client_id:
          type: string
        invoice_id:
          type: string
        amount:
          type: number
        currency:
          type: string
        payment_date:
          type: string
        observations:
          type: string
        type:
          type: string
        language:
          type: string
        exchange_rate:
          type: number

    InvoiceCreateRequest:
      type: object
      oneOf:
        - required: [client_id, items]
        - required: [client_data, items]
      properties:
        client_id:
          type: string
          description: Existing client CzUid (required if client_data not provided)
        client_data:
          type: object
          description: Inline client creation (required if client_id not provided)
          properties:
            type:
              type: string
              enum: [b2b, b2c]
              description: Client type - b2b for companies, b2c for individuals
            name:
              type: string
              required: true
            email:
              type: string
              format: email
            phone:
              type: string
            cui:
              type: string
              description: Tax ID (required for b2b)
            rc:
              type: string
              description: Trade register number
            address:
              type: string
            city:
              type: string
            county:
              type: string
            country:
              type: string
              default: RO
            postal_code:
              type: string
            iban:
              type: string
            bank:
              type: string
            contact_person:
              type: string
        series_id:
          type: string
          description: Invoice series CzUid
        reservation_token:
          type: string
          description: |
            Offline-mode only. Token returned by
            [`POST /invoice-series/{id}/reserve-numbers`](/api-reference/endpoints/invoice-series/reserve-numbers).
            When supplied, the server uses the reservation's pre-allocated
            number instead of calling `nextNumber()`, and flips the
            reservation to `consumed`. Must match the same `series_id` and
            belong to the caller's device. See [Offline Mode](/concepts/offline-mode).
        force_chronology:
          type: boolean
          default: true
          description: |
            Set to `false` to bypass the chronology check when syncing an
            offline draft dated before the last invoice on the series.
        date:
          type: string
          format: date
          description: Invoice date (defaults to today)
        due_date:
          type: string
          format: date
          description: Payment due date
        currency:
          type: string
          default: RON
        currency_rate:
          type: number
          description: Exchange rate to RON (required for foreign currency)
        document_type:
          type: string
          enum: [fiscal, proforma, receipt]
          default: fiscal
        is_draft:
          type: integer
          enum: [0, 1]
          default: 0
          description: 1 to save as draft without invoice number
        efactura_enabled:
          type: integer
          enum: [0, 1]
          default: 1
          description: Whether to submit to e-Factura (Romanian e-invoicing)
        spv_environment:
          type: string
          enum: [test, live]
          description: e-Factura environment (test for SPV testing)
        with_vat_inverted:
          type: integer
          enum: [0, 1]
          default: 0
          description: 1 for reverse charge (taxare inversă)
        payment_method:
          type: string
        payment_type:
          type: string
        payment_installments:
          type: integer
        send_email:
          type: boolean
          default: false
          description: Automatically send invoice by email after creation
        email_address:
          type: string
          format: email
          description: Override recipient email (uses client email if not specified)
        with_delegate:
          type: integer
          enum: [0, 1]
          description: Include delegate information
        delegate:
          type: object
          properties:
            delegate_name:
              type: string
            delegate_ci:
              type: string
            delegate_transport:
              type: string
            delegate_date:
              type: string
              format: date
            delegate_time:
              type: string
        info:
          type: string
          description: Additional invoice information
        observations:
          type: string
          description: Internal notes
        notes:
          type: string
          description: Customer-visible notes
        items:
          type: array
          minItems: 1
          items:
            type: object
            oneOf:
              - required: [description, quantity, price]
              - required: [product_czuid, quantity]
            properties:
              product_czuid:
                type: string
                description: Use existing product from catalog
              description:
                type: string
                description: Item description (required if not using product_czuid)
              description_extended:
                type: string
                description: Extended description
              quantity:
                type: number
                minimum: 0.01
              price:
                type: number
                description: Unit price (can be negative for discounts)
              vat_rate:
                type: number
                default: 19
                enum: [0, 5, 9, 11, 19, 21]
              vat_key:
                type: integer
                description: Override VAT key for special exemptions
              unit:
                type: string
                default: buc
              ubl_um:
                type: string
                description: UBL unit code for e-Factura
              ubl_nc:
                type: string
                description: Combined Nomenclature code
              ubl_cpv:
                type: string
                description: CPV code
              save_as_product:
                type: boolean
                default: false
                description: Save this item as a product in catalog
                
    Product:
      type: object
      required:
        - id
        - object
        - name
        - price
      properties:
        id:
          type: string
          description: Unique identifier (CzUid)
          example: "prod_1a2b3c4d5e"
        object:
          type: string
          default: product
        name:
          type: string
        description:
          type: string
        currency:
          type: string
          default: RON
        price:
          type: number
          description: Selling price without VAT
        purchase_price:
          type: number
          description: Purchase/cost price
        vat_rate:
          type: number
          default: 19
          enum: [0, 5, 9, 11, 19, 21]
        unit_of_measure:
          type: string
          default: buc
        ubl_um:
          type: string
          description: UBL unit of measure code
          default: H87
        ubl_nc:
          type: string
          description: UBL nomenclature code
        ubl_cpv:
          type: string
          description: CPV code
        type:
          type: string
          enum: [product, service]
          default: service
          description: |
            Distinguishes trackable goods from one-off services. `product`
            rows participate in stock accounting; `service` rows skip the
            stock columns even when present. Values outside the enum are
            normalized to `service` on read.
        is_service:
          type: boolean
          default: false
          description: Legacy flag kept for backwards compatibility. Prefer `type`.
        is_active:
          type: boolean
          default: true
        stock_quantity:
          type: number
          description: Current stock level
        stock_min:
          type: number
          description: Minimum stock alert level
        stock_max:
          type: number
          description: Maximum stock level
        created_at:
          type: string
          format: date-time
        modified_at:
          type: string
          format: date-time

    ProductList:
      type: object
      allOf:
        - $ref: '#/components/schemas/PaginationMeta'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Product'
                
    ProductCreateRequest:
      type: object
      required:
        - name
        - price
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 255
        description:
          type: string
        price:
          type: number
          minimum: 0
        purchase_price:
          type: number
          minimum: 0
        currency:
          type: string
          default: RON
        vat_rate:
          type: number
          default: 21
          enum: [0, 5, 9, 11, 19, 21]
        unit_of_measure:
          type: string
          default: buc
        ubl_um:
          type: string
        ubl_nc:
          type: string
        ubl_cpv:
          type: string
        type:
          type: string
          enum: [product, service]
          default: service
          description: See `Product.type`. Defaults to `service` when omitted.
        is_service:
          type: boolean
          default: false
          description: Legacy flag — prefer `type`.
        stock_quantity:
          type: number
        stock_min:
          type: number
        stock_max:
          type: number

    ProductUpdateRequest:
      type: object
      properties:
        name:
          type: string
        description:
          type: string
        price:
          type: number
          minimum: 0
        purchase_price:
          type: number
          minimum: 0
        currency:
          type: string
        vat_rate:
          type: number
          enum: [0, 5, 9, 11, 19, 21]
        unit_of_measure:
          type: string
        ubl_um:
          type: string
        ubl_nc:
          type: string
        ubl_cpv:
          type: string
        type:
          type: string
          enum: [product, service]
          description: See `Product.type`. Omit to keep the current value.
        is_service:
          type: boolean
          description: Legacy flag — prefer `type`.
        is_active:
          type: boolean
        stock_quantity:
          type: number
        stock_min:
          type: number
        stock_max:
          type: number

    Expense:
      type: object
      required:
        - id
        - reference
        - amount
        - date
        - due_date
        - status
      properties:
        id:
          type: string
          description: Unique identifier (CzUid)
          example: "exp_1a2b3c4d5e"
        reference:
          type: string
          description: Invoice/document reference number
        description:
          type: string
        amount:
          type: object
          properties:
            total:
              type: number
              example: 500.00
            without_vat:
              type: number
            vat:
              type: number
            currency:
              type: string
        account_amount:
          type: object
          description: Amounts in account currency (RON)
          properties:
            total:
              type: number
            without_vat:
              type: number
            vat:
              type: number
            currency:
              type: string
              default: RON
        vat_percent:
          type: integer
          enum: [0, 5, 9, 11, 19, 21]
        with_vat:
          type: boolean
          description: Whether amount includes VAT
        date:
          type: string
          format: date
        due_date:
          type: string
          format: date
        paid_date:
          type: string
          format: date
          nullable: true
        is_paid:
          type: boolean
        payment_type:
          type: object
          nullable: true
          properties:
            id:
              type: integer
            name:
              type: string
        status:
          type: string
          enum: [paid, unpaid, overdue, registered]
        supplier_id:
          type: string
        supplier:
          $ref: '#/components/schemas/Supplier'
        category_id:
          type: integer
        category:
          $ref: '#/components/schemas/ExpenseCategory'
        user_id:
          type: integer
        user:
          type: object
          properties:
            id:
              type: integer
            name:
              type: string
        currency_exchange:
          type: object
          nullable: true
          properties:
            from:
              type: string
            to:
              type: string
            rate:
              type: number
        attachment:
          type: object
          nullable: true
          description: Single attachment (stored in the 'image' field)
          properties:
            url:
              type: string
            filename:
              type: string
            type:
              type: string
              enum: [pdf, image]
            size:
              type: integer
        efactura:
          type: object
          nullable: true
          description: |
            Populated when the expense was imported from the ANAF e-Factura SPV
            inbox. `null` for manually created expenses.
          properties:
            supplier_invoice_id:
              type: string
            invoice_number:
              type: string
              nullable: true
            anaf_message_id:
              type: string
              nullable: true
            xml_available:
              type: boolean
            pdf_available:
              type: boolean
            pdf_url:
              type: string
              nullable: true
              description: Bearer-authenticated URL that streams the e-Factura PDF; regenerated on demand when missing
        items:
          type: array
          description: |
            Line rows for the expense. Always at least one entry — legacy flat
            expenses get a single synthesized line built from the header totals
            so API consumers can render a uniform table. Send `items` on
            create/update to persist real multi-line rows.
          items:
            $ref: '#/components/schemas/ExpenseLine'
        vat_breakdown:
          type: array
          nullable: true
          description: |
            Per-rate VAT tranches when the receipt mixes two or more rates.
            `null` for single-rate expenses.
          items:
            $ref: '#/components/schemas/ExpenseVatBreakdownEntry'
        category_source:
          type: string
          nullable: true
          enum: [ai, supplier, manual]
          description: |
            How the category was assigned. `null` on uncategorized expenses
            or legacy rows where provenance wasn't recorded.
        category_confidence:
          type: number
          nullable: true
          minimum: 0
          maximum: 1
          description: Auto-classifier confidence when category_source is 'ai'.
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time

    ExpenseLine:
      type: object
      required:
        - id
        - line_index
        - name
        - quantity
        - unit_price
        - vat_rate
        - amount_wvat
        - amount_vat
        - amount
      properties:
        id:
          type: integer
          description: Line row ID. `0` for synthesized legacy lines.
        line_index:
          type: integer
          description: Zero-based position within the expense.
        name:
          type: string
        description:
          type: string
          nullable: true
        quantity:
          type: number
          description: Supports fractional quantities (e.g. 0.5 kg).
        unit_code:
          type: string
          nullable: true
          description: Optional UN/ECE unit code (e.g. H87, KGM).
        unit_price:
          type: number
          description: Net unit price (excluding VAT). Negative values represent discount rows (e.g. bon fiscal `DISCOUNT 4,40-A`); the sign is preserved through net/VAT/gross.
        vat_rate:
          type: integer
          enum: [0, 5, 9, 11, 19, 21]
        amount_wvat:
          type: number
          description: Line net, 2dp, `round(quantity * unit_price, 2)`.
        amount_vat:
          type: number
          description: Line VAT, 2dp, `round(amount_wvat * vat_rate / 100, 2)`.
        amount:
          type: number
          description: Line gross, 2dp, `amount_wvat + amount_vat`.
        category_id:
          type: string
          nullable: true
          description: Optional per-line category override (falls back to expense-level category).
        product_id:
          type: string
          nullable: true
          description: Optional link to a product in the firm's catalog.

    ExpenseVatBreakdownEntry:
      type: object
      required:
        - rate
        - vat_amount
      properties:
        rate:
          type: integer
          enum: [0, 5, 9, 11, 19, 21]
        net:
          type: number
          nullable: true
          description: Sum of line nets at this rate (2dp).
        vat_amount:
          type: number
          description: Sum of line VATs at this rate (2dp).
        gross:
          type: number
          nullable: true
          description: Sum of line gross values at this rate (2dp).

    OcrReceiptPayload:
      type: object
      description: |
        Normalized prefill returned by POST /expenses/ocr-extract. Map to
        a Create Expense body — see the OCR endpoint guide for the full
        translation table.
      properties:
        tempFileToken:
          type: string
          description: Opaque 15-min token for the staged image; pass through to attachments.
        supplier:
          type: object
          properties:
            id:              { type: string, nullable: true }
            name:            { type: string }
            cui:             { type: string, nullable: true }
            matchedExisting: { type: boolean }
        category:
          type: object
          properties:
            id:   { type: string, nullable: true }
            name: { type: string, nullable: true }
        date:        { type: string, format: date }
        dueDate:     { type: string, nullable: true }
        currency:    { type: string }
        amount:      { type: number, description: Net subtotal (excluding VAT). }
        vatRate:     { type: number, description: Dominant VAT rate. }
        vatAmount:   { type: number, description: Total VAT across all rate tranches. }
        vatMode:
          type: string
          enum: [flat, mix]
          description: |
            "flat" = single rate; send `vat = <number>` on POST.
            "mix"  = two or more non-zero rate tranches; send `vat = "mix"`
                     + `amount_vat_manual = vatAmount` on POST.
        total:        { type: number, description: Gross total printed on the receipt. }
        vatIncluded:  { type: boolean }
        vatBreakdown:
          type: array
          nullable: true
          items:
            type: object
            properties:
              rate:      { type: number }
              net:       { type: number, nullable: true }
              gross:     { type: number, nullable: true }
              vatAmount: { type: number }
        paymentMethod:
          type: string
          nullable: true
          enum: [cash, card, transfer, other, null]
          description: |
            Inferred payment method. Map to `payment_type` on POST:
            cash→1, card→4, transfer→3, other/null→caller decides.
        docNumber:    { type: string, nullable: true }
        description:  { type: string, nullable: true }
        items:
          type: array
          description: |
            Optional. May be absent depending on document quality and
            structure. Clients that ignore this field still get correct
            totals via the aggregate fields.
          items:
            type: object
            properties:
              name:       { type: string }
              quantity:   { type: number }
              unit_price: { type: number, description: NET (ex-VAT). Negative on discount rows (e.g. bon fiscal `DISCOUNT 4,40-A`). }
              vat_rate:   { type: number }
        warnings:
          type: array
          description: Pre-localized Romanian strings safe to surface in the form alert.
          items: { type: string }

    ExpenseLineInput:
      type: object
      required:
        - name
        - quantity
        - unit_price
        - vat_rate
      properties:
        name:
          type: string
        quantity:
          type: number
          minimum: 0.0001
        unit_price:
          type: number
          description: Net unit price (excluding VAT). Negative values are accepted for discount rows (e.g. bon fiscal `DISCOUNT 4,40-A`).
        vat_rate:
          type: integer
          enum: [0, 5, 9, 11, 19, 21]
        description:
          type: string
          nullable: true
        unit_code:
          type: string
          nullable: true
        category_id:
          type: string
          nullable: true
        product_id:
          type: string
          nullable: true

    ExpenseList:
      type: object
      allOf:
        - $ref: '#/components/schemas/PaginationMeta'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Expense'
            totals:
              type: object
              description: Aggregated totals for all expenses matching the filters
              properties:
                subtotal:
                  type: number
                  format: float
                  description: Total amount without VAT
                vat:
                  type: number
                  format: float
                  description: Total VAT amount
                total:
                  type: number
                  format: float
                  description: Total amount including VAT
                paid:
                  type: number
                  format: float
                  description: Total amount of paid expenses
                unpaid:
                  type: number
                  format: float
                  description: Total amount of unpaid expenses
            count:
              type: integer
              
    ExpenseCreateRequest:
      type: object
      required:
        - date
      description: |
        Either `supplier_id` or `supplier_data` must be provided. Either
        (`amount` + `vat`) or `items[]` must be provided — when `items` is
        sent the header `amount`/`vat` request fields are ignored and the
        server derives them from the lines.
      properties:
        supplier_id:
          type: string
          description: Supplier CzUid. Omit when sending `supplier_data` to auto-create.
        supplier_data:
          type: object
          description: |
            Auto-create a supplier when `supplier_id` is missing. If a
            supplier with the same CUI (or name when CUI is missing) already
            exists on the firm, it is reused instead of creating a duplicate.
          required:
            - name
          properties:
            name:
              type: string
            cui:
              type: string
              nullable: true
        amount:
          type: number
          minimum: 0.01
          description: Amount (positive number). Required on the flat path; ignored when `items` is sent.
        vat:
          oneOf:
            - type: integer
              enum: [0, 5, 9, 11, 19, 21]
            - type: string
              enum: ["mix"]
          description: |
            VAT percentage. Either a numeric percent (0/5/9/11/19/21) or the
            string "mix" for multi-rate receipts where the caller supplies
            the total VAT manually via `amount_vat_manual`. Required on the
            flat and mix paths; ignored when `items` is sent.
        amount_vat_manual:
          type: number
          minimum: 0
          description: |
            Total VAT amount in receipt currency. **Required when `vat = "mix"`**,
            ignored otherwise. Server stores `amount_wvat = amount`,
            `amount_vat = amount_vat_manual`, `amount_total = amount + amount_vat_manual`
            exactly — no rounding inference.
        date:
          type: string
          format: date
          description: Expense date (required, Y-m-d format)
        items:
          type: array
          description: |
            Line rows. When present and non-empty, the server persists real
            line records and derives `amount` / `vat` / `vat_breakdown` from
            them. See the Expense Lines concept for rounding rules.
          items:
            $ref: '#/components/schemas/ExpenseLineInput'
        vat_breakdown:
          type: array
          description: |
            Per-rate VAT tranches for multi-VAT receipts saved on the flat
            or mix paths. Supply two or more entries. On the mix path the
            server synthesizes one persisted line per rate group from the
            breakdown so reports keep accurate per-rate totals. Ignored when
            `items` is sent.
          items:
            $ref: '#/components/schemas/ExpenseVatBreakdownEntry'
        currency:
          type: string
          default: RON
          description: Currency code (optional, defaults to RON)
        due_date:
          type: string
          format: date
          description: Due date (optional, defaults to 30 days from today)
        paid_date:
          type: string
          format: date
          description: Payment date (optional, defaults to today if is_paid=true)
        payment_type:
          type: integer
          minimum: 1
          maximum: 7
          description: |
            Payment type ID 1-7 (optional, defaults to 1 if is_paid=true):
            1 = Cash
            2 = Bank transfer
            3 = Card
            4 = Check
            5 = Promissory note
            6 = Other
            7 = Compensation
        category_id:
          type: integer
          description: Category ID (optional, defaults to 0)
          nullable: true
        reference:
          type: string
          description: Reference number (optional)
        description:
          type: string
          description: Description (optional)
        with_vat:
          type: boolean
          default: false
          description: Whether amount includes VAT (optional, defaults to false)
        is_paid:
          type: boolean
          default: false
          description: Whether expense is paid (optional, defaults to false)
        with_currency_exchange:
          type: boolean
          default: false
          description: Whether to apply currency exchange (optional)
        currency_to:
          type: string
          description: Target currency (if with_currency_exchange)
        currency_rate:
          type: number
          description: Exchange rate (if with_currency_exchange)
          
    ExpenseUpdateRequest:
      type: object
      description: |
        All fields optional. Sending `items` REPLACES all existing lines —
        send the full desired set, not a diff. Omit `items` to leave lines
        untouched. To convert an itemized expense back to flat, send
        `items: []` alongside new `amount` + `vat`.
      properties:
        supplier_id:
          type: string
        category_id:
          type: integer
          nullable: true
        reference:
          type: string
        description:
          type: string
        amount:
          type: number
        with_vat:
          type: integer
          enum: [0, 1]
        vat:
          oneOf:
            - type: integer
              enum: [0, 5, 9, 11, 19, 21]
            - type: string
              enum: ["mix"]
          description: |
            VAT percentage. Either a numeric value or the string "mix" for
            multi-rate receipts. When set to "mix" the request must include
            `amount_vat_manual`.
        amount_vat_manual:
          type: number
          minimum: 0
          description: |
            Total VAT amount when `vat = "mix"`. Server stores
            `amount_wvat = amount`, `amount_vat = amount_vat_manual`,
            `amount_total = amount + amount_vat_manual`.
        currency:
          type: string
        date:
          type: string
          format: date
        due_date:
          type: string
          format: date
        is_paid:
          type: integer
          enum: [0, 1]
        paid_date:
          type: string
          format: date
        payment_type:
          type: integer
          minimum: 1
          maximum: 7
        with_currency_exchange:
          type: integer
          enum: [0, 1]
        currency_to:
          type: string
        currency_rate:
          type: number
        items:
          type: array
          description: |
            Replace all line rows. When present, the server re-derives
            `amount` / `vat` / `vat_breakdown` from the lines and ignores
            the corresponding header fields on the body. Empty array
            (`[]`) clears the lines.
          items:
            $ref: '#/components/schemas/ExpenseLineInput'
        vat_breakdown:
          type: array
          description: |
            Update the per-rate breakdown for flat-path multi-VAT receipts.
            Ignored when `items` is sent.
          items:
            $ref: '#/components/schemas/ExpenseVatBreakdownEntry'
          
    ExpenseCategory:
      type: object
      required:
        - id
        - name
        - type
      properties:
        id:
          type: integer
        name:
          type: string
        parent_id:
          type: integer
          nullable: true
        is_default:
          type: boolean
          description: Whether this is a system default category
        is_visible:
          type: boolean
        type:
          type: string
          enum: [system, custom]
        expense_count:
          type: integer
          description: Number of expenses in this category
        children:
          type: array
          items:
            $ref: '#/components/schemas/ExpenseCategory'
            
    ExpenseCategoryCreateRequest:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 100
        parent_id:
          type: integer
          default: 0
          description: Parent category ID (0 for root)
        is_visible:
          type: integer
          enum: [0, 1]
          default: 1
          
    ExpenseCategoryUpdateRequest:
      type: object
      properties:
        name:
          type: string
        parent_id:
          type: integer
        is_visible:
          type: integer
          enum: [0, 1]
            
    Supplier:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: string
          description: Unique identifier (CzUid)
          example: "sup_1a2b3c4d5e"
        name:
          type: string
        cui:
          type: string
          description: Tax identification number
        rc:
          type: string
          description: Company registration number
        cnp:
          type: string
          description: Personal identification number
        address:
          type: string
        city:
          type: string
        county:
          type: string
        country:
          type: string
        postal_code:
          type: string
        phone:
          type: string
        email:
          type: string
        iban:
          type: string
        bank:
          type: string
        contact_person:
          type: string
        contact_phone:
          type: string
        contact_email:
          type: string
        is_vat_payer:
          type: boolean
        statistics:
          type: object
          properties:
            expense_count:
              type: integer
            total_amount:
              type: number
            paid_amount:
              type: number
            unpaid_amount:
              type: number
        recent_expenses:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              reference:
                type: string
              amount:
                type: number
              currency:
                type: string
              date:
                type: string
                format: date
              is_paid:
                type: boolean
        metadata:
          type: object
          description: |
            Lightweight expense aggregates. Returned by `GET /suppliers` only
            when `with_totals=1` is supplied. Cheaper than `expand=statistics`
            since the totals come from a single inline subquery rather than
            a per-row N+1 follow-up. Amounts are expressed in the firm's
            accounting currency.
          properties:
            expense_count:
              type: integer
              description: Number of non-deleted expenses for this supplier
            total_expenses:
              type: number
              description: Sum of `account_amount_total` across all matching expenses
            unpaid_total:
              type: number
              description: Sum of `account_amount_total` across unpaid matching expenses
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time

    SupplierList:
      type: object
      allOf:
        - $ref: '#/components/schemas/PaginationMeta'
        - type: object
          properties:
            data:
              type: array
              items:
                $ref: '#/components/schemas/Supplier'
                
    SupplierCreateRequest:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 255
        cui:
          type: string
          description: Tax identification number
        rc:
          type: string
          description: Company registration number
        cnp:
          type: string
          description: Personal identification number
        address:
          type: string
        city:
          type: string
        county:
          type: string
        country:
          type: string
          default: RO
        postal_code:
          type: string
        phone:
          type: string
        email:
          type: string
          format: email
        iban:
          type: string
        bank:
          type: string
        contact_person:
          type: string
        contact_phone:
          type: string
        contact_email:
          type: string
          format: email
        is_vat_payer:
          type: boolean
          default: true
          
    SupplierUpdateRequest:
      type: object
      properties:
        name:
          type: string
        cui:
          type: string
        rc:
          type: string
        cnp:
          type: string
        address:
          type: string
        city:
          type: string
        county:
          type: string
        country:
          type: string
        postal_code:
          type: string
        phone:
          type: string
        email:
          type: string
        iban:
          type: string
        bank:
          type: string
        contact_person:
          type: string
        contact_phone:
          type: string
        contact_email:
          type: string
        is_vat_payer:
          type: boolean
          
    SupplierBillAmounts:
      type: object
      properties:
        tax_exclusive: { type: number, format: float, description: Subtotal without VAT }
        tax: { type: number, format: float, description: Total VAT amount }
        tax_inclusive: { type: number, format: float, description: Grand total }
        paid: { type: number, format: float, description: Amount already paid }
        unpaid: { type: number, format: float, description: tax_inclusive minus paid (can be negative for credit notes) }

    SupplierBillSupplierSummary:
      type: object
      properties:
        id: { type: string, nullable: true, description: Supplier CzUid (null when no FirmSupplier row exists) }
        name: { type: string, nullable: true }
        vat_id: { type: string, nullable: true }
        reg_com: { type: string, nullable: true }
        address: { type: string, nullable: true }
        email: { type: string, nullable: true }
        phone: { type: string, nullable: true }

    SupplierBill:
      type: object
      properties:
        id: { type: string, description: Supplier bill CzUid }
        object: { type: string, example: supplier_bill }
        invoice_number: { type: string }
        invoice_type_code: { type: string, enum: ['380', '381'] }
        invoice_type: { type: string, enum: [invoice, credit_note] }
        issue_date: { type: string, format: date }
        due_date: { type: string, format: date, nullable: true }
        currency: { type: string, example: RON }
        amounts: { $ref: '#/components/schemas/SupplierBillAmounts' }
        status: { type: string, enum: [unpaid, paid, partial] }
        payment_date: { type: string, format: date, nullable: true }
        payment_amount: { type: number, format: float, nullable: true }
        supplier: { $ref: '#/components/schemas/SupplierBillSupplierSummary' }
        supplier_id: { type: string, nullable: true, description: CzUid of the linked FirmSupplier (if any) }
        expense_id: { type: string, nullable: true, description: CzUid of the linked FirmExpense (if any) }
        client_id: { type: string, nullable: true, description: CzUid of the reciprocal FirmClient — populated when this firm has a client with the same CIF as the supplier }
        efactura_message_id: { type: integer, nullable: true, description: Local id of the FirmEfacturaMessage row (the SPV message that produced this bill) }
        efactura_pdf_url: { type: string, nullable: true, description: Direct URL to the PDF stream endpoint (null when there is no SPV XML) }
        order_reference: { type: string, nullable: true }
        note: { type: string, nullable: true }
        created_at: { type: integer, description: Unix timestamp }
        updated_at: { type: integer, description: Unix timestamp, nullable: true }
        expense:
          type: object
          nullable: true
          description: Present when expand contains `expense`.
        client:
          type: object
          nullable: true
          description: Present when expand contains `client` and a reciprocal client exists.
        efactura_message:
          type: object
          nullable: true
          description: Present when expand contains `efactura_message`.
          properties:
            id: { type: integer }
            message_id: { type: string }
            cif: { type: string, nullable: true }
            type: { type: string, nullable: true }
            creation_date: { type: string, format: date-time, nullable: true }
            environment: { type: string, enum: [test, live], nullable: true }
        lines:
          type: array
          description: Present when expand contains `lines`.
          items:
            type: object

    SupplierBillBalance:
      type: object
      description: Aggregate over the same supplier (matched by id, vat_id, or name).
      properties:
        unpaid_total: { type: number, format: float }
        unpaid_count: { type: integer }
        currency: { type: string }
        next_due:
          type: object
          nullable: true
          properties:
            id: { type: string }
            invoice_number: { type: string }
            due_date: { type: string, format: date, nullable: true }
            tax_inclusive: { type: number, format: float }

    SupplierBillCurrencyTotals:
      type: object
      properties:
        count: { type: integer }
        tax_exclusive: { type: number, format: float }
        tax: { type: number, format: float }
        tax_inclusive: { type: number, format: float }
        paid: { type: number, format: float }
        unpaid: { type: number, format: float }

    SupplierBillTotals:
      type: object
      description: Aggregate totals (global plus per-currency breakdown).
      properties:
        count: { type: integer }
        tax_exclusive: { type: number, format: float }
        tax: { type: number, format: float }
        tax_inclusive: { type: number, format: float }
        paid: { type: number, format: float }
        unpaid: { type: number, format: float }
        by_currency:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/SupplierBillCurrencyTotals'

    SupplierBillList:
      type: object
      allOf:
        - $ref: '#/components/schemas/PaginationMeta'
        - type: object
          properties:
            data:
              type: array
              items: { $ref: '#/components/schemas/SupplierBill' }
            totals:
              $ref: '#/components/schemas/SupplierBillTotals'

    SupplierBillMarkPaidRequest:
      type: object
      properties:
        payment_date:
          type: string
          format: date
          description: Defaults to today.
        payment_amount:
          type: number
          format: float
          minimum: 0
          description: |
            Defaults to the bill's `tax_inclusive` total. A value lower than
            the total marks the bill `partial`; zero marks it `unpaid`.

    SupplierBillSyncResult:
      type: object
      properties:
        synced: { type: integer, description: Total messages returned by ANAF for the chosen window }
        created: { type: integer, description: New FirmEfacturaMessage rows }
        updated: { type: integer, description: Existing rows touched }
        failed: { type: integer }
        xml_saved: { type: integer, description: XML files freshly downloaded to disk }
        invoices_imported: { type: integer, description: New FirmSupplierInvoice rows produced from XML }
        days_synced: { type: integer }
        environment: { type: string, enum: [test, live] }
        errors:
          type: array
          items: { type: string }

    Settings:
      type: object
      properties:
        api_version:
          type: string
          example: "v1"
        firm:
          type: object
          properties:
            id:
              type: string
            name:
              type: string
            cui:
              type: string
            address:
              type: string
            city:
              type: string
            country:
              type: string
        invoice_series:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              name:
                type: string
              prefix:
                type: string
              next_number:
                type: integer
              is_default:
                type: boolean
        e_factura:
          type: object
          properties:
            enabled:
              type: boolean
            oauth_configured:
              type: boolean
            environment:
              type: string
              enum: [test, live]
        bank_accounts:
          type: array
          items:
            type: object
            properties:
              iban:
                type: string
              bank:
                type: string
              currency:
                type: string
              is_default:
                type: boolean
        currencies:
          type: array
          items:
            type: string
        default_currency:
          type: string
        vat_rates:
          type: array
          items:
            type: integer
        payment_types:
          type: array
          items:
            type: object
            properties:
              id:
                type: integer
              name:
                type: string
        subscription:
          type: object
          properties:
            plan:
              type: string
            status:
              type: string
            expires_at:
              type: string
              format: date
        features:
          type: object
          properties:
            expenses:
              type: boolean
            efactura:
              type: boolean
            multi_currency:
              type: boolean
            api_access:
              type: boolean
        rate_limits:
          type: object
          properties:
            requests_per_hour:
              type: integer
            creates_per_minute:
              type: integer
            current_usage:
              type: integer
            reset_at:
              type: string
              format: date-time

    InvoiceSeries:
      type: object
      properties:
        id:
          type: string
          description: Unique series identifier (CzUid)
        object:
          type: string
          example: invoice_series
        name:
          type: string
          description: Series prefix/name
        document_type:
          type: string
          enum: [fiscal, proforma]
        description:
          type: string
          nullable: true
        start_number:
          type: integer
        next_number:
          type: integer
          description: Next available invoice number
        format:
          type: string
          description: Number format pattern
          example: "FACT-{year}-{number}"
        is_primary:
          type: boolean
        is_used:
          type: boolean
          description: Whether any documents have been issued with this series
        is_locked:
          type: boolean
          description: |
            True when this series is bound to a specific mobile device. While
            locked, only that device can emit invoices on the series (online
            or via pre-reserved numbers while offline). See
            [Offline Mode](/concepts/offline-mode).
        lock:
          $ref: '#/components/schemas/InvoiceSeriesLock'
          nullable: true
        year:
          type: integer
        created_at:
          type: integer
          description: Unix timestamp

    InvoiceSeriesLock:
      type: object
      description: Mobile-device binding metadata. `null` when the series is unlocked.
      properties:
        device_id:
          type: string
          description: Stable device identifier (persisted on the mobile app).
        session_id:
          type: integer
          nullable: true
          description: user_session.id that created the lock.
        user_id:
          type: integer
          nullable: true
        device_name:
          type: string
          nullable: true
        device_platform:
          type: string
          nullable: true
          description: ios, android, or web.
        locked_at:
          type: integer
          nullable: true
          description: Unix timestamp (seconds)

    NumberReservation:
      type: object
      description: Pre-allocated invoice number held for a mobile device.
      properties:
        object:
          type: string
          example: number_reservation
        token:
          type: string
          description: Opaque token — pass as `reservation_token` on POST /invoices.
        series_id:
          type: string
          nullable: true
          description: CzUid of the series the reservation belongs to.
        number:
          type: integer
          description: The pre-allocated `number_idx` within the series.
        status:
          type: string
          enum: [pending, consumed, released, expired]
        device_id:
          type: string
        reserved_at:
          type: integer
          nullable: true
        expires_at:
          type: integer
          nullable: true
        consumed_at:
          type: integer
          nullable: true
        client_local_uuid:
          type: string
          nullable: true

    BankAccount:
      type: object
      properties:
        id:
          type: string
          description: Unique bank account identifier (CzUid)
        object:
          type: string
          example: bank_account
        iban:
          type: string
        bank_name:
          type: string
        currency:
          type: string
        swift:
          type: string
          nullable: true
        bic:
          type: string
          nullable: true
        is_visible:
          type: boolean
          description: Whether shown on invoices
        created_at:
          type: integer
          description: Unix timestamp

    VatRate:
      type: object
      properties:
        id:
          type: string
          description: VAT rate CzUid
        percent:
          type: number
          example: 19
        description:
          type: string
          example: 19% - TVA
        is_used:
          type: boolean
          description: True if at least one bill row references this rate
        can_be_deleted:
          type: boolean
        is_custom:
          type: boolean
          description: Always true for rows returned in data (they are firm-scoped). Standard Romanian rates appear under `available`.

    Currency:
      type: object
      properties:
        id:
          type: string
          description: Currency CzUid
        code:
          type: string
          example: EUR
        description:
          type: string
          example: Euro
        is_used:
          type: boolean
        is_default:
          type: boolean
          description: True for RON

    Language:
      type: object
      properties:
        id:
          type: string
          description: Language CzUid
        code:
          type: string
          example: en
        description:
          type: string
          example: English
        is_default:
          type: boolean
          description: True for `ro`

    FiscalProfile:
      type: object
      description: |
        Snapshot of the public ANAF v9 PlatitorTVA record for the firm's CUI.
      properties:
        object:
          type: string
          enum: [fiscal_profile]
        id:
          type: string
          description: CzUid of the local cached record.
          example: "f8h2cKp9"
        subject_cui:
          type: string
          description: CUI looked up at ANAF (firm's own CUI in phase 1).
          example: "28171477"
        denumire:
          type: string
          example: "HAPPY PIXELS SRL"
        tva_status:
          type: boolean
          description: True if the firm is currently a registered TVA payer.
        tva_scope_start_date:
          type: string
          format: date
          nullable: true
          example: "2011-03-16"
        tva_scope_end_date:
          type: string
          format: date
          nullable: true
        rtvai:
          type: boolean
          description: TVA la încasare (cash-VAT) registration.
        split_tva:
          type: boolean
        inactiv:
          type: boolean
          description: ANAF inactive-state flag.
        inactiv_date:
          type: string
          format: date
          nullable: true
        efactura_registered:
          type: boolean
          description: Registered for the RO_e_Factura system.
        caen:
          type: integer
          nullable: true
          example: 6201
        caen_name:
          type: string
          nullable: true
        address_sediu_social:
          type: string
          nullable: true
        address_domiciliu_fiscal:
          type: string
          nullable: true
        last_synced_at:
          type: string
          format: date-time
          example: "2026-04-27 08:24:57"

    BalanceSheet:
      type: object
      description: |
        Annual financial statement for the firm, sourced from the public ANAF
        Bilanț webservice. Hot fields are best-effort denormalizations of the
        most useful indicators; the full per-indicator detail is available in
        the per-year `GET /accounting/balance-sheets/{year}` response.
      properties:
        object:
          type: string
          enum: [balance_sheet]
        id:
          type: string
          description: CzUid.
        subject_cui:
          type: string
        an:
          type: integer
          example: 2024
        denumire:
          type: string
          nullable: true
        caen:
          type: integer
          nullable: true
        caen_name:
          type: string
          nullable: true
        cifra_afaceri:
          type: number
          format: float
          nullable: true
          example: 781376.00
        venituri_total:
          type: number
          format: float
          nullable: true
        cheltuieli_total:
          type: number
          format: float
          nullable: true
        profit_brut:
          type: number
          format: float
          nullable: true
        pierdere_bruta:
          type: number
          format: float
          nullable: true
        profit_net:
          type: number
          format: float
          nullable: true
          example: 212401.00
        pierdere_neta:
          type: number
          format: float
          nullable: true
        capitaluri_proprii:
          type: number
          format: float
          nullable: true
        datorii_total:
          type: number
          format: float
          nullable: true
        active_imobilizate:
          type: number
          format: float
          nullable: true
        active_circulante:
          type: number
          format: float
          nullable: true
        active_total:
          type: number
          format: float
          nullable: true
          description: Computed as `active_imobilizate + active_circulante` when both present.
        nr_salariati:
          type: integer
          nullable: true
          example: 1
        synced_at:
          type: string
          format: date-time

    BalanceSheetIndicator:
      type: object
      description: One raw ANAF indicator as returned by the Bilanț webservice.
      properties:
        indicator:
          type: string
          description: ANAF code (e.g. `I7`, `I47`, `nr_med_sal`). Stable per OMFP form, may differ between forms.
          example: "I7"
        value:
          type: number
          example: 781376
        indicator_name:
          type: string
          description: Romanian human label (uppercase, no diacritics).
          example: "CIFRA DE AFACERI NETA"
        case:
          type: string
          description: SDK enum case name (e.g. `NET_TURNOVER`). Stable across years.
          example: "NET_TURNOVER"

    BalanceSheetDetail:
      allOf:
        - $ref: '#/components/schemas/BalanceSheet'
        - type: object
          properties:
            indicators:
              type: array
              description: Full per-indicator payload, in the order ANAF returned them.
              items:
                $ref: '#/components/schemas/BalanceSheetIndicator'

    BalanceSheetList:
      type: object
      properties:
        object:
          type: string
          enum: [list]
        data:
          type: array
          items:
            $ref: '#/components/schemas/BalanceSheet'
        count:
          type: integer

    BalanceSheetSyncEmpty:
      type: object
      description: Returned when the requested year is not yet published by ANAF.
      properties:
        object:
          type: string
          enum: [balance_sheet_sync]
        year:
          type: integer
        imported:
          type: integer
          example: 0
        message:
          type: string
          example: "Bilantul pentru 2025 nu este publicat de ANAF."

    BalanceSheetBackfillResult:
      type: object
      description: Stats returned by the backfill operation.
      properties:
        object:
          type: string
          enum: [balance_sheet_backfill]
        from_year:
          type: integer
          example: 2014
        to_year:
          type: integer
          example: 2024
        imported:
          type: integer
          description: Number of years imported (with data).
        empty:
          type: integer
          description: Number of years skipped because ANAF had no data yet.
        errors:
          type: object
          description: Map of `year → error message` for years that hit a hard error.
          additionalProperties:
            type: string

  responses:
    UnauthorizedError:
      description: API key is missing or invalid
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFoundError:
      description: The specified resource was not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    MethodNotAllowedError:
      description: Method not allowed
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    BadRequestError:
      description: Invalid or missing request parameters
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ValidationError:
      description: Request validation failed
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RateLimitError:
      description: Too many requests
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'

paths:
  # Root endpoint
  /:
    get:
      operationId: getApiInfo
      tags: [Authentication]
      summary: API information
      description: Returns basic API information and status
      security: []
      responses:
        '200':
          description: API information
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      name:
                        type: string
                        example: "Contazen API"
                      version:
                        type: string
                        example: "v1"
                      documentation:
                        type: string
                        format: uri
                      status:
                        type: string
                        example: "operational"
  
  # Test endpoints
  /test/public:
    get:
      operationId: testPublic
      tags: [Authentication]
      summary: Public test endpoint
      description: Test endpoint that doesn't require authentication
      security: []
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'
          
  /test/protected:
    get:
      operationId: testProtected
      tags: [Authentication]
      summary: Protected test endpoint
      description: Test endpoint that requires authentication
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /test/echo:
    post:
      operationId: testEcho
      tags: [Authentication]
      summary: Echo test endpoint
      description: Echoes back the request data for testing
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SuccessResponse'
                
  /test/rate-limit:
    get:
      operationId: testRateLimit
      tags: [Authentication]
      summary: Test rate limiting
      description: Returns current rate limit status for your API key
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      limit:
                        type: integer
                      remaining:
                        type: integer
                      reset_at:
                        type: string
                        format: date-time
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '429':
          $ref: '#/components/responses/RateLimitError'
          
  /test/error:
    get:
      operationId: testError
      tags: [Authentication]
      summary: Test error response
      description: Returns a test error for debugging error handling
      security: []
      parameters:
        - name: type
          in: query
          schema:
            type: string
            default: api_error
          description: Error type to return
        - name: code
          in: query
          schema:
            type: integer
            default: 400
          description: HTTP status code to return
      responses:
        '400':
          $ref: '#/components/responses/ValidationError'
        '500':
          description: Server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
          
  # Clients endpoints
  /clients:
    get:
      operationId: listClients
      tags: [Clients]
      summary: List all clients
      description: Retrieves a paginated list of clients for your firm
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
          description: Page number (1-indexed)
        - name: per_page
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
          description: Number of items per page
        - name: search
          in: query
          schema:
            type: string
          description: Search term for name, email, or CUI
        - name: client_type
          in: query
          schema:
            type: string
            enum: [b2b, b2c]
          description: Filter by client type (`b2b` = companies, `b2c` = individuals)
        - name: sort
          in: query
          schema:
            type: string
            enum: [name, created_at, total_invoiced, invoices_count]
          description: |
            Sort field. When omitted, results are ordered by aggregated
            `total_invoiced` DESC (the default surface for the client
            list).
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: asc
          description: Sort order (ignored when `sort` is omitted)
      responses:
        '200':
          description: |
            List of clients. Each item includes a `metadata` block with
            `invoices_count` and `total_invoiced` aggregated across the
            firm's fiscal invoices (snapshot-aware), so the list view can
            render totals without a follow-up call.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ClientList'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

    post:
      operationId: createClient
      tags: [Clients]
      summary: Create a client
      description: Creates a new client
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ClientCreateRequest'
      responses:
        '201':
          description: Client created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Client'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /clients/{id}:
    get:
      operationId: getClient
      tags: [Clients]
      summary: Retrieve a client
      description: Get a specific client by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Client CzUid (e.g., cli_1a2b3c4d5e)
      responses:
        '200':
          description: Client details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Client'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    put:
      operationId: updateClient
      tags: [Clients]
      summary: Update a client
      description: Updates an existing client
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Client CzUid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ClientUpdateRequest'
      responses:
        '200':
          description: Client updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Client'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    delete:
      operationId: deleteClient
      tags: [Clients]
      summary: Delete a client
      description: Deletes a client (soft delete, cannot delete if has associated invoices)
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Client CzUid
      responses:
        '200':
          description: Client deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '409':
          description: Cannot delete client with existing invoices
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  # Invoices endpoints
  /invoices:
    get:
      operationId: listInvoices
      tags: [Invoices]
      summary: List all invoices
      description: |
        Retrieves a paginated list of invoices with optional filters and expansion.
        
        ## Filtering
        Use query parameters to filter invoices by various criteria.
        
        ## Expanding Objects
        Use the `expand[]` parameter to include related objects:
        - `expand[]=lines` - Include invoice line items
        - `expand[]=payments` - Include payment records
        - `expand[]=client` - Include full client object
        - `expand[]=efactura` - Include e-Factura submission details
        
        ## Totals
        The response includes aggregated totals for all invoices matching your filters.
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
          description: Page number
        - name: per_page
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
          description: Items per page
        - name: client_id
          in: query
          schema:
            type: string
          description: Filter by client CzUid
        - name: series_id
          in: query
          schema:
            type: string
          description: Filter by series CzUid
        - name: is_paid
          in: query
          description: |
            Filter by payment status (0=unpaid, 1=paid).
            Note: This filter excludes voided and storno invoices.
          schema:
            type: integer
            enum: [0, 1]
        - name: is_void
          in: query
          schema:
            type: integer
            enum: [0, 1]
          description: Filter by void status
        - name: document_type
          in: query
          schema:
            type: string
            enum: [fiscal, proforma, receipt]
          description: Filter by document type
        - name: status
          in: query
          schema:
            type: string
            enum: [draft, sent, paid, overdue, cancelled]
          description: Filter by status
        - name: currency
          in: query
          schema:
            type: string
          description: Filter by currency code (e.g., RON, EUR, USD)
        - name: start_date
          in: query
          schema:
            type: string
            format: date
          description: Start date (YYYY-MM-DD)
        - name: end_date
          in: query
          schema:
            type: string
            format: date
          description: End date (YYYY-MM-DD)
        - name: sort
          in: query
          schema:
            type: string
            enum: [created_at, date, due_date, total, number]
            default: created_at
          description: Sort field
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: desc
          description: Sort order
        - name: expand[]
          in: query
          schema:
            type: array
            items:
              type: string
              enum: [lines, payments, client, efactura]
          style: form
          explode: true
          description: Expand nested objects
      responses:
        '200':
          description: List of invoices
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/InvoiceList'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    post:
      operationId: createInvoice
      tags: [Invoices]
      summary: Create an invoice
      description: |
        Creates a new invoice with flexible client handling and item management.
        
        ## Client Handling
        You can either:
        - Use an existing client with `client_id`
        - Create/find a client inline with `client_data`
        
        For B2B clients with the same CUI, the system will automatically reuse the existing client.
        
        ## Product Integration
        Invoice items can be:
        - Linked to existing products using `product_czuid`
        - Created as one-off items
        - Saved as new products with `save_as_product: true`
        
        ## E-Factura
        Romanian e-invoicing is enabled by default. Include UBL codes for compliance.
        
        ## Email Automation
        Set `send_email: true` to automatically send the invoice after creation.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InvoiceCreateRequest'
      responses:
        '201':
          description: Invoice created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Invoice'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /invoices/{id}:
    get:
      operationId: getInvoice
      tags: [Invoices]
      summary: Retrieve an invoice
      description: Get a specific invoice by ID with optional expansion of related objects
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
        - name: expand[]
          in: query
          schema:
            type: array
            items:
              type: string
              enum: [lines, payments, client, efactura]
          style: form
          explode: true
          description: Expand nested objects
      responses:
        '200':
          description: Invoice details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Invoice'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

    put:
      operationId: updateInvoice
      tags: [Invoices]
      summary: Update an invoice (header-only)
      description: |
        Updates a narrow set of header-level fields on an existing invoice.
        Full item/client rewrites are intentionally out of scope in v1 —
        issue a storno + a fresh invoice instead.

        ## Edit guards

        The endpoint rejects the update when:

        - The invoice is itself a storno row — `400 invoice_is_storno`.
        - The invoice has already been storno'd — `400 invoice_already_storned`.
        - The invoice is paid *and* the body touches totals
          (`items`, `currency`, `with_vat_inverted`) — `400 invoice_is_paid`.
        - ANAF has `accepted` or `validated` the invoice via SPV —
          `403 invoice_locked_efactura` (with `efactura_status` in the
          error payload).

        ## Field semantics

        - `info` is the canonical field for free-text notes. The legacy
          aliases `observation` and `notes` are accepted and mapped to
          `info` server-side, but new integrations should use `info`.
        - Row-level `price_total` / `account_amount_total` are **not**
          accepted — line totals are derived from `quantity × price` plus
          VAT. Send per-row components only.
        - `exchange_rate` is only applied when the invoice currency is not
          RON. It overrides `currency_rate` and is mirrored into every
          `account_amount_*` field.
        - `currency = "RON"` forces `currency_rate = 1.000` and
          `currency_to = "RON"` regardless of `exchange_rate`.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                date_at:
                  type: string
                  description: ISO date or unix timestamp. Alias - `date`.
                due_at:
                  type: string
                  nullable: true
                  description: ISO date or unix timestamp. Pass empty/null to clear. Alias - `due_date`.
                info:
                  type: string
                  nullable: true
                  description: Free-text notes shown on the PDF. Accepted aliases - `observation`, `notes`.
                client_id:
                  type: string
                  description: CzUid of an existing firm client; rebinds the invoice to that client's current snapshot.
                currency:
                  type: string
                  description: ISO-4217 code. Passing `RON` resets `currency_rate` to 1.
                exchange_rate:
                  type: number
                  description: Positive FX rate. Ignored for RON invoices. Overrides `currency_rate` and propagates to all `account_amount_*` fields.
                series_id:
                  type: string
                  description: CzUid (or numeric PK) of a `firm_number` series owned by the firm. Only used when actually switching series.
                items:
                  type: array
                  description: |
                    Replace the whole line-items array. Each row accepts
                    `description`, `quantity`, `price`, `vat_rate`,
                    `unit`, `product_czuid`, `um_id` etc. Row-level
                    `price_total` and `account_amount_total` are **not**
                    accepted — they are recomputed from the components.
                  items:
                    $ref: '#/components/schemas/InvoiceItem'
      responses:
        '200':
          description: Invoice updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/Invoice' }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400': { $ref: '#/components/responses/ValidationError' }
        '403':
          description: Invoice is locked by ANAF
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/NotFoundError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

    patch:
      operationId: patchInvoice
      tags: [Invoices]
      summary: Partial update (alias of PUT)
      description: Same contract as `PUT /invoices/{id}` — every field is optional and the two verbs are interchangeable.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      responses:
        '200':
          description: Invoice updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/Invoice' }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400': { $ref: '#/components/responses/ValidationError' }
        '403':
          description: Invoice is locked by ANAF
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/NotFoundError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

    delete:
      operationId: deleteInvoice
      tags: [Invoices]
      summary: Delete an invoice
      description: |
        Deletes an invoice. The invoice must be either a draft or voided before it can be deleted.
        For voided invoices with sequential numbers, only the last invoice in the series can be deleted
        to maintain number sequence integrity.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
      responses:
        '200':
          description: Invoice deleted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: invoice
                      id:
                        type: string
                        description: CzUid of deleted invoice
                      deleted:
                        type: boolean
                        example: true
                      deleted_at:
                        type: string
                        format: date-time
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          description: Invoice cannot be deleted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '405':
          $ref: '#/components/responses/MethodNotAllowedError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /invoices/{id}/pdf:
    get:
      operationId: getInvoicePdf
      tags: [Invoices]
      summary: Download invoice PDF
      description: |
        Get invoice PDF file or download URL.
        
        ## Response Modes
        - `download` (default): Returns the PDF file directly
        - `url`: Returns a JSON response with a temporary download URL
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
        - name: mode
          in: query
          schema:
            type: string
            enum: [download, url]
            default: download
          description: Response mode - direct download or URL
      responses:
        '200':
          description: PDF file or URL
          content:
            application/pdf:
              schema:
                type: string
                format: binary
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      url:
                        type: string
                        format: uri
                      expires_at:
                        type: integer
                        format: timestamp
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /invoices/{id}/send:
    post:
      operationId: sendInvoice
      tags: [Invoices]
      summary: Send invoice by email
      description: Send invoice to client via email with optional customization
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                email:
                  type: string
                  format: email
                  description: Override recipient email (uses client email if not specified)
                cc:
                  type: string
                  format: email
                  description: CC email address
                subject:
                  type: string
                  description: Custom email subject
                message:
                  type: string
                  description: Custom email message
      responses:
        '200':
          description: Invoice sent
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /invoices/{id}/pay:
    post:
      operationId: payInvoice
      tags: [Invoices]
      summary: Mark invoice as paid
      description: |
        Record a payment for an invoice.
        
        ## Payment Recording
        - Full payment: Invoice is marked as paid
        - Partial payment: Invoice remains unpaid with updated balance
        - Already paid invoices cannot accept additional payments
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - amount
                - payment_date
              properties:
                amount:
                  type: number
                  description: Payment amount
                payment_date:
                  type: string
                  format: date
                  description: Payment date (defaults to today)
                payment_method:
                  type: string
                  description: Payment method used
                observations:
                  type: string
                  description: Payment notes
      responses:
        '200':
          description: Payment recorded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      is_paid:
                        type: boolean
                      total_amount:
                        type: number
                      total_paid:
                        type: number
                      remaining:
                        type: number
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          description: Cannot pay - invoice already paid or validation error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /invoices/{id}/void:
    post:
      operationId: voidInvoice
      tags: [Invoices]
      summary: Void an invoice
      description: |
        Void (cancel) an invoice following Romanian accounting regulations.
        
        ## Voiding Process
        - Fiscal invoices with numbers: Creates a storno (reversal) invoice
        - Draft invoices: Simply marked as cancelled
        - Voided invoices cannot be edited or sent
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                reason:
                  type: string
                  description: Reason for voiding
      responses:
        '200':
          description: Invoice voided
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Invoice'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /invoices/{id}/unvoid:
    post:
      operationId: unvoidInvoice
      tags: [Invoices]
      summary: Unvoid an invoice
      description: Restore a voided invoice to its previous state
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
      responses:
        '200':
          description: Invoice restored
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Invoice'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /invoices/{id}/storno:
    post:
      operationId: stornoInvoice
      tags: [Invoices]
      summary: Storno (reverse) an invoice
      description: |
        Creates a reversal invoice with negated line amounts and links it to
        the source via `storno_bill_id`. Both invoices receive a history
        event (`TYPE_STORNO` on the source, `TYPE_STORNED` on the reversal).
        The whole operation runs inside a DB transaction.

        ## Preconditions
        - Source invoice must be fiscal (not a draft or proforma).
        - Source must not already be a storno (`is_storno = 0`).
        - Source must not already have been storno'd (`storno_bill_id` unset).
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Source invoice CzUid
      responses:
        '200':
          description: Storno invoice created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Invoice'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          description: Invoice cannot be reversed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              examples:
                cannot_be_storned:
                  value:
                    success: false
                    error:
                      type: invalid_request_error
                      code: invoice_cannot_be_storned
                      message: This invoice cannot be reversed. Only fiscal invoices can be reversed.
                already_storned:
                  value:
                    success: false
                    error:
                      type: invalid_request_error
                      code: invoice_already_storned
                      message: Invoice has already been reversed
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /invoices/{id}/send-to-spv:
    post:
      operationId: sendInvoiceToSpv
      tags: [Invoices]
      summary: Send invoice to e-Factura SPV
      description: |
        Submit invoice to Romanian e-Factura system (SPV).
        
        ## Requirements
        - Firm must have OAuth configured for e-Factura
        - Invoice must have e-Factura enabled
        - Client must have valid Romanian CUI
        
        ## Environments
        - `test`: SPV test environment for testing
        - `live`: Production ANAF system
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Invoice CzUid
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                test_mode:
                  type: boolean
                  default: false
                  description: Use SPV test environment
      responses:
        '200':
          description: Invoice sent to SPV
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      submission_id:
                        type: string
                      status:
                        type: string
                      message:
                        type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          description: OAuth not configured or validation error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  # Products endpoints
  /products:
    get:
      operationId: listProducts
      tags: [Products]
      summary: List all products
      description: Retrieves a paginated list of products and services
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
          description: Page number
        - name: per_page
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
          description: Items per page
        - name: search
          in: query
          schema:
            type: string
          description: Search in name and description
        - name: type
          in: query
          schema:
            type: string
            enum: [product, service]
          description: Filter by row type. Preferred over the legacy `is_service` flag.
        - name: is_service
          in: query
          schema:
            type: integer
            enum: [0, 1]
          description: Legacy filter (`0` = product, `1` = service). Prefer `type`.
        - name: is_active
          in: query
          schema:
            type: integer
            enum: [0, 1]
          description: Filter by active status
        - name: currency
          in: query
          schema:
            type: string
          description: Filter by currency
        - name: sort
          in: query
          schema:
            type: string
            enum: [name, price, created_at]
            default: name
          description: Sort field
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: asc
          description: Sort order
      responses:
        '200':
          description: List of products
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ProductList'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    post:
      operationId: createProduct
      tags: [Products]
      summary: Create a product
      description: Creates a new product or service
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProductCreateRequest'
      responses:
        '201':
          description: Product created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Product'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /products/{id}:
    get:
      operationId: getProduct
      tags: [Products]
      summary: Retrieve a product
      description: Get a specific product by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Product CzUid
      responses:
        '200':
          description: Product details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Product'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    put:
      operationId: updateProduct
      tags: [Products]
      summary: Update a product
      description: Updates an existing product
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Product CzUid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ProductUpdateRequest'
      responses:
        '200':
          description: Product updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Product'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    delete:
      operationId: deleteProduct
      tags: [Products]
      summary: Delete a product
      description: Deletes a product (soft delete, cannot delete if used in invoices)
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Product CzUid
      responses:
        '200':
          description: Product deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '409':
          description: Cannot delete product in use
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  # Expenses endpoints
  /expenses:
    get:
      operationId: listExpenses
      tags: [Expenses]
      summary: List all expenses
      description: Retrieves a paginated list of expenses with optional filters
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
          description: Page number
        - name: per_page
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
          description: Items per page
        - name: supplier_id
          in: query
          schema:
            type: string
          description: Filter by supplier CzUid
        - name: category_id
          in: query
          schema:
            type: integer
          description: Filter by category ID
        - name: status
          in: query
          schema:
            type: string
            enum: [paid, unpaid, overdue, registered]
          description: Filter by payment status
        - name: currency
          in: query
          schema:
            type: string
          description: Filter by currency code
        - name: payment_type
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 7
          description: |
            Filter by payment type:
            1 = Cash
            2 = Bank transfer
            3 = Card
            4 = Check
            5 = Promissory note
            6 = Other
            7 = Compensation
        - name: start_date
          in: query
          schema:
            type: string
            format: date
          description: Start date (YYYY-MM-DD)
        - name: end_date
          in: query
          schema:
            type: string
            format: date
          description: End date (YYYY-MM-DD)
        - name: min_amount
          in: query
          schema:
            type: number
          description: Minimum amount filter
        - name: max_amount
          in: query
          schema:
            type: number
          description: Maximum amount filter
        - name: search
          in: query
          schema:
            type: string
          description: Search in reference and description
        - name: sort
          in: query
          schema:
            type: string
            enum: [created_at, date, due_date, amount]
            default: date
          description: Sort field
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: desc
          description: Sort order
        - name: expand
          in: query
          schema:
            type: string
          description: "Comma-separated list of relations to expand. Supported: `supplier`, `category`, `user`."
      responses:
        '200':
          description: List of expenses
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ExpenseList'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    post:
      operationId: createExpense
      tags: [Expenses]
      summary: Create an expense
      description: |
        Creates a new expense record with minimal required fields.
        
        ## Required Fields (only 4)
        - `supplier_id`: Supplier CzUid (required)
        - `amount`: Amount (required, positive number) 
        - `vat`: VAT percentage (required - accepts 0, 5, 9, 11, 19, 21)
        - `date`: Date in Y-m-d format (required)
        
        ## Optional Fields with Smart Defaults
        - `currency`: Currency code (defaults to RON)
        - `due_date`: Due date (defaults to 30 days from today)
        - `paid_date`: Payment date (defaults to today if is_paid=true)
        - `payment_type`: Payment type ID 1-7 (defaults to 1 if is_paid=true)
        - `category_id`: Category ID (defaults to 0)
        - `reference`: Reference number
        - `description`: Description
        - `with_vat`: Whether amount includes VAT (defaults to false)
        - `is_paid`: Whether expense is paid (defaults to false)
        - `with_currency_exchange`: Boolean for currency exchange
        - `currency_to`: Target currency (if with_currency_exchange)
        - `currency_rate`: Exchange rate (if with_currency_exchange)
        
        ## VAT Rates
        Supported VAT rates: 0%, 5%, 9%, 11%, 19%, 21% (21% is standard in Romania)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExpenseCreateRequest'
      responses:
        '201':
          description: Expense created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Expense'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /expenses/export:
    get:
      operationId: exportExpenses
      tags: [Expenses]
      summary: Export expenses to CSV
      description: Export expenses to CSV format with optional filters
      parameters:
        - name: supplier_id
          in: query
          schema:
            type: string
          description: Filter by supplier CzUid
        - name: category_id
          in: query
          schema:
            type: integer
          description: Filter by category ID
        - name: start_date
          in: query
          schema:
            type: string
            format: date
          description: Start date (Y-m-d format)
        - name: end_date
          in: query
          schema:
            type: string
            format: date
          description: End date (Y-m-d format)
        - name: status
          in: query
          schema:
            type: string
            enum: [paid, unpaid, overdue]
          description: Filter by payment status
      responses:
        '200':
          description: CSV export file
          content:
            text/csv:
              schema:
                type: string
                format: binary
              examples:
                csv_export:
                  summary: CSV file with expense data
                  description: Returns a CSV file with all expense data matching the filters
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /expenses/{id}:
    get:
      operationId: getExpense
      tags: [Expenses]
      summary: Retrieve an expense
      description: Get a specific expense by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
        - name: expand
          in: query
          schema:
            type: string
          description: "Comma-separated list of relations to expand. Supported: `supplier`, `category`, `user`."
      responses:
        '200':
          description: Expense details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Expense'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    put:
      operationId: updateExpense
      tags: [Expenses]
      summary: Update an expense
      description: Updates an existing expense
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExpenseUpdateRequest'
      responses:
        '200':
          description: Expense updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Expense'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    delete:
      operationId: deleteExpense
      tags: [Expenses]
      summary: Delete an expense
      description: |
        Permanently deletes an expense (hard delete, not soft delete).
        
        ## Important Notes
        - This is a HARD delete operation - the expense is permanently removed
        - Unlike other entities that use soft delete, expenses are completely removed from the database
        - Cannot be undone once deleted
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
      responses:
        '200':
          description: Expense deleted successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /expenses/{id}/pay:
    post:
      operationId: payExpense
      tags: [Expenses]
      summary: Mark expense as paid
      description: Mark an expense as paid
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - paid_date
                - payment_type
              properties:
                paid_date:
                  type: string
                  format: date
                  description: Payment date
                payment_type:
                  type: integer
                  minimum: 1
                  maximum: 7
                  description: Payment method (1-7)
      responses:
        '200':
          description: Expense marked as paid
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Expense'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /expenses/ocr-extract:
    post:
      operationId: ocrExtractReceipt
      tags: [Expenses]
      summary: Scan receipt (OCR)
      description: |
        Upload a Romanian receipt or supplier invoice photo and receive a
        structured prefill payload (supplier match, dates, totals, per-rate
        VAT breakdown, optional per-line items, payment-method hint).

        Use the response to prefill an expense form. Persist via
        POST /expenses — typically with `vat = "mix"` + `amount_vat_manual`
        for multi-rate receipts.

        See [the OCR endpoint guide](/api-reference/endpoints/expenses/ocr-extract).
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [image]
              properties:
                image:
                  type: string
                  format: binary
                  description: Receipt image (JPEG / PNG / WebP, ≤ 10 MB).
      responses:
        '200':
          description: Extracted prefill payload
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OcrReceiptPayload'
        '400':
          description: Invalid file (missing, wrong type, too large)
        '502':
          description: Extraction failed (transient — safe to retry)
        '503':
          description: OCR not enabled on this deployment

  /expenses/check-duplicate:
    post:
      operationId: checkExpenseDuplicate
      tags: [Expenses]
      summary: Pre-check for duplicate expense
      description: |
        Probe the firm's books for an existing expense that would collide
        with the prospective payload (same supplier + reference, or same
        supplier + date + amount within tolerance). Useful before posting a
        scanned receipt to surface a confirmation dialog.

        Returns `{ duplicate: null }` when nothing matches, or a payload
        describing the existing row otherwise. Match types:
        - `exact` — supplier + reference
        - `strong` — supplier + date + amount (±0.02)
        - `likely` — reference collision across suppliers
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                supplier_id:
                  type: string
                  description: Supplier CzUid (preferred) or omit and send `supplier_data`.
                supplier_data:
                  type: object
                  properties:
                    name: { type: string }
                    cui:  { type: string }
                reference:
                  type: string
                date:
                  type: string
                  format: date
                amount:
                  type: number
                currency:
                  type: string
                  default: RON
      responses:
        '200':
          description: Duplicate check result
          content:
            application/json:
              schema:
                type: object
                properties:
                  duplicate:
                    nullable: true
                    type: object
                    properties:
                      id:         { type: string }
                      reference:  { type: string, nullable: true }
                      date:       { type: string, format: date }
                      amount:     { type: number }
                      currency:   { type: string }
                      match_type: { type: string, enum: [exact, strong, likely] }

  /expenses/ai-categorize-batch:
    post:
      operationId: aiCategorizeExpensesBatch
      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.
      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

  /expenses/{id}/attachments:
    post:
      operationId: uploadExpenseAttachment
      tags: [Expenses]
      summary: Upload expense attachment
      description: |
        Upload a single PDF or image attachment for an expense. Each expense supports only ONE attachment (stored in the 'image' field).
        
        ## File Requirements
        - Supported types: PDF, JPG, JPEG, PNG
        - Maximum file size: 10MB
        - Only one attachment per expense
        
        ## Important Notes
        - Uploading a new file will replace any existing attachment
        - Creates a default supplier if the expense doesn't have one
        - There is NO GET endpoint for listing attachments (single attachment only)
        - There is NO DELETE endpoint for removing attachments individually
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - file
              properties:
                file:
                  type: string
                  format: binary
                  description: PDF or image file (max 10MB)
      responses:
        '200':
          description: Attachment uploaded successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      filename:
                        type: string
                      url:
                        type: string
                      size:
                        type: integer
                      type:
                        type: string
                        enum: [pdf, image]
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          description: Invalid file or size limit exceeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /expenses/{id}/efactura-pdf:
    get:
      operationId: getExpenseEfacturaPdf
      tags: [Expenses]
      summary: Download e-Factura PDF
      description: |
        Streams the ANAF e-Factura PDF for an expense imported from the SPV
        inbox. Generated on demand via the ANAF public validator the first
        time it is requested, then cached on disk.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
      responses:
        '200':
          description: PDF stream
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '404':
          description: Expense is not linked to an SPV supplier invoice or XML missing
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '502':
          description: ANAF PDF generation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  # Expense Categories endpoints
  /expense-categories:
    get:
      operationId: listExpenseCategories
      tags: [Expense Categories]
      summary: List expense categories
      description: Get all expense categories with optional hierarchy
      parameters:
        - name: parent_id
          in: query
          schema:
            type: integer
          description: Filter by parent category ID (0 for root categories)
        - name: include_children
          in: query
          schema:
            type: boolean
            default: false
          description: Include child categories in response
        - name: include_system
          in: query
          schema:
            type: boolean
            default: true
          description: Include system default categories
        - name: is_visible
          in: query
          schema:
            type: integer
            enum: [0, 1]
          description: Filter by visibility
      responses:
        '200':
          description: List of categories
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/ExpenseCategory'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    post:
      operationId: createExpenseCategory
      tags: [Expense Categories]
      summary: Create expense category
      description: Create a custom expense category
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExpenseCategoryCreateRequest'
      responses:
        '201':
          description: Category created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ExpenseCategory'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /expense-categories/{id}:
    get:
      operationId: getExpenseCategory
      tags: [Expense Categories]
      summary: Get category details
      description: Get a specific expense category
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
          description: Category ID
        - name: include_children
          in: query
          schema:
            type: boolean
            default: false
          description: Include child categories
      responses:
        '200':
          description: Category details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ExpenseCategory'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    put:
      operationId: updateExpenseCategory
      tags: [Expense Categories]
      summary: Update expense category
      description: Update a custom expense category (cannot modify system categories)
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
          description: Category ID
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExpenseCategoryUpdateRequest'
      responses:
        '200':
          description: Category updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/ExpenseCategory'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '403':
          description: Cannot modify system categories
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    delete:
      operationId: deleteExpenseCategory
      tags: [Expense Categories]
      summary: Delete expense category
      description: Delete a custom expense category (cannot delete system categories or categories with expenses)
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
          description: Category ID
      responses:
        '200':
          description: Category deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '403':
          description: Cannot delete system categories or categories with expenses
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  # Suppliers endpoints
  /suppliers:
    get:
      operationId: listSuppliers
      tags: [Suppliers]
      summary: List all suppliers
      description: Retrieves a paginated list of suppliers
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            minimum: 1
            default: 1
          description: Page number
        - name: per_page
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
          description: Items per page
        - name: search
          in: query
          schema:
            type: string
          description: Search in name, CUI, email
        - name: country
          in: query
          schema:
            type: string
          description: Filter by country code
        - name: is_vat_payer
          in: query
          schema:
            type: integer
            enum: [0, 1]
          description: Filter by VAT payer status
        - name: has_expenses
          in: query
          schema:
            type: boolean
          description: Only suppliers with expenses
        - name: sort
          in: query
          schema:
            type: string
            enum: [name, created_at, usage]
            default: name
          description: Sort field
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: asc
          description: Sort order
        - name: expand
          in: query
          schema:
            type: string
          description: Comma-separated list (statistics,recent_expenses)
        - name: with_totals
          in: query
          schema:
            type: integer
            enum: [0, 1]
          description: |
            When `1`, attaches a `metadata` object to each supplier with
            `expense_count`, `total_expenses`, and `unpaid_total` computed
            via inline subqueries (avoids N+1). Cheaper than
            `expand=statistics`.
      responses:
        '200':
          description: List of suppliers
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/SupplierList'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    post:
      operationId: createSupplier
      tags: [Suppliers]
      summary: Create a supplier
      description: Creates a new supplier
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SupplierCreateRequest'
      responses:
        '201':
          description: Supplier created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Supplier'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  /suppliers/{id}:
    get:
      operationId: getSupplier
      tags: [Suppliers]
      summary: Retrieve a supplier
      description: Get a specific supplier by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Supplier CzUid
        - name: expand
          in: query
          schema:
            type: string
          description: Comma-separated list (statistics,recent_expenses)
      responses:
        '200':
          description: Supplier details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Supplier'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    put:
      operationId: updateSupplier
      tags: [Suppliers]
      summary: Update a supplier
      description: Updates an existing supplier
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Supplier CzUid
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SupplierUpdateRequest'
      responses:
        '200':
          description: Supplier updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Supplier'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
    delete:
      operationId: deleteSupplier
      tags: [Suppliers]
      summary: Delete a supplier
      description: Permanently deletes a supplier (hard delete, only if no associated expenses)
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Supplier CzUid
      responses:
        '200':
          description: Supplier deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  message:
                    type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '409':
          description: Cannot delete supplier with existing expenses
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
          
  # Supplier Bills endpoints (e-Factura received invoices)
  /supplier-bills:
    get:
      operationId: listSupplierBills
      tags: [Supplier Bills]
      summary: List supplier bills
      description: |
        Returns supplier invoices received from the ANAF SPV inbox (e-Factura).
        Mirrors the web view at /firm/bill-supplier with filters, totals and
        pagination. Spans every work point under the parent company.
      parameters:
        - name: page
          in: query
          schema: { type: integer, minimum: 1, default: 1 }
        - name: per_page
          in: query
          schema: { type: integer, minimum: 1, maximum: 100, default: 25 }
        - name: status
          in: query
          schema: { type: string, enum: [unpaid, paid, partial] }
        - name: supplier
          in: query
          description: Search by supplier name or VAT id (LIKE).
          schema: { type: string }
        - name: search
          in: query
          description: Alias of `supplier` — search by CIF or supplier name.
          schema: { type: string }
        - name: supplier_id
          in: query
          description: Filter by supplier CzUid.
          schema: { type: string }
        - name: currency
          in: query
          schema: { type: string }
        - name: invoice_type_code
          in: query
          schema: { type: string, enum: ['380', '381'] }
          description: 380 = invoice, 381 = credit note.
        - name: start_date
          in: query
          schema: { type: string, format: date }
        - name: end_date
          in: query
          schema: { type: string, format: date }
        - name: sort
          in: query
          schema:
            type: string
            enum: [issue_date, due_date, total, invoice_number, created_at]
            default: issue_date
        - name: order
          in: query
          schema: { type: string, enum: [asc, desc], default: desc }
        - name: expand
          in: query
          description: "Comma-separated list of relations to expand. Supported: `supplier`, `expense`, `client`, `efactura_message`, `lines`."
          schema: { type: string }
      responses:
        '200':
          description: List of supplier bills
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/SupplierBillList' }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /supplier-bills/sync:
    post:
      operationId: syncSupplierBills
      tags: [Supplier Bills]
      summary: Trigger SPV sync
      description: |
        Pulls fresh messages from the ANAF SPV inbox, downloads any missing
        XMLs, and imports received invoices into Contazen. Synchronous — the
        call blocks until ANAF responds (typically 5–30s per firm). Concurrent
        syncs for the same firm are rejected with HTTP 429.
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                days:
                  type: integer
                  minimum: 1
                  maximum: 60
                  description: |
                    How far back to fetch (1–60). When omitted, the window is
                    chosen automatically based on the time since the last sync.
      responses:
        '200':
          description: Sync result
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/SupplierBillSyncResult' }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '429':
          description: A sync for this firm is already in progress
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '502':
          description: ANAF SPV call failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /supplier-bills/{id}:
    get:
      operationId: getSupplierBill
      tags: [Supplier Bills]
      summary: Get supplier bill
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Supplier bill CzUid.
        - name: expand
          in: query
          schema: { type: string }
          description: "Defaults to `supplier,expense,client,efactura_message,lines`."
      responses:
        '200':
          description: Supplier bill detail (with `supplier_balance` block)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      supplier_bill:
                        allOf:
                          - $ref: '#/components/schemas/SupplierBill'
                          - type: object
                            properties:
                              supplier_balance:
                                $ref: '#/components/schemas/SupplierBillBalance'
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          description: Bill not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

    delete:
      operationId: deleteSupplierBill
      tags: [Supplier Bills]
      summary: Delete supplier bill (soft delete)
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Bill marked as deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      id: { type: string }
                      object: { type: string, example: supplier_bill }
                      deleted: { type: boolean }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          description: Bill not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /supplier-bills/{id}/mark-paid:
    post:
      operationId: markSupplierBillPaid
      tags: [Supplier Bills]
      summary: Mark supplier bill as paid
      description: |
        Records a payment on the supplier bill. Pass `payment_amount` lower
        than the bill total to record a partial payment — the resulting status
        becomes `partial`. Linked expenses are kept in sync.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SupplierBillMarkPaidRequest'
      responses:
        '200':
          description: Bill updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      supplier_bill: { $ref: '#/components/schemas/SupplierBill' }
                      message: { type: string }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          description: Bill not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /supplier-bills/{id}/mark-unpaid:
    post:
      operationId: markSupplierBillUnpaid
      tags: [Supplier Bills]
      summary: Mark supplier bill as unpaid
      description: Clears `payment_date`, `payment_amount`, and resets `status` to `unpaid`.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Bill updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      supplier_bill: { $ref: '#/components/schemas/SupplierBill' }
                      message: { type: string }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          description: Bill not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /supplier-bills/{id}/efactura-pdf:
    get:
      operationId: getSupplierBillEfacturaPdf
      tags: [Supplier Bills]
      summary: Download e-Factura PDF
      description: |
        Streams the ANAF e-Factura PDF for this bill. Generated on demand via
        the ANAF public validator the first time it is requested, then cached
        on disk. Returns 404 when the bill has no associated SPV message.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: PDF stream
          content:
            application/pdf:
              schema:
                type: string
                format: binary
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          description: Bill not found or no e-Factura XML available
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '502':
          description: ANAF PDF generation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  # Settings endpoint
  /settings:
    get:
      operationId: getSettings
      tags: [Settings]
      summary: Get API settings
      description: |
        Get current API settings, configuration, and account information.

        This endpoint provides comprehensive information about:
        - API version and rate limits
        - Firm details and configuration
        - Invoice series and numbering
        - E-Factura setup status
        - Available features and subscription
        - Supported currencies and VAT rates
      responses:
        '200':
          description: API settings
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Settings'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /payments:
    get:
      operationId: listPayments
      tags: [Payments]
      summary: List payments
      description: |
        List all payments across invoices for the authenticated firm.
        Returns a flattened view of invoice payments with invoice and client references.
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: per_page
          in: query
          schema:
            type: integer
            default: 50
            maximum: 100
        - name: invoice_id
          in: query
          description: Filter by invoice ID (CzUid)
          schema:
            type: string
        - name: client_id
          in: query
          description: Filter by client ID (CzUid)
          schema:
            type: string
        - name: type
          in: query
          description: Filter by payment type
          schema:
            type: string
            enum: [receipt, bank_order, card, cheque, promissory_note, other, fiscal_receipt]
        - name: date_from
          in: query
          description: Filter from date (YYYY-MM-DD)
          schema:
            type: string
            format: date
        - name: date_to
          in: query
          description: Filter to date (YYYY-MM-DD)
          schema:
            type: string
            format: date
        - name: sort
          in: query
          schema:
            type: string
            enum: [date, amount, created_at]
            default: date
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: desc
      responses:
        '200':
          description: List of payments
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: list
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/Payment'
                      has_more:
                        type: boolean
                      total:
                        type: integer
                      page:
                        type: integer
                      per_page:
                        type: integer
                      total_pages:
                        type: integer
                      totals:
                        $ref: '#/components/schemas/PaymentTotals'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /payments/{id}:
    get:
      operationId: getPayment
      tags: [Payments]
      summary: Retrieve a payment
      description: Get details of a specific payment by its ID.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Payment details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Payment'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /receipts:
    get:
      operationId: listReceipts
      tags: [Receipts]
      summary: List receipts
      description: |
        List `chitanță` (cash receipt) documents for the authenticated firm.
        Each row may be standalone or paired with an invoice and a
        `FirmBillPayment` (see `payment` on `GET /receipts/{id}`).
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: per_page
          in: query
          schema:
            type: integer
            default: 50
            maximum: 100
        - name: date_from
          in: query
          description: Filter from date (YYYY-MM-DD)
          schema:
            type: string
            format: date
        - name: date_to
          in: query
          description: Filter to date (YYYY-MM-DD)
          schema:
            type: string
            format: date
        - name: client_id
          in: query
          description: Filter by client CzUid (matches all snapshots of that client)
          schema:
            type: string
        - name: invoice_id
          in: query
          description: Only chitanțe paying this invoice (CzUid)
          schema:
            type: string
        - name: include_deleted
          in: query
          schema:
            type: boolean
            default: false
        - name: sort
          in: query
          schema:
            type: string
            enum: [date, amount, created_at]
            default: date
        - name: order
          in: query
          schema:
            type: string
            enum: [asc, desc]
            default: desc
      responses:
        '200':
          description: List of receipts
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: list
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/Receipt'
                      has_more:
                        type: boolean
                      total:
                        type: integer
                      page:
                        type: integer
                      per_page:
                        type: integer
                      total_pages:
                        type: integer
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

    post:
      operationId: createReceipt
      tags: [Receipts]
      summary: Create a receipt
      description: |
        Create a chitanță. When `invoice_id` is supplied, a paired
        `FirmBillPayment` is created and the invoice's paid state is
        recomputed (flips to `is_paid: true` once the cumulative paid amount
        meets the invoice total). Standalone chitanțe (no invoice) skip the
        payment row and default to type `receipt` (numerar).

        Cash-register synchronization runs inside the same transaction —
        failures roll the whole save back.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReceiptCreateRequest'
      responses:
        '201':
          description: Receipt created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Receipt'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          $ref: '#/components/responses/ValidationError'
        '422':
          description: |
            Returned when the firm has no chitanță series configured
            (`code: chitanta_series_missing`) or `validate()` rejects the
            payload (`code: validation_failed`).
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /receipts/{id}:
    get:
      operationId: getReceipt
      tags: [Receipts]
      summary: Retrieve a receipt
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Receipt CzUid
      responses:
        '200':
          description: Receipt details
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Receipt'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

    put:
      operationId: updateReceipt
      tags: [Receipts]
      summary: Update a receipt
      description: |
        Updates an existing chitanță. Returns `409 resource_deleted` if the
        receipt has already been soft-deleted. Linked invoice paid state is
        re-computed when amount/invoice changes.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReceiptUpdateRequest'
      responses:
        '200':
          description: Receipt updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Receipt'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '409':
          description: "Receipt already deleted (`code: resource_deleted`)"
        '422':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

    delete:
      operationId: deleteReceipt
      tags: [Receipts]
      summary: Delete a receipt
      description: |
        Soft-deletes the chitanță. Cascades to the linked
        `FirmBillPayment` (if any) and undoes the invoice's paid state.
        Idempotent — re-deleting an already-deleted receipt returns success.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Receipt deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                      object:
                        type: string
                        example: receipt
                      deleted:
                        type: boolean
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /company-lookup:
    get:
      operationId: companyLookup
      tags: [Company Lookup]
      summary: Look up a Romanian company by CUI/CIF
      description: |
        Query Romanian company registry data by CUI/CIF number. Returns company name,
        registration details, address, VAT status, and e-invoice registration status.

        The lookup is rate-limited to 1 request per second due to upstream ANAF constraints.
      parameters:
        - name: cui
          in: query
          required: true
          description: The CUI/CIF number to look up (with or without RO prefix)
          schema:
            type: string
            example: "12345678"
      responses:
        '200':
          description: Company data found
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: company_lookup
                      cui:
                        type: string
                      name:
                        type: string
                      rc:
                        type: string
                        description: Trade registry number (Registrul Comerțului)
                      address:
                        type: string
                      city:
                        type: string
                      county:
                        type: string
                      country:
                        type: string
                      postal_code:
                        type: string
                      caen:
                        type: string
                        description: CAEN activity code
                      vat_payer:
                        type: boolean
                      split_vat:
                        type: boolean
                      ro_einvoice_registered:
                        type: boolean
                        description: Whether registered for Romanian e-invoice system
                      is_inactive:
                        type: boolean
                      registration_date:
                        type: string
                      authority_name:
                        type: string
                      source:
                        type: string
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          description: No company found for the given CUI
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '503':
          description: Lookup service temporarily unavailable

  /invoice-series:
    get:
      operationId: listInvoiceSeries
      tags: [Invoice Series]
      summary: List invoice series
      description: List all invoice numbering series for the authenticated firm.
      parameters:
        - name: document_type
          in: query
          description: Filter by document type
          schema:
            type: string
            enum: [fiscal, proforma]
      responses:
        '200':
          description: List of invoice series
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: list
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/InvoiceSeries'
                      total:
                        type: integer
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
    post:
      operationId: createInvoiceSeries
      tags: [Invoice Series]
      summary: Create an invoice series
      description: Create a new invoice numbering series.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, document_type]
              properties:
                name:
                  type: string
                  description: Series prefix/name (e.g., "FACT", "PF")
                  example: FACT
                document_type:
                  type: string
                  enum: [fiscal, proforma]
                description:
                  type: string
                start_number:
                  type: integer
                  default: 1
                  description: First invoice number in the series
                is_primary:
                  type: boolean
                  default: false
                  description: Set as the default series for this document type
      responses:
        '201':
          description: Series created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/InvoiceSeries'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '409':
          description: Series with this name/type already exists
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /invoice-series/{id}:
    put:
      operationId: updateInvoiceSeries
      tags: [Invoice Series]
      summary: Update an invoice series
      description: |
        Update an invoice series. Only series that have not been used for any documents can be modified.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                description:
                  type: string
      responses:
        '200':
          description: Series updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/InvoiceSeries'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '400':
          description: Series is already in use and cannot be modified
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /invoice-series/{id}/set-primary:
    post:
      operationId: setInvoiceSeriesPrimary
      tags: [Invoice Series]
      summary: Set series as primary
      description: Set an invoice series as the default for its document type. The previous primary series will be demoted.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Series set as primary
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/InvoiceSeries'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /invoice-series/{id}/lock:
    post:
      operationId: lockInvoiceSeries
      tags: [Invoice Series]
      summary: Lock series to mobile device
      description: |
        Bind the series to the calling mobile device so only that device can
        issue invoices against it. Requires a mobile JWT session whose backing
        `user_session` has a non-empty `device_id`.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Series locked
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/InvoiceSeries'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '409':
          description: Series is already locked to another device
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /invoice-series/{id}/unlock:
    post:
      operationId: unlockInvoiceSeries
      tags: [Invoice Series]
      summary: Unlock series
      description: |
        Release the mobile-device lock. The owning device can always unlock;
        other callers must pass `force: true` and have admin rights.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                force:
                  type: boolean
                  default: false
                  description: Override the same-device rule when unlocking from another device.
      responses:
        '200':
          description: Series unlocked
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/InvoiceSeries'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '403':
          description: Locked to another device and `force` not supplied
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /invoice-series/{id}/reserve-numbers:
    post:
      operationId: reserveInvoiceSeriesNumbers
      tags: [Invoice Series]
      summary: Pre-allocate numbers for offline emission
      description: |
        Returns `count` reservation tokens. Each token corresponds to a
        pre-allocated invoice number on the series. The mobile device uses
        the tokens to emit invoices while offline — passing
        `reservation_token` to `POST /invoices` consumes the reservation and
        assigns its pre-allocated number instead of calling `nextNumber()`.

        Requires the series to already be locked to the calling device.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                count:
                  type: integer
                  minimum: 1
                  maximum: 50
                  default: 10
      responses:
        '201':
          description: Reservations created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: list
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/NumberReservation'
                      total:
                        type: integer
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '409':
          description: Series is not locked to this device
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'

  /invoice-series/{id}/reservations:
    get:
      operationId: listInvoiceSeriesReservations
      tags: [Invoice Series]
      summary: List pending reservations for this device
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Reservation list
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: list
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/NumberReservation'
                      total:
                        type: integer
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /invoice-series/reservations/{token}/release:
    post:
      operationId: releaseInvoiceSeriesReservation
      tags: [Invoice Series]
      summary: Release an unused reservation
      description: |
        Flip a pending reservation to `released`. The pre-allocated number is
        not returned to the pool — it becomes a documented gap.
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Reservation released
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/NumberReservation'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '403':
          description: Reservation belongs to another device
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          $ref: '#/components/responses/NotFoundError'

  /bank-accounts:
    get:
      operationId: listBankAccounts
      tags: [Bank Accounts]
      summary: List bank accounts
      description: List all IBAN bank accounts for the authenticated firm.
      parameters:
        - name: currency
          in: query
          description: Filter by currency
          schema:
            type: string
            example: RON
        - name: is_visible
          in: query
          description: Filter by visibility on invoices
          schema:
            type: boolean
      responses:
        '200':
          description: List of bank accounts
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: list
                      data:
                        type: array
                        items:
                          $ref: '#/components/schemas/BankAccount'
                      total:
                        type: integer
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
    post:
      operationId: createBankAccount
      tags: [Bank Accounts]
      summary: Create a bank account
      description: Add a new IBAN bank account. The IBAN is validated and bank name/BIC are auto-detected for Romanian banks.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [iban, bank_name, currency]
              properties:
                iban:
                  type: string
                  description: Valid IBAN number
                  example: RO49AAAA1B31007593840000
                bank_name:
                  type: string
                  example: Banca Transilvania
                currency:
                  type: string
                  example: RON
                swift:
                  type: string
                  description: SWIFT/BIC code (optional, auto-detected for Romanian banks)
                is_visible:
                  type: boolean
                  default: true
                  description: Whether to show this account on invoices
      responses:
        '201':
          description: Bank account created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/BankAccount'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '409':
          description: IBAN already registered for this firm
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /bank-accounts/{id}:
    put:
      operationId: updateBankAccount
      tags: [Bank Accounts]
      summary: Update a bank account
      description: Update bank account details. IBAN uniqueness is validated.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                iban:
                  type: string
                bank_name:
                  type: string
                currency:
                  type: string
                swift:
                  type: string
                is_visible:
                  type: boolean
      responses:
        '200':
          description: Bank account updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/BankAccount'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
    delete:
      operationId: deleteBankAccount
      tags: [Bank Accounts]
      summary: Delete a bank account
      description: Permanently delete a bank account.
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Bank account deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                      object:
                        type: string
                        example: bank_account
                      deleted:
                        type: boolean
                        example: true
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '404':
          $ref: '#/components/responses/NotFoundError'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /efactura/status:
    get:
      operationId: getEfacturaStatus
      tags: [E-Factura]
      summary: Get e-Factura status
      description: |
        Get the current e-Factura configuration status including OAuth connection,
        token validity, environment settings, and auto-send configuration.

        This is a read-only endpoint. To configure e-Factura OAuth, use the web interface at contazen.ro.
      responses:
        '200':
          description: E-Factura status
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: object
                    properties:
                      object:
                        type: string
                        example: efactura_status
                      enabled:
                        type: boolean
                      oauth_configured:
                        type: boolean
                      token_valid:
                        type: boolean
                      token_expires_at:
                        type: string
                        format: date-time
                        nullable: true
                      environment:
                        type: string
                        enum: [test, live]
                      environments:
                        type: object
                        properties:
                          test:
                            type: object
                            properties:
                              configured:
                                type: boolean
                              token_expires_at:
                                type: string
                                nullable: true
                          live:
                            type: object
                            properties:
                              configured:
                                type: boolean
                              token_expires_at:
                                type: string
                                nullable: true
                      auto_send:
                        type: boolean
                      auto_send_timing:
                        type: string
                        enum: [immediate, delayed]
                        nullable: true
                      auto_send_delay_days:
                        type: integer
                        nullable: true
                      send_to_public_institutions:
                        type: boolean
                      configure_url:
                        type: string
                        description: URL to configure e-Factura on the web interface
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'

  /invoices/{id}/history:
    get:
      operationId: getInvoiceHistory
      tags: [Invoices]
      summary: Invoice change history
      description: Audit trail for a fiscal invoice — creation, updates, payments, voids, etc.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Invoice ID (czUid).
        - name: page
          in: query
          schema: { type: integer, default: 1, minimum: 1 }
        - name: per_page
          in: query
          schema: { type: integer, default: 50, minimum: 1, maximum: 100 }
      responses:
        '200':
          description: History entries
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      object: { type: string, example: list }
                      data:
                        type: array
                        items:
                          type: object
                          properties:
                            id: { type: string }
                            type: { type: string, description: Internal event type }
                            type_label: { type: string, description: Human-readable label }
                            message: { type: string }
                            icon: { type: string, nullable: true }
                            by: { type: string, nullable: true, description: User who triggered the event }
                            created_at: { type: string, format: date-time }
                      pagination:
                        type: object
                        properties:
                          page: { type: integer }
                          per_page: { type: integer }
                          total: { type: integer }
                          total_pages: { type: integer }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400': { $ref: '#/components/responses/BadRequestError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }
        '404': { $ref: '#/components/responses/NotFoundError' }

  /invoices/{id}/payment-estimate:
    get:
      operationId: getInvoicePaymentEstimate
      tags: [Invoices]
      summary: Predict invoice payment date
      description: |
        Returns a predicted payment date for an unpaid invoice using the client's
        historical average days-to-pay (falls back to firm average, then to
        `due_at + 7 days`). For already-paid invoices, returns the actual payment date.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Invoice ID (czUid).
      responses:
        '200':
          description: Payment estimate
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    type: object
                    properties:
                      status:
                        type: string
                        enum: [unpaid, paid]
                      estimated_at:
                        type: string
                        format: date
                        nullable: true
                      due_at:
                        type: string
                        format: date
                        nullable: true
                      days_from_now:
                        type: integer
                        description: Days between today and estimated_at (negative if past).
                      days_overdue:
                        type: integer
                        description: Days the invoice is already overdue (0 if not overdue).
                      confidence:
                        type: string
                        enum: [low, medium, high, actual]
                      basis:
                        type: object
                        description: Data used to compute the estimate.
                        properties:
                          source:
                            type: string
                            enum: [client_history, firm_history, due_date_fallback, actual_payment]
                          sample_size: { type: integer, nullable: true }
                          avg_days_to_pay: { type: number, nullable: true }
                          client_on_time_pct: { type: number, nullable: true }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400': { $ref: '#/components/responses/BadRequestError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }
        '404': { $ref: '#/components/responses/NotFoundError' }

  /vat-rates:
    get:
      operationId: listVatRates
      tags: [VAT Rates]
      summary: List firm VAT rates
      description: |
        Returns the firm's custom `firm_vat` rows plus the full catalog of
        Romanian rates (`available`) the firm can enable, adjusted for the
        firm's VAT-payer type and the 2025-08-01 rate rules.
      responses:
        '200':
          description: VAT rates list
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [list] }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/VatRate' }
                  total: { type: integer }
                  available:
                    type: array
                    items:
                      type: object
                      properties:
                        key: { type: integer }
                        percent: { type: number }
                        description: { type: string }
                        ubl_category: { type: string }
                        reason: { type: string }
                  default_percent: { type: number }
        '401': { $ref: '#/components/responses/UnauthorizedError' }
    post:
      operationId: createVatRate
      tags: [VAT Rates]
      summary: Add a firm-scoped VAT rate
      description: |
        Creates (or returns the existing) `firm_vat` row for the given
        percent. A standard description from the Romanian catalog is applied
        when `description` is omitted. Non-VAT-payer firms receive
        `400 non_vat_payer`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [percent]
              properties:
                percent:
                  type: integer
                  minimum: 0
                  maximum: 100
                description:
                  type: string
      responses:
        '200':
          description: Rate returned (created or already present)
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [vat_rate] }
                  data: { $ref: '#/components/schemas/VatRate' }
                  created:
                    type: boolean
                    description: false when an equivalent rate already existed
        '400': { $ref: '#/components/responses/BadRequestError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /vat-rates/{id}:
    put:
      operationId: updateVatRate
      tags: [VAT Rates]
      summary: Update a VAT rate description
      description: Only `description` is mutable. `percent` is immutable because changing it would invalidate every bill line that references the rate.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: VAT rate CzUid
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                description: { type: string }
      responses:
        '200':
          description: Rate updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [vat_rate] }
                  data: { $ref: '#/components/schemas/VatRate' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }
        '404': { $ref: '#/components/responses/NotFoundError' }
    delete:
      operationId: deleteVatRate
      tags: [VAT Rates]
      summary: Delete a firm VAT rate
      description: Fails with `409 in_use` if the rate is still referenced by any bill or notice row.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Rate deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [vat_rate] }
                  deleted: { type: boolean }
        '409':
          description: Rate in use
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/NotFoundError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /currencies:
    get:
      operationId: listCurrencies
      tags: [Currencies]
      summary: List firm currencies
      description: Returns the firm's enabled currencies plus the `available` catalog of ISO-4217 codes Contazen supports.
      responses:
        '200':
          description: Currency list
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [list] }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Currency' }
                  total: { type: integer }
                  available:
                    type: array
                    items:
                      type: object
                      properties:
                        code: { type: string, example: EUR }
                        description: { type: string }
                  default_code: { type: string, example: RON }
        '401': { $ref: '#/components/responses/UnauthorizedError' }
    post:
      operationId: createCurrency
      tags: [Currencies]
      summary: Enable a currency for the firm
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              properties:
                code:
                  type: string
                  example: EUR
                  description: ISO-4217 three-letter code (uppercased server-side).
      responses:
        '200':
          description: Currency enabled or already present
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [currency] }
                  data: { $ref: '#/components/schemas/Currency' }
                  created: { type: boolean }
        '400':
          description: Invalid or unsupported currency
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /currencies/{id}:
    delete:
      operationId: deleteCurrency
      tags: [Currencies]
      summary: Disable a currency
      description: Fails with `409 in_use` if any bill or client still references the currency.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Currency CzUid
      responses:
        '200':
          description: Currency removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [currency] }
                  deleted: { type: boolean }
        '409':
          description: Currency in use
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/NotFoundError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /languages:
    get:
      operationId: listLanguages
      tags: [Languages]
      summary: List firm languages
      description: Returns the firm's enabled bill-template languages plus the `available` catalog of supported codes. Romanian (`ro`) is always enabled and cannot be removed.
      responses:
        '200':
          description: Language list
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [list] }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Language' }
                  total: { type: integer }
                  available:
                    type: array
                    items:
                      type: object
                      properties:
                        code: { type: string, example: en }
                        description: { type: string }
                  default_code: { type: string, example: ro }
        '401': { $ref: '#/components/responses/UnauthorizedError' }
    post:
      operationId: createLanguage
      tags: [Languages]
      summary: Enable a language for the firm
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              properties:
                code:
                  type: string
                  example: en
                  description: Two-letter lowercase ISO-639-1 code.
      responses:
        '200':
          description: Language enabled or already present
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [language] }
                  data: { $ref: '#/components/schemas/Language' }
                  created: { type: boolean }
        '400':
          description: Invalid or unsupported language
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /languages/{id}:
    delete:
      operationId: deleteLanguage
      tags: [Languages]
      summary: Disable a language
      description: Fails with `409 is_default` when removing `ro`, which is the hard-coded default.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
          description: Language CzUid
      responses:
        '200':
          description: Language removed
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  object: { type: string, enum: [language] }
                  deleted: { type: boolean }
        '409':
          description: Default language cannot be removed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/NotFoundError' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /accounting/profile:
    get:
      operationId: getFiscalProfile
      tags: [Conta]
      summary: Retrieve the fiscal profile
      description: |
        Returns the cached ANAF v9 PlatitorTVA snapshot for the authenticated
        firm's CUI. If the profile has never been synced, returns 404 with
        code `profile_not_synced` — call `POST /accounting/profile/sync` first.
      responses:
        '200':
          description: Fiscal profile snapshot
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/FiscalProfile' }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400':
          description: Firm has no CUI configured
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: Profile not synced yet
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /accounting/profile/sync:
    post:
      operationId: syncFiscalProfile
      tags: [Conta]
      summary: Sync the fiscal profile from ANAF
      description: |
        Triggers a fresh ANAF v9 lookup for the firm's CUI and upserts the
        cached `FiscalProfile`. Throttled at 1 request/second across all
        callers (UI, API, scripts).

        **Required permission**: `firm_accounting_sync`.
      responses:
        '200':
          description: Profile synced
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/FiscalProfile' }
                  message: { type: string, example: "Profil fiscal sincronizat." }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400':
          description: Firm has no CUI configured
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '502':
          description: ANAF sync failed (rate limit, network, or invalid response)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /accounting/balance-sheets:
    get:
      operationId: listBalanceSheets
      tags: [Conta]
      summary: List balance sheets
      description: |
        Returns all locally cached balance sheets for the authenticated firm,
        ordered by year DESC. Each item exposes the headline financial figures
        (cifra de afaceri, profit, capitaluri, datorii, salariați). For
        per-indicator detail call `GET /accounting/balance-sheets/{year}`.
      responses:
        '200':
          description: List of balance sheets
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/BalanceSheetList' }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400':
          description: Firm has no CUI configured
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /accounting/balance-sheets/{year}:
    get:
      operationId: getBalanceSheet
      tags: [Conta]
      summary: Retrieve a balance sheet for a specific year
      description: |
        Returns the cached balance sheet plus the full `indicators[]` array
        as returned by the ANAF Bilanț webservice. If the year hasn't been
        synced yet, returns 404 with code `year_not_synced` — call
        `POST /accounting/balance-sheets/sync` first.
      parameters:
        - name: year
          in: path
          required: true
          schema:
            type: integer
            minimum: 2014
          description: Calendar year (2014 onward).
      responses:
        '200':
          description: Balance sheet detail
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data: { $ref: '#/components/schemas/BalanceSheetDetail' }
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '400':
          description: Invalid year (out of supported range)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404':
          description: Year not synced yet
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }

  /accounting/balance-sheets/sync:
    post:
      operationId: syncBalanceSheet
      tags: [Conta]
      summary: Sync balance sheets from ANAF
      description: |
        Triggers a fresh ANAF Bilanț fetch. Three modes:

        - **Single year** (`year` provided): fetch one year. Returns the
          balance sheet, or `BalanceSheetSyncEmpty` if ANAF has not published
          that year yet.
        - **Backfill** (`backfill: true`): fetch a range of years (default
          `2014 → currentYear-1`). Returns `BalanceSheetBackfillResult` with
          stats. Throttled at ~1.05s per year (10 years ≈ 11s wall time).
        - **Default** (no `year`, no `backfill`): fetch the latest published
          year (currentYear-1, fallback currentYear-2).

        **Required permission**: `firm_accounting_sync`.

        **Note**: backfill ranges are clamped to 10 years per call to keep
        request duration bounded.
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                year:
                  type: integer
                  minimum: 2014
                  description: Sync only this single year.
                backfill:
                  type: boolean
                  description: When true, sync a range of years.
                from_year:
                  type: integer
                  minimum: 2014
                  description: Start of backfill range (inclusive). Default 2014.
                to_year:
                  type: integer
                  description: End of backfill range (inclusive). Default currentYear-1.
      responses:
        '200':
          description: Sync result. Shape varies by mode.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success: { type: boolean }
                  data:
                    oneOf:
                      - $ref: '#/components/schemas/BalanceSheet'
                      - $ref: '#/components/schemas/BalanceSheetSyncEmpty'
                      - $ref: '#/components/schemas/BalanceSheetBackfillResult'
                  meta: { $ref: '#/components/schemas/ResponseMeta' }
        '403':
          description: Insufficient permissions
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '502':
          description: ANAF sync failed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '401': { $ref: '#/components/responses/UnauthorizedError' }
