openapi: 3.0.3
info:
  title: e-Fiscal Cloud — API de Integración e-CF
  version: "1.2.0"
  description: >
    API para originar comprobantes fiscales electrónicos (e-CF) de la DGII desde
    un POS, ERP, e-commerce o software propio. e-Fiscal Cloud asigna la
    secuencia (e-NCF), firma el XML, lo transmite a la DGII y da seguimiento.
    El integrador solo envía la venta ya cerrada.


    Autenticación: dos mecanismos, ambos como `Authorization: Bearer`.
    (1) Connection key por sucursal (POS): se canjea por un token `ecft_…`.
    (2) API key de integrador (ERP/terceros): secreto `ik_live_…` con scopes y
    empresas permitidas, revocable.


    Manual de referencia: Manual de Integración — API e-CF de e-Fiscal Cloud v1.2.

    Cambios de la 1.2.0 respecto de la 1.1.0 (aditivos, sin romper clientes existentes):
    listado de sucursales con filtros y estado, identidad completa del documento
    (companyId, branchId, clientUuid), separación processingStatus / dgiiStatus,
    errorCode estable en errores y Retry-After en 429.

    Sistemas con conector o integración evaluada: POS con Connection Key por sucursal
    (ICG FrontRest, ICG FrontRetail, Ágora POS, PixelPoint) y plataformas con API Key de
    integrador (ICG Software, ICG Manager, Odoo, QuickBooks). El alcance de cada una está
    sujeto a evaluación técnica; las marcas pertenecen a sus titulares.
    e-Fiscal Cloud es una solución de KarmaTech Consulting.
  contact:
    name: Soporte e-Fiscal Cloud
    email: soporte@efiscalcloud.com
    url: https://efiscalcloud.com/integraciones
servers:
  - url: https://api.efiscalcloud.com
    description: e-Fiscal Cloud

tags:
  - name: Autenticación
  - name: Integrador
  - name: Emisión
  - name: Consulta
  - name: Compras
  - name: Estadísticas
  - name: RNC

