{
  "openapi": "3.0.3",
  "info": {
    "title": "P&S2B ADN Gateway Multiempresa",
    "version": "2.2.0",
    "description": "Gateway seguro para consultas ao ADN da NFS-e e distribuição de NF-e modelo 55 com certificados A1 de múltiplas empresas. Use X-API-Key nos endpoints operacionais. Os endpoints administrativos são restritos ao Appsmith e à equipe de TI."
  },
  "servers": [{ "url": "https://adn-gateway.pes2b.com", "description": "Produção" }],
  "tags": [
    { "name": "Status" },
    { "name": "ADN" },
    { "name": "NF-e" },
    { "name": "Administração - Empresas" },
    { "name": "Administração - Certificados" }
  ],
  "paths": {
    "/health": {
      "get": {
        "tags": ["Status"], "summary": "Verificar disponibilidade", "operationId": "health",
        "responses": { "200": { "description": "Serviço operacional", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Health" } } } } }
      }
    },
    "/adn/consultar-dfe": {
      "post": {
        "tags": ["ADN"], "summary": "Consultar DFe no ADN", "operationId": "consultarDfe", "security": [{ "ApiKeyAuth": [] }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ConsultaDfeRequest" }, "example": { "empresa_codigo": "JORGEPLA_CONTABILIDADE", "cnpj_consulta": "10576541000116", "nsu": 2144 } } } },
        "responses": {
          "200": { "description": "Consulta realizada", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ConsultaDfeResponse" } } } },
          "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "$ref": "#/components/responses/UnauthorizedApiKey" },
          "422": { "$ref": "#/components/responses/Unprocessable" }, "503": { "$ref": "#/components/responses/Unavailable" }
        }
      }
    },
    "/nfe/distribuicao-dfe": {
      "post": {
        "tags": ["NF-e"],
        "summary": "Distribuir DF-e de NF-e por último NSU",
        "description": "Executa exatamente uma chamada ao NFeDistribuicaoDFe na modalidade distNSU. Não controla cursor, não faz loop, não persiste e não descompacta docZip.",
        "operationId": "distribuirNfePorNsu",
        "security": [{ "ApiKeyAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/NfeDistribuicaoRequest" },
              "example": { "empresa_codigo": "JORGEPLA_CONTABILIDADE", "cnpj_consulta": "10576541000116", "ult_nsu": "000000000000000" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Resposta fiscal da SEFAZ, inclusive quando não há documentos ou quando há rejeição fiscal",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/NfeDistribuicaoResponse" } } }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/UnauthorizedApiKey" },
          "404": { "description": "Certificado da empresa não encontrado", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TechnicalError" } } } },
          "422": { "$ref": "#/components/responses/Unprocessable" },
          "502": { "description": "Erro técnico na comunicação com o Ambiente Nacional", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TechnicalError" } } } },
          "503": { "$ref": "#/components/responses/Unavailable" }
        }
      }
    },
    "/admin/empresas": {
      "get": {
        "tags": ["Administração - Empresas"], "summary": "Listar empresas", "security": [{ "AdminBearer": [] }],
        "responses": { "200": { "description": "Empresas cadastradas", "content": { "application/json": { "schema": { "type": "object", "properties": { "sucesso": { "type": "boolean" }, "empresas": { "type": "array", "items": { "$ref": "#/components/schemas/Empresa" } } } } } } }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" } }
      },
      "post": {
        "tags": ["Administração - Empresas"], "summary": "Cadastrar empresa", "security": [{ "AdminBearer": [] }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/EmpresaInput" } } } },
        "responses": { "201": { "description": "Empresa cadastrada" }, "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "409": { "description": "Conflito de cadastro" } }
      }
    },
    "/admin/empresas/sugerir-codigo": {
      "get": {
        "tags": ["Administração - Empresas"], "summary": "Sugerir código automático", "security": [{ "AdminBearer": [] }],
        "parameters": [{ "name": "nome", "in": "query", "required": true, "schema": { "type": "string" } }],
        "responses": { "200": { "description": "Código sugerido", "content": { "application/json": { "schema": { "type": "object", "properties": { "sucesso": { "type": "boolean" }, "codigo": { "type": "string" } } } } } }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" } }
      }
    },
    "/admin/empresas/{codigo}": {
      "parameters": [{ "$ref": "#/components/parameters/CodigoEmpresa" }],
      "get": { "tags": ["Administração - Empresas"], "summary": "Consultar empresa", "security": [{ "AdminBearer": [] }], "responses": { "200": { "description": "Empresa encontrada" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "404": { "description": "Empresa não encontrada" } } },
      "patch": { "tags": ["Administração - Empresas"], "summary": "Editar empresa", "security": [{ "AdminBearer": [] }], "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/EmpresaInput" } } } }, "responses": { "200": { "description": "Empresa atualizada" }, "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "404": { "description": "Empresa não encontrada" }, "409": { "description": "Código não pode ser alterado" } } }
    },
    "/admin/empresas/{codigo}/ativar-captura": {
      "post": { "tags": ["Administração - Empresas"], "summary": "Ativar captura", "security": [{ "AdminBearer": [] }], "parameters": [{ "$ref": "#/components/parameters/CodigoEmpresa" }], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "origem": { "type": "string", "enum": ["CARGA_HISTORICA", "INCREMENTAL"], "default": "CARGA_HISTORICA" } } } } } }, "responses": { "200": { "description": "Captura ativada" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "409": { "description": "Modo ainda não disponível" } } }
    },
    "/admin/empresas/{codigo}/pausar-captura": {
      "post": { "tags": ["Administração - Empresas"], "summary": "Pausar captura", "security": [{ "AdminBearer": [] }], "parameters": [{ "$ref": "#/components/parameters/CodigoEmpresa" }], "responses": { "200": { "description": "Captura pausada" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "404": { "description": "Empresa não encontrada" } } }
    },
    "/admin/empresas/{codigo}/inativar": {
      "post": { "tags": ["Administração - Empresas"], "summary": "Inativar empresa", "security": [{ "AdminBearer": [] }], "parameters": [{ "$ref": "#/components/parameters/CodigoEmpresa" }], "responses": { "200": { "description": "Empresa inativada" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "404": { "description": "Empresa não encontrada" } } }
    },
    "/admin/certificados": {
      "get": { "tags": ["Administração - Certificados"], "summary": "Listar certificados", "security": [{ "AdminBearer": [] }], "responses": { "200": { "description": "Certificados sem senhas ou arquivos privados" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" } } },
      "post": { "tags": ["Administração - Certificados"], "summary": "Cadastrar certificado", "security": [{ "AdminBearer": [] }], "requestBody": { "$ref": "#/components/requestBodies/CertificateUpload" }, "responses": { "201": { "description": "Certificado cadastrado" }, "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "422": { "$ref": "#/components/responses/Unprocessable" } } }
    },
    "/admin/certificados/{empresa}": {
      "get": { "tags": ["Administração - Certificados"], "summary": "Listar certificados de uma empresa", "security": [{ "AdminBearer": [] }], "parameters": [{ "$ref": "#/components/parameters/Empresa" }], "responses": { "200": { "description": "Certificados da empresa" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" } } }
    },
    "/admin/certificados/{empresa}/substituir": {
      "post": { "tags": ["Administração - Certificados"], "summary": "Substituir certificado ativo", "security": [{ "AdminBearer": [] }], "parameters": [{ "$ref": "#/components/parameters/Empresa" }], "requestBody": { "$ref": "#/components/requestBodies/CertificateUploadReplacement" }, "responses": { "201": { "description": "Certificado substituído" }, "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "422": { "$ref": "#/components/responses/Unprocessable" } } }
    },
    "/admin/certificados/{empresa}/testar": {
      "post": { "tags": ["Administração - Certificados"], "summary": "Testar certificado no ADN", "security": [{ "AdminBearer": [] }], "parameters": [{ "$ref": "#/components/parameters/Empresa" }], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "required": ["cnpj_consulta", "nsu"], "properties": { "cnpj_consulta": { "type": "string", "pattern": "^[0-9]{14}$" }, "nsu": { "type": "integer", "minimum": 0 }, "finalidade": { "type": "string", "default": "ADN_DFE" } } } } } }, "responses": { "200": { "description": "Teste realizado" }, "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "$ref": "#/components/responses/UnauthorizedAdmin" }, "422": { "$ref": "#/components/responses/Unprocessable" } } }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": { "type": "apiKey", "in": "header", "name": "X-API-Key", "description": "Chave operacional para integrações como o n8n." },
      "AdminBearer": { "type": "http", "scheme": "bearer", "bearerFormat": "token", "description": "Token administrativo restrito ao Appsmith e à TI." }
    },
    "parameters": {
      "CodigoEmpresa": { "name": "codigo", "in": "path", "required": true, "schema": { "type": "string" } },
      "Empresa": { "name": "empresa", "in": "path", "required": true, "schema": { "type": "string" } }
    },
    "schemas": {
      "Health": { "type": "object", "properties": { "ok": { "type": "boolean", "example": true }, "service": { "type": "string", "example": "adn-gateway-multiempresa" }, "version": { "type": "string", "example": "2.2.0" }, "status": { "type": "string", "example": "running" } } },
      "ConsultaDfeRequest": { "type": "object", "required": ["empresa_codigo", "cnpj_consulta", "nsu"], "properties": { "empresa_codigo": { "type": "string", "example": "JORGEPLA_CONTABILIDADE" }, "cnpj_consulta": { "type": "string", "pattern": "^[0-9]{14}$", "example": "10576541000116" }, "nsu": { "type": "integer", "minimum": 0, "example": 2144 } } },
      "ConsultaDfeResponse": { "type": "object", "properties": { "sucesso": { "type": "boolean", "example": true }, "empresa_codigo": { "type": "string" }, "nsu": { "type": "integer" }, "data": { "type": "object", "additionalProperties": true } } },
      "NfeDistribuicaoRequest": {
        "type": "object",
        "required": ["empresa_codigo", "cnpj_consulta", "ult_nsu"],
        "properties": {
          "empresa_codigo": { "type": "string", "example": "JORGEPLA_CONTABILIDADE" },
          "cnpj_consulta": { "type": "string", "pattern": "^[0-9]{14}$", "example": "10576541000116" },
          "ult_nsu": { "type": "string", "pattern": "^[0-9]{15}$", "example": "000000000000000" }
        }
      },
      "NfeDocumentoDistribuido": {
        "type": "object",
        "required": ["nsu", "schema", "docZip"],
        "properties": {
          "nsu": { "type": "string", "example": "000000000000121" },
          "schema": { "type": "string", "example": "resNFe_v1.01.xsd" },
          "docZip": { "type": "string", "format": "byte", "description": "Base64 compactado exatamente como entregue pela SEFAZ; não é descompactado pelo gateway." }
        }
      },
      "NfeDistribuicaoResponse": {
        "type": "object",
        "required": ["success", "cStat", "xMotivo", "documentos"],
        "properties": {
          "success": { "type": "boolean", "example": true, "description": "Indica que houve resposta fiscal da SEFAZ, ainda que cStat represente rejeição." },
          "cStat": { "type": "string", "example": "138" },
          "xMotivo": { "type": "string", "example": "Documento(s) localizado(s)" },
          "ultNSU": { "type": "string", "nullable": true, "example": "000000000000123" },
          "maxNSU": { "type": "string", "nullable": true, "example": "000000000000456" },
          "documentos": { "type": "array", "items": { "$ref": "#/components/schemas/NfeDocumentoDistribuido" } }
        }
      },
      "Empresa": { "type": "object", "additionalProperties": true, "properties": { "codigo": { "type": "string" }, "razao_social": { "type": "string" }, "nome_fantasia": { "type": "string", "nullable": true }, "cnpj": { "type": "string" }, "ativo": { "type": "boolean" }, "captura_ativa": { "type": "boolean" }, "modo_captura": { "type": "string", "enum": ["compartilhado", "dedicado"] }, "tipo_estabelecimento": { "type": "string", "enum": ["MATRIZ", "FILIAL"] }, "matriz_codigo": { "type": "string", "nullable": true }, "usa_certificado_matriz": { "type": "boolean" } } },
      "EmpresaInput": { "type": "object", "required": ["razao_social", "cnpj", "modo_captura", "tipo_estabelecimento"], "properties": { "razao_social": { "type": "string" }, "nome_fantasia": { "type": "string" }, "cnpj": { "type": "string", "pattern": "^[0-9]{14}$" }, "ativo": { "type": "boolean", "default": true }, "codigo_dominio": { "type": "string" }, "apelido_dominio": { "type": "string" }, "modo_captura": { "type": "string", "enum": ["compartilhado", "dedicado"] }, "captura_ativa": { "type": "boolean", "default": false }, "tipo_estabelecimento": { "type": "string", "enum": ["MATRIZ", "FILIAL"] }, "matriz_codigo": { "type": "string" }, "usa_certificado_matriz": { "type": "boolean", "default": false } } },
      "Error": { "type": "object", "properties": { "sucesso": { "type": "boolean", "example": false }, "erro": { "type": "string" }, "codigo": { "type": "string", "nullable": true } } },
      "TechnicalError": { "type": "object", "properties": { "success": { "type": "boolean", "example": false }, "error": { "type": "object", "properties": { "code": { "type": "string", "example": "NFE_DISTRIBUICAO_ERROR" }, "message": { "type": "string", "example": "Nao foi possivel consultar a distribuicao de NF-e" } } } } }
    },
    "requestBodies": {
      "CertificateUpload": { "required": true, "content": { "multipart/form-data": { "schema": { "type": "object", "required": ["empresa_codigo", "empresa_cnpj", "senha", "arquivo"], "properties": { "empresa_codigo": { "type": "string" }, "empresa_cnpj": { "type": "string", "pattern": "^[0-9]{14}$" }, "razao_social": { "type": "string" }, "finalidade": { "type": "string", "default": "ADN_DFE" }, "senha": { "type": "string", "format": "password", "writeOnly": true }, "arquivo": { "type": "string", "format": "binary" } } } } } },
      "CertificateUploadReplacement": { "required": true, "content": { "multipart/form-data": { "schema": { "type": "object", "required": ["empresa_cnpj", "senha", "arquivo"], "properties": { "empresa_cnpj": { "type": "string", "pattern": "^[0-9]{14}$" }, "razao_social": { "type": "string" }, "finalidade": { "type": "string", "default": "ADN_DFE" }, "senha": { "type": "string", "format": "password", "writeOnly": true }, "arquivo": { "type": "string", "format": "binary" } } } } } }
    },
    "responses": {
      "BadRequest": { "description": "Requisição inválida", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "UnauthorizedApiKey": { "description": "X-API-Key ausente ou inválida", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" }, "example": { "sucesso": false, "erro": "API Key ausente ou invalida", "codigo": "API_KEY_INVALIDA" } } } },
      "UnauthorizedAdmin": { "description": "Bearer token administrativo ausente ou inválido", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Unprocessable": { "description": "Certificado ou consulta não processável", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Unavailable": { "description": "Serviço ou autenticação indisponível", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
    }
  }
}
