{
  "openapi": "3.0.3",
  "info": {
    "title": "PES2B Contábil Parser API",
    "version": "1.1.0",
    "description": "API para análise, diagnóstico e importação de planilhas contábeis XLSX/XLS de grande volume. O serviço evita transportar centenas de milhares de linhas pelo n8n e concentra leitura, validação, diagnóstico e persistência no backend."
  },
  "servers": [
    {
      "url": "https://contabil-parser.pes2b.com",
      "description": "Produção"
    }
  ],
  "tags": [
    {
      "name": "Status",
      "description": "Disponibilidade do serviço"
    },
    {
      "name": "Análise",
      "description": "Leitura e diagnóstico sem gravação"
    },
    {
      "name": "Importação",
      "description": "Processamento com persistência no PostgreSQL"
    }
  ],
  "paths": {
    "/health": {
      "get": {
        "tags": [
          "Status"
        ],
        "summary": "Verifica a disponibilidade do parser",
        "operationId": "health",
        "responses": {
          "200": {
            "description": "Serviço disponível",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthResponse"
                }
              }
            }
          }
        }
      }
    },
    "/v1/analyze": {
      "post": {
        "tags": [
          "Análise"
        ],
        "summary": "Analisa uma planilha sem gravar no banco",
        "description": "Calcula hash, totais, datas, tipos, quantidade de movimentos financeiros e lotes desbalanceados. Não cria importação e não grava movimentos.",
        "operationId": "analyzeWorkbook",
        "security": [
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "file"
                ],
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary",
                    "description": "Planilha XLSX ou XLS"
                  },
                  "batch_size": {
                    "type": "integer",
                    "minimum": 100,
                    "maximum": 10000,
                    "default": 1000,
                    "description": "Tamanho lógico de batch usado no resumo"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Análise concluída",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/AnalyzeResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/diagnose-unbalanced": {
      "post": {
        "tags": [
          "Análise"
        ],
        "summary": "Diagnostica grupos contábeis desbalanceados",
        "description": "Analisa a planilha sem gravar no banco e retorna somente os grupos id_movim_finan desbalanceados, incluindo as linhas originais que compõem cada grupo.",
        "operationId": "diagnoseUnbalanced",
        "security": [
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "file"
                ],
                "properties": {
                  "file": {
                    "type": "string",
                    "format": "binary",
                    "description": "Planilha XLSX ou XLS"
                  },
                  "batch_size": {
                    "type": "integer",
                    "minimum": 100,
                    "maximum": 10000,
                    "default": 1000
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Diagnóstico concluído",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DiagnoseResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          }
        }
      }
    },
    "/v1/process": {
      "post": {
        "tags": [
          "Importação"
        ],
        "summary": "Processa e grava uma importação contábil",
        "description": "Analisa o arquivo, valida balanceamento e duplicidade, cria a importação, grava movimentos em batches, valida os totais e finaliza a carga. Em REIMPORTAR, a importação anterior é marcada como SUBSTITUIDO somente após a nova carga ser validada.",
        "operationId": "processWorkbook",
        "security": [
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "multipart/form-data": {
              "schema": {
                "type": "object",
                "required": [
                  "codigo_dominio",
                  "file"
                ],
                "properties": {
                  "codigo_dominio": {
                    "type": "string",
                    "description": "Código da empresa no Domínio",
                    "example": "469"
                  },
                  "modo_importacao": {
                    "type": "string",
                    "enum": [
                      "NORMAL",
                      "REIMPORTAR"
                    ],
                    "default": "NORMAL"
                  },
                  "batch_size": {
                    "type": "integer",
                    "minimum": 100,
                    "maximum": 10000,
                    "default": 1000
                  },
                  "file": {
                    "type": "string",
                    "format": "binary",
                    "description": "Planilha XLSX ou XLS"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Importação concluída e validada",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ProcessResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "description": "Empresa não cadastrada",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "example": {
                  "detail": "Empresa não cadastrada."
                }
              }
            }
          },
          "409": {
            "description": "Conflito de empresa ou importação",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "422": {
            "description": "Arquivo desbalanceado ou dados inválidos",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ErrorResponse"
                },
                "examples": {
                  "desbalanceado": {
                    "value": {
                      "detail": "Arquivo desbalanceado: -196210.0."
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key",
        "description": "API Key configurada no ambiente do serviço"
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Parâmetros ou formato inválidos",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            }
          }
        }
      },
      "Unauthorized": {
        "description": "API key inválida ou ausente",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            },
            "example": {
              "detail": "API key inválida ou ausente."
            }
          }
        }
      },
      "PayloadTooLarge": {
        "description": "Arquivo acima do limite configurado",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/ErrorResponse"
            }
          }
        }
      }
    },
    "schemas": {
      "HealthResponse": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "example": true
          },
          "service": {
            "type": "string",
            "example": "PES2B Contabil Parser"
          },
          "environment": {
            "type": "string",
            "example": "production"
          }
        }
      },
      "AnalyzeResponse": {
        "type": "object",
        "required": [
          "success",
          "file_name",
          "sha256",
          "total_rows",
          "total_debit",
          "total_credit",
          "difference"
        ],
        "properties": {
          "success": {
            "type": "boolean"
          },
          "file_name": {
            "type": "string"
          },
          "sha256": {
            "type": "string"
          },
          "total_rows": {
            "type": "integer"
          },
          "total_batches": {
            "type": "integer"
          },
          "total_debit": {
            "type": "number",
            "format": "double"
          },
          "total_credit": {
            "type": "number",
            "format": "double"
          },
          "difference": {
            "type": "number",
            "format": "double"
          },
          "distinct_id_movim_finan": {
            "type": "integer"
          },
          "min_date": {
            "type": "string",
            "format": "date",
            "nullable": true
          },
          "max_date": {
            "type": "string",
            "format": "date",
            "nullable": true
          },
          "types": {
            "type": "object",
            "additionalProperties": {
              "type": "integer"
            }
          },
          "rows_with_both_debit_credit": {
            "type": "integer"
          },
          "rows_without_values": {
            "type": "integer"
          },
          "unbalanced_lots": {
            "type": "integer"
          }
        }
      },
      "DiagnosticSummary": {
        "type": "object",
        "properties": {
          "total_linhas": {
            "type": "integer"
          },
          "total_movimentos_financeiros": {
            "type": "integer"
          },
          "total_debito": {
            "type": "number"
          },
          "total_credito": {
            "type": "number"
          },
          "diferenca": {
            "type": "number"
          },
          "quantidade_grupos_desbalanceados": {
            "type": "integer"
          },
          "total_batches": {
            "type": "integer"
          }
        }
      },
      "DiagnosticLine": {
        "type": "object",
        "properties": {
          "linha_origem": {
            "type": "integer"
          },
          "tipo_origem": {
            "type": "string",
            "nullable": true
          },
          "id_conta": {
            "type": "integer",
            "nullable": true
          },
          "id_planejamento": {
            "type": "integer",
            "nullable": true
          },
          "descricao_origem": {
            "type": "string",
            "nullable": true
          },
          "valor_debito": {
            "type": "number"
          },
          "valor_credito": {
            "type": "number"
          },
          "historico_origem": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "DiagnosticGroup": {
        "type": "object",
        "properties": {
          "id_movim_finan": {
            "type": "integer"
          },
          "data": {
            "type": "string",
            "format": "date",
            "nullable": true
          },
          "total_debito": {
            "type": "number"
          },
          "total_credito": {
            "type": "number"
          },
          "diferenca": {
            "type": "number"
          },
          "quantidade_linhas": {
            "type": "integer"
          },
          "descricao_origem": {
            "type": "string",
            "nullable": true
          },
          "historico_origem": {
            "type": "string",
            "nullable": true
          },
          "linhas": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DiagnosticLine"
            }
          }
        }
      },
      "DiagnoseResponse": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean"
          },
          "diagnostico": {
            "type": "string",
            "enum": [
              "ARQUIVO_DESBALANCEADO",
              "ARQUIVO_BALANCEADO"
            ]
          },
          "nome_arquivo": {
            "type": "string"
          },
          "sha256": {
            "type": "string"
          },
          "resumo": {
            "$ref": "#/components/schemas/DiagnosticSummary"
          },
          "grupos_desbalanceados": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DiagnosticGroup"
            }
          }
        }
      },
      "ProcessResponse": {
        "allOf": [
          {
            "$ref": "#/components/schemas/AnalyzeResponse"
          },
          {
            "type": "object",
            "properties": {
              "importacao_id": {
                "type": "string",
                "format": "uuid"
              },
              "empresa_id": {
                "type": "string",
                "format": "uuid"
              },
              "codigo_dominio": {
                "type": "string"
              },
              "modo_importacao": {
                "type": "string",
                "enum": [
                  "NORMAL",
                  "REIMPORTAR"
                ]
              },
              "replaced_importacao_id": {
                "type": "string",
                "format": "uuid",
                "nullable": true
              },
              "inserted_rows": {
                "type": "integer"
              },
              "status": {
                "type": "string",
                "example": "VALIDADO"
              }
            }
          }
        ]
      },
      "ErrorResponse": {
        "type": "object",
        "properties": {
          "detail": {
            "description": "Detalhe do erro. Pode ser string ou objeto.",
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "object",
                "additionalProperties": true
              }
            ]
          }
        }
      }
    }
  }
}