paths:
  /api/v1/portal/keys/validate:
    post:
      tags: [Autenticación]
      summary: Activar una sucursal (canjea connection key por token del POS)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [key]
              properties:
                key: { type: string, description: Connection key de la sucursal }
      responses:
        "200":
          description: Token del POS
          content:
            application/json:
              schema:
                type: object
                properties:
                  token: { type: string, example: "ecft_mi-sucursal-001_..." }
        "401": { description: "Clave inválida o ya usada" }

  /api/v1/integrator/verify:
    get:
      tags: [Integrador]
      summary: Verificar una API key de integrador (scopes, empresas, estado)
      security:
        - integratorKey: []
      responses:
        "200":
          description: Contexto de la API key
          content:
            application/json:
              schema: { $ref: "#/components/schemas/IntegratorContext" }
        "401": { description: "API key revocada o inválida" }

  /api/v1/integrator/branches:
    get:
      tags: [Integrador]
      summary: Sucursales autorizadas a la API key (fuente de verdad del mapeo)
      description: >
        Requiere scope `ecf:emit`. Solo devuelve sucursales de las empresas de la credencial,
        nunca de otra marca. `branchCode` es exactamente el valor que `branchId` acepta junto
        con `companyId` en la emisión.
      security:
        - integratorKey: []
      parameters:
        - { name: companyId, in: query, schema: { type: string }, description: "Filtra por empresa" }
        - { name: environment, in: query, schema: { type: string, enum: [test, cert, prod] }, description: "Filtra por ambiente" }
      responses:
        "200":
          description: Sucursales autorizadas
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BranchList" }
        "401": { description: "Sin credencial o inválida" }
        "403": { description: "La API key no tiene el scope requerido" }

  /api/v1/ecf/branches:
    get:
      tags: [Autenticación]
      summary: "Sucursal(es) del token del POS"
      description: Devuelve la sucursal a la que pertenece el token `ecft_…`, con el mismo esquema que `/integrator/branches`.
      security:
        - posToken: []
      responses:
        "200":
          description: Sucursales del token
          content:
            application/json:
              schema: { $ref: "#/components/schemas/BranchList" }
        "401": { description: "Sin credencial o inválida" }

  /api/v1/ecf/emit:
    post:
      tags: [Emisión]
      summary: Emitir un e-CF desde el POS (venta ya cerrada)
      description: >
        Requiere token del POS (`ecft_…`). Respuesta asíncrona (202): estado
        técnico al emitir; el estado fiscal DGII se obtiene consultando
        (GET /api/v1/ecf/uuid/{clientUuid}). Un código de seguridad NO implica
        aceptación.
      security:
        - posToken: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EmitRequest" }
      responses:
        "200": { $ref: "#/components/responses/EmitAlreadyExisted" }
        "202": { $ref: "#/components/responses/EmitAccepted" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { description: "Autenticación inválida" }
        "403": { description: "Sin permiso para esta empresa/sucursal" }
        "409": { $ref: "#/components/responses/SequenceConflict" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /api/v1/integrator/ecf/emit:
    post:
      tags: [Emisión, Integrador]
      summary: Emitir un e-CF con API key de integrador
      description: >
        Mismo cuerpo y respuesta que /api/v1/ecf/emit. Requiere API key
        (`ik_live_…`) con scope `ecf:emit`. Las keys creadas desde el
        2026-11-04 exigen `companyId` + `branchId` (código de sucursal).
      security:
        - integratorKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/EmitRequest" }
      responses:
        "200": { $ref: "#/components/responses/EmitAlreadyExisted" }
        "202": { $ref: "#/components/responses/EmitAccepted" }
        "400": { $ref: "#/components/responses/BadRequest" }
        "401": { description: "API key de integrador inválida, ausente o revocada" }
        "403": { $ref: "#/components/responses/ScopeError" }
        "404": { $ref: "#/components/responses/BranchNotFound" }
        "409": { $ref: "#/components/responses/SequenceConflict" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /api/v1/ecf/uuid/{clientUuid}:
    get:
      tags: [Consulta]
      summary: Estado de un documento por clientUuid (recomendado)
      description: Solo documentos de las empresas/sucursales de la credencial; en otro caso 404. También disponible bajo /api/v1/integrator/ecf/uuid/{clientUuid}.
      security:
        - integratorKey: []
        - posToken: []
      parameters:
        - { name: clientUuid, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Documento
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EcfDocument" }
        "401": { description: "Sin credencial o inválida" }
        "404": { description: "No existe o no pertenece a tu alcance" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /api/v1/ecf/{documentId}:
    get:
      tags: [Consulta]
      summary: Estado de un documento por id
      security:
        - integratorKey: []
        - posToken: []
      parameters:
        - { name: documentId, in: path, required: true, schema: { type: integer } }
      responses:
        "200":
          description: Documento
          content:
            application/json:
              schema: { $ref: "#/components/schemas/EcfDocument" }
        "401": { description: "Sin credencial o inválida" }
        "404": { description: "No existe o no pertenece a tu alcance" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /api/v1/ecf/track/{trackId}:
    get:
      tags: [Consulta]
      summary: Estado por TrackID de la DGII (incluye companyId y companyRnc)
      security:
        - integratorKey: []
        - posToken: []
      parameters:
        - { name: trackId, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Estado del documento
          content:
            application/json:
              schema: { $ref: "#/components/schemas/TrackStatus" }
        "401": { description: "Sin credencial o inválida" }
        "404": { description: "No existe o no pertenece a tu alcance" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /api/v1/ecf:
    get:
      tags: [Consulta]
      summary: Listar documentos (acotado a tu credencial)
      security:
        - integratorKey: []
        - posToken: []
      parameters:
        - { name: companyId, in: query, schema: { type: string } }
        - { name: posTicketId, in: query, schema: { type: string } }
        - { name: encf, in: query, schema: { type: string } }
        - { name: status, in: query, schema: { $ref: "#/components/schemas/EcfStatus" } }
        - { name: ecfType, in: query, schema: { $ref: "#/components/schemas/EcfType" } }
        - { name: dateFrom, in: query, schema: { type: string, format: date } }
        - { name: dateTo, in: query, schema: { type: string, format: date } }
        - { name: environment, in: query, schema: { type: string, enum: [prod, cert, test, all], default: prod } }
        - { name: limit, in: query, schema: { type: integer, maximum: 200 } }
        - { name: offset, in: query, schema: { type: integer } }
      responses:
        "200":
          description: Documentos
          content:
            application/json:
              schema:
                type: object
                properties:
                  documents: { type: array, items: { $ref: "#/components/schemas/EcfDocument" } }
                  total: { type: integer }
        "401": { description: "Sin credencial o inválida" }
        "429": { $ref: "#/components/responses/RateLimited" }

  /api/v1/integrator/purchases:
    get:
      tags: [Compras]
      summary: Listar compras recibidas (e-CF de proveedores)
      description: Requiere scope `purchases:read`.
      security:
        - integratorKey: []
      parameters:
        - { name: estado, in: query, schema: { type: string, enum: [pendiente, aprobado, rechazado] } }
        - { name: ecfType, in: query, schema: { $ref: "#/components/schemas/EcfType" } }
        - { name: environment, in: query, schema: { type: string, enum: [prod, cert, test], default: prod } }
        - { name: limit, in: query, schema: { type: integer, maximum: 200 } }
        - { name: offset, in: query, schema: { type: integer } }
      responses:
        "200":
          description: Compras recibidas
          content:
            application/json:
              schema: { $ref: "#/components/schemas/PurchaseList" }
        "401": { description: "Sin credencial o inválida" }
        "403": { description: "La API key no tiene el scope requerido" }

  /api/v1/integrator/purchases/{encf}:
    get:
      tags: [Compras]
      summary: Detalle de una compra recibida (incluye XML)
      description: Requiere scope `purchases:read`.
      security:
        - integratorKey: []
      parameters:
        - { name: encf, in: path, required: true, schema: { type: string } }
      responses:
        "200":
          description: Detalle de la compra
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Purchase" }
        "401": { description: "Sin credencial o inválida" }
        "404": { description: "No existe o no pertenece a tu alcance" }

  /api/v1/integrator/purchases/{encf}/approve:
    post:
      tags: [Compras]
      summary: Aprobar comercialmente una compra (firma el ACECF)
      description: Requiere scope `purchases:approve`.
      security:
        - integratorKey: []
      parameters:
        - { name: encf, in: path, required: true, schema: { type: string } }
      responses:
        "200": { description: "Compra aprobada" }
        "401": { description: "Sin credencial o inválida" }
        "403": { description: "La API key no tiene el scope requerido" }
        "404": { description: "No existe o no pertenece a tu alcance" }

  /api/v1/integrator/purchases/{encf}/reject:
    post:
      tags: [Compras]
      summary: Rechazar comercialmente una compra (firma el ACECF)
      description: Requiere scope `purchases:approve`.
      security:
        - integratorKey: []
      parameters:
        - { name: encf, in: path, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [motivo]
              properties:
                motivo: { type: string }
      responses:
        "200": { description: "Compra rechazada" }
        "401": { description: "Sin credencial o inválida" }
        "403": { description: "La API key no tiene el scope requerido" }
        "404": { description: "No existe o no pertenece a tu alcance" }

  /api/v1/integrator/stats/documents:
    get:
      tags: [Estadísticas]
      summary: Contador de documentos por tipo (ventas y compras)
      description: Requiere scope `stats:read`. Acotado a las empresas de la key.
      security:
        - integratorKey: []
      parameters:
        - { name: from, in: query, schema: { type: string, format: date } }
        - { name: to, in: query, schema: { type: string, format: date } }
        - { name: environment, in: query, schema: { type: string, enum: [prod, cert, all], default: prod } }
        - { name: kind, in: query, schema: { type: string, enum: [all, sales, purchases], default: all } }
        - { name: ecfType, in: query, schema: { $ref: "#/components/schemas/EcfType" } }
      responses:
        "200":
          description: Conteo por tipo
          content:
            application/json:
              schema: { $ref: "#/components/schemas/DocumentStats" }
        "401": { description: "Sin credencial o inválida" }
        "403": { description: "La API key no tiene el scope requerido" }

  /api/v1/integrator/rnc/{rnc}:
    get:
      tags: [RNC]
      summary: Consulta exacta de RNC/Cédula en el padrón DGII
      description: Requiere scope `rnc:lookup`.
      security:
        - integratorKey: []
      parameters:
        - { name: rnc, in: path, required: true, schema: { type: string, pattern: "^([0-9]{9}|[0-9]{11})$" } }
      responses:
        "200":
          description: Contribuyente encontrado
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RncLookup" }
        "404":
          description: No encontrado
          content:
            application/json:
              schema:
                type: object
                properties:
                  found: { type: boolean, example: false }

  /api/v1/integrator/rnc/search:
    get:
      tags: [RNC]
      summary: Búsqueda de contribuyentes por nombre o prefijo de RNC
      description: Requiere scope `rnc:lookup`.
      security:
        - integratorKey: []
      parameters:
        - { name: q, in: query, required: true, schema: { type: string, minLength: 2 } }
        - { name: limit, in: query, schema: { type: integer, default: 20, maximum: 50 } }
      responses:
        "200":
          description: Resultados
          content:
            application/json:
              schema: { $ref: "#/components/schemas/RncSearch" }

components:
  securitySchemes:
    posToken:
      type: http
      scheme: bearer
      description: Token del POS (ecft_…) obtenido de /api/v1/portal/keys/validate
    integratorKey:
      type: http
      scheme: bearer
      description: API key de integrador (ik_live_…)

  responses:
    EmitAccepted:
      description: Documento recibido y firmado (o en cola); la DGII responde después
      content:
        application/json:
          schema: { $ref: "#/components/schemas/EmitResponse" }
    EmitAlreadyExisted:
      description: El posTicketId ya había sido emitido; se devuelve el documento existente (alreadyExisted = true)
      content:
        application/json:
          schema: { $ref: "#/components/schemas/EmitResponse" }
    BadRequest:
      description: Payload inválido (corregir y reenviar; no reintentar en bucle) o key nueva sin companyId (`COMPANY_ID_REQUIRED`)
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    BranchNotFound:
      description: "`BRANCH_NOT_FOUND` o `BRANCH_NOT_IN_COMPANY`: el código no existe en la empresa indicada, o la sucursal no pertenece a `companyId`"
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    ScopeError:
      description: "`CREDENTIAL_SCOPE` (sin el scope requerido o sin acceso a la empresa/sucursal)"
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    SequenceConflict:
      description: La empresa no tiene secuencia activa para el tipo o la secuencia se agotó
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }
    RateLimited:
      description: Límite de 30 peticiones por minuto alcanzado (emisión y consultas). Reintenta tras el tiempo de `Retry-After`; la emisión es idempotente por `clientUuid` / `posTicketId`.
      headers:
        Retry-After:
          description: Segundos a esperar antes de reintentar
          schema: { type: integer, example: 60 }
      content:
        application/json:
          schema: { $ref: "#/components/schemas/Error" }

  schemas:
    EcfType:
      type: string
      enum: ["31", "32", "33", "34", "41", "43", "44", "45", "46", "47"]

    EcfStatus:
      type: string
      enum: [queued, signed, sent, accepted, accepted_conditional, rejected, error, cancelled]

    Scope:
      type: string
      enum: ["ecf:emit", "purchases:read", "purchases:approve", "stats:read", "rnc:lookup"]

    IntegratorContext:
      type: object
      properties:
        ok: { type: boolean }
        name: { type: string }
        tenant: { type: string, example: efiscal, description: Marca a la que pertenece la key }
        scopes: { type: array, items: { $ref: "#/components/schemas/Scope" } }
        allowedCompanies: { type: array, items: { type: string } }
        allowedBranches: { type: array, items: { type: string } }

    Branch:
      type: object
      properties:
        active: { type: boolean, description: "La sucursal está habilitada para emitir" }
        branchId: { type: string, example: "EFACTURA-003", description: Id global (único) }
        branchCode: { type: string, example: "003", description: Código local (se repite entre empresas) }
        name: { type: string }
        companyId: { type: string, example: "mi-empresa" }
        companyName: { type: string }
        rnc: { type: string }
        environment: { type: string, enum: [test, cert, prod] }

    BranchList:
      type: object
      properties:
        branches: { type: array, items: { $ref: "#/components/schemas/Branch" } }

    EmitRequest:
      type: object
      required: [branchId, ecfType, items, subtotal, total]
      properties:
        companyId: { type: string, example: "mi-empresa", description: "Empresa. OBLIGATORIO con API key de integrador creada desde 2026-11-04; entonces branchId es el CÓDIGO de sucursal (p. ej. 001). No usar con token del POS." }
        branchId: { type: string, example: "001", description: "Código de sucursal (con companyId) o id global (token del POS / keys anteriores)." }
        ecfType: { $ref: "#/components/schemas/EcfType" }
        posTicketId: { type: string, description: Id del ticket en tu sistema (clave de idempotencia) }
        posOpenDate: { type: string, format: date, example: "2026-10-16" }
        clientUuid: { type: string, format: uuid, description: UUID determinístico por ticket }
        referenceEncf: { type: string, description: e-CF afectado (tipos 33/34) }
        referenceDate: { type: string, example: "15-10-2026", description: "Fecha del e-CF afectado (dd-MM-yyyy)" }
        buyer: { $ref: "#/components/schemas/Buyer" }
        items:
          type: array
          minItems: 1
          items: { $ref: "#/components/schemas/Item" }
        payments:
          type: array
          items: { $ref: "#/components/schemas/Payment" }
        subtotal: { type: number, description: Base del documento en DOP }
        taxItbis: { type: number, description: Total ITBIS en DOP }
        taxLaw: { type: number, description: "Propina legal (10 %) en DOP; no es base de ITBIS" }
        discount: { type: number }
        total: { type: number, description: "Subtotal + ITBIS + propina, en DOP" }
        withholdings: { $ref: "#/components/schemas/Withholding" }
        currency: { $ref: "#/components/schemas/Currency" }
        emisorOverride: { $ref: "#/components/schemas/EmisorOverride" }

    Buyer:
      type: object
      properties:
        rncCedula: { type: string, description: "9 dígitos (RNC) u 11 (cédula)" }
        name: { type: string }
        businessName: { type: string }
        email: { type: string, format: email }
        phone: { type: string }
        whatsappConsent: { type: boolean }
        foreignId: { type: string, description: "Identificador extranjero (46/47)" }
        country: { type: string, example: "US", description: "País del comprador extranjero (46/47)" }

    Item:
      type: object
      required: [lineNumber, productName, quantity, unitPrice, subtotal]
      properties:
        lineNumber: { type: integer }
        productName: { type: string }
        quantity: { type: number }
        unitPrice: { type: number, description: Precio neto (sin ITBIS) }
        discount: { type: number }
        itbisAmount: { type: number }
        itbisRate: { type: integer, example: 18 }
        subtotal: { type: number, description: Subtotal neto de la línea (sin ITBIS) }
        withholding: { $ref: "#/components/schemas/Withholding" }

    Withholding:
      type: object
      description: Retenciones (tipos 41 y 47)
      properties:
        itbisRetenido: { type: number }
        isrRetenido: { type: number }

    Currency:
      type: object
      description: Moneda del documento, sección OtraMoneda (tipo 46)
      properties:
        currencyIso: { type: string, example: "USD" }
        exchangeRate: { type: number, example: 58.0 }
        totalForeign: { type: number }

    EmisorOverride:
      type: object
      description: Dirección fiscal del emisor para esta venta (opcional)
      properties:
        address: { type: string }
        municipio: { type: string, example: "010100", description: Código DGII de 6 dígitos }
        provincia: { type: string, example: "010000", description: Código DGII de 6 dígitos }

    Payment:
      type: object
      required: [monto]
      properties:
        methodName: { type: string }
        formaPago: { type: string, enum: ["1", "2", "3", "4", "5", "6", "7", "8"] }
        monto: { type: number, description: Monto en DOP }
        change: { type: number }
        montoForeign: { type: number, description: Monto en moneda original (solo impresión) }
        changeForeign: { type: number }
        currencyIso: { type: string, example: "USD" }

    EmitResponse:
      type: object
      properties:
        status: { type: string, enum: [signed, queued], description: "Estado técnico al emitir. La respuesta de la DGII se obtiene consultando." }
        documentId: { type: integer }
        clientUuid: { type: string, format: uuid }
        encf: { type: string, example: "E320000000045" }
        companyRnc: { type: string }
        branchCode: { type: string, example: "001" }
        securityCode: { type: string }
        signatureDate: { type: string, example: "16-10-2026 10:15:30" }
        sequenceExpiry: { type: string }
        alreadyExisted: { type: boolean, description: "true (HTTP 200) si el posTicketId ya había sido emitido." }

    DgiiResponse:
      type: object
      properties:
        codigo: { type: string, enum: ["1", "2", "3", "4"], description: "1 Aceptado · 2 Rechazado · 3 En proceso · 4 Aceptado condicional" }
        estado: { type: string }
        mensajes:
          type: array
          items:
            type: object
            properties:
              valor: { type: string }
              codigo: { type: string }

    EcfDocument:
      type: object
      description: >
        Documento emitido. El e-NCF se repite entre empresas: usa `companyId` + `branchId`
        para identificar al emisor antes de aplicar un resultado.
      properties:
        id: { type: integer }
        clientUuid: { type: string, format: uuid }
        encf: { type: string }
        companyId: { type: string, description: "Empresa emisora" }
        branchId: { type: string, description: "Código de sucursal dentro de la empresa" }
        ecfType: { $ref: "#/components/schemas/EcfType" }
        status: { $ref: "#/components/schemas/EcfStatus" }
        processingStatus: { type: string, enum: [queued, signed, sent, error], description: "Estado técnico (firma y envío)" }
        dgiiStatus: { type: string, enum: [pending, accepted, accepted_conditional, rejected], description: "Estado fiscal según la DGII; la aceptación solo se confirma aquí" }
        errors: { type: array, items: { type: string } }
        warnings: { type: array, items: { type: string } }
        trackId: { type: string, nullable: true }
        securityCode: { type: string }
        environment: { type: string, enum: [test, cert, prod] }
        dgiiResponse: { $ref: "#/components/schemas/DgiiResponse" }

    TrackStatus:
      type: object
      properties:
        trackId: { type: string }
        encf: { type: string }
        status: { $ref: "#/components/schemas/EcfStatus" }
        companyId: { type: string }
        companyRnc: { type: string }
        dgiiResponse: { $ref: "#/components/schemas/DgiiResponse" }

    Purchase:
      type: object
      description: Compra recibida. Estructura completa por confirmar en el contrato.
      additionalProperties: true
      properties:
        encf: { type: string }
        ecfType: { $ref: "#/components/schemas/EcfType" }
        estado: { type: string, enum: [pendiente, aprobado, rechazado] }

    PurchaseList:
      type: object
      description: Listado de compras recibidas. Estructura completa por confirmar en el contrato.
      additionalProperties: true

    StatsRow:
      type: object
      properties:
        ecfType: { $ref: "#/components/schemas/EcfType" }
        name: { type: string }
        salesCount: { type: integer }
        salesTotal: { type: number }
        purchasesCount: { type: integer }
        purchasesTotal: { type: number }
        count: { type: integer }
        total: { type: number }

    DocumentStats:
      type: object
      properties:
        range:
          type: object
          properties:
            from: { type: string, format: date }
            to: { type: string, format: date }
            environment: { type: string }
            kind: { type: string }
        rows: { type: array, items: { $ref: "#/components/schemas/StatsRow" } }
        totals:
          type: object
          properties:
            salesCount: { type: integer }
            purchasesCount: { type: integer }
            count: { type: integer }
            salesTotal: { type: number }
            purchasesTotal: { type: number }
            total: { type: number }

    RncLookup:
      type: object
      properties:
        found: { type: boolean }
        contribuyente:
          type: object
          properties:
            rnc: { type: string }
            razonSocial: { type: string }
            estado: { type: string }
            actividadEconomica: { type: string }

    RncSearch:
      type: object
      properties:
        results:
          type: array
          items:
            type: object
            properties:
              rnc: { type: string }
              razonSocial: { type: string }
              estado: { type: string }
        count: { type: integer }
        query: { type: string }

    ErrorCode:
      type: string
      description: Código estable para que los sistemas muestren su propio mensaje sin interpretar texto libre.
      enum: [BRANCH_NOT_FOUND, COMPANY_ID_REQUIRED, BRANCH_NOT_IN_COMPANY, CREDENTIAL_SCOPE, RATE_LIMITED]

    Error:
      type: object
      description: Error de la API. Incluye `error` (texto), `errorCode` (estable) y, en errores de validación (400), `details`.
      additionalProperties: true
      properties:
        error: { type: string }
        errorCode: { $ref: "#/components/schemas/ErrorCode" }
        details: {}
