MVP
N/A

Sem data

🔗 Contratos de Integração MVP — AegisTech IA

Contratos OpenAPI 3.1 para integração com sistemas externos dos pilares institucionais


📋 Índice

  1. Visão Geral
  2. Contratos por Pilar
  3. Especificações OpenAPI
  4. Webhooks e Eventos
  5. Versionamento e Compatibilidade
  6. Políticas de Erro

1. Visão Geral

Objetivo

Definir contratos padronizados para integração do MVP com sistemas externos dos 4 pilares institucionais, garantindo interoperabilidade, segurança e compliance LGPD/CNMP.

Padrões Adotados

  • OpenAPI 3.1: Especificação de APIs REST
  • JSON Schema: Validação de dados
  • JWT: Autenticação e autorização
  • Webhooks: Notificações assíncronas
  • Idempotência: Operações seguras para retry

Camadas de Integração

Carregando diagrama...

2. Contratos por Pilar

2.1 Ministério Público - PJe Integration

Endpoint Principal

POST /api/v1/mp/manifestations

Request Schema

ManifestationMP:
  type: object
  required:
    - id
    - tipo
    - conteudo
    - prioridade
    - metadata
  properties:
    id:
      type: string
      format: uuid
      description: "ID único da manifestação"
    tipo:
      type: string
      enum: [denuncia, solicitacao, reclamacao, elogio]
      description: "Tipo da manifestação"
    conteudo:
      type: object
      properties:
        texto:
          type: string
          maxLength: 10000
        resumo:
          type: string
          maxLength: 500
        entidades:
          type: array
          items:
            $ref: '#/components/schemas/Entity'
    prioridade:
      type: object
      properties:
        score:
          type: number
          minimum: 0
          maximum: 100
        motivo:
          type: string
          description: "Explicação da priorização"
    metadata:
      type: object
      properties:
        tenant:
          type: string
          description: "Identificador do órgão MP"
        timestamp:
          type: string
          format: date-time
        hashMidia:
          type: string
          description: "Hash SHA-256 da mídia processada"
        traceId:
          type: string
          description: "ID de rastreamento distribuído"

Response Schema

ManifestationResponse:
  type: object
  properties:
    success:
      type: boolean
    data:
      type: object
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          enum: [aceito, rejeitado, pendente]
        processoId:
          type: string
          description: "ID do processo no PJe (se aplicável)"
        observacoes:
          type: string
    errors:
      type: array
      items:
        $ref: '#/components/schemas/Error'

2.2 Estados/Municípios - e-SUS Integration

Endpoint Principal

POST /api/v1/gov/policies

Request Schema

PolicyManifestation:
  type: object
  required:
    - id
    - categoria
    - conteudo
    - localizacao
    - metadata
  properties:
    id:
      type: string
      format: uuid
    categoria:
      type: string
      enum: [saude, educacao, infraestrutura, assistencia_social, seguranca]
    conteudo:
      type: object
      properties:
        titulo:
          type: string
          maxLength: 200
        descricao:
          type: string
          maxLength: 5000
        impacto:
          type: string
          enum: [baixo, medio, alto, critico]
    localizacao:
      type: object
      properties:
        uf:
          type: string
          pattern: '^[A-Z]{2}$'
        municipio:
          type: string
        bairro:
          type: string
        coordenadas:
          type: object
          properties:
            lat:
              type: number
              format: float
            lng:
              type: number
              format: float
    metadata:
      type: object
      properties:
        tenant:
          type: string
        secretaria:
          type: string
        timestamp:
          type: string
          format: date-time

2.3 Polícia Militar - SINESP Integration

Endpoint Principal

POST /api/v1/pm/occurrences

Request Schema

OccurrencePM:
  type: object
  required:
    - id
    - tipo
    - gravidade
    - localizacao
    - metadata
  properties:
    id:
      type: string
      format: uuid
    tipo:
      type: string
      enum: [furto, roubo, agressao, trafico, acidente, disturbio]
    gravidade:
      type: string
      enum: [baixa, media, alta, critica]
    localizacao:
      type: object
      properties:
        endereco:
          type: string
        bairro:
          type: string
        coordenadas:
          type: object
          properties:
            lat:
              type: number
              format: float
            lng:
              type: number
              format: float
    contexto:
      type: object
      properties:
        descricao:
          type: string
          maxLength: 2000
        suspeitos:
          type: array
          items:
            type: string
        vitimas:
          type: array
          items:
            type: string
    metadata:
      type: object
      properties:
        tenant:
          type: string
        batalhao:
          type: string
        timestamp:
          type: string
          format: date-time

3. Especificações OpenAPI

3.1 Autenticação

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key

3.2 Headers Obrigatórios

headers:
  X-Tenant-ID:
    description: "Identificador do órgão/tenant"
    required: true
    schema:
      type: string
  X-Request-ID:
    description: "ID único da requisição para rastreamento"
    required: true
    schema:
      type: string
      format: uuid
  X-Trace-ID:
    description: "ID de rastreamento distribuído"
    required: true
    schema:
      type: string
  Authorization:
    description: "Token JWT para autenticação"
    required: true
    schema:
      type: string
      pattern: '^Bearer .+$'

3.3 Schemas Compartilhados

components:
  schemas:
    Entity:
      type: object
      properties:
        tipo:
          type: string
          enum: [pessoa, organizacao, local, data, valor]
        valor:
          type: string
        confianca:
          type: number
          minimum: 0
          maximum: 1
    
    Error:
      type: object
      properties:
        code:
          type: string
        message:
          type: string
        details:
          type: object
        timestamp:
          type: string
          format: date-time
    
    Pagination:
      type: object
      properties:
        page:
          type: integer
          minimum: 1
          default: 1
        limit:
          type: integer
          minimum: 1
          maximum: 100
          default: 20
        total:
          type: integer
        hasNext:
          type: boolean
        hasPrev:
          type: boolean

4. Webhooks e Eventos

4.1 Eventos Suportados

webhookEvents:
  manifestation.created:
    description: "Manifestação criada e processada"
    payload:
      type: object
      properties:
        event:
          type: string
          enum: [manifestation.created]
        data:
          $ref: '#/components/schemas/ManifestationMP'
        timestamp:
          type: string
          format: date-time
  
  manifestation.triaged:
    description: "Manifestação triada e priorizada"
    payload:
      type: object
      properties:
        event:
          type: string
          enum: [manifestation.triaged]
        data:
          type: object
          properties:
            id:
              type: string
              format: uuid
            prioridade:
              type: number
            motivo:
              type: string
            analista:
              type: string
  
  manifestation.resolved:
    description: "Manifestação resolvida"
    payload:
      type: object
      properties:
        event:
          type: string
          enum: [manifestation.resolved]
        data:
          type: object
          properties:
            id:
              type: string
              format: uuid
            resultado:
              type: string
            observacoes:
              type: string

4.2 Configuração de Webhooks

webhookConfig:
  url:
    type: string
    format: uri
    description: "URL do endpoint do sistema externo"
  secret:
    type: string
    description: "Secret para validação de assinatura"
  events:
    type: array
    items:
      type: string
      enum: [manifestation.created, manifestation.triaged, manifestation.resolved]
  retryPolicy:
    maxAttempts:
      type: integer
      default: 3
    backoffMultiplier:
      type: number
      default: 2.0
    maxDelay:
      type: integer
      default: 300

5. Versionamento e Compatibilidade

5.1 Estratégia de Versionamento

  • Semantic Versioning: MAJOR.MINOR.PATCH
  • URL Versioning: /api/v1/, /api/v2/
  • Header Versioning: API-Version: v1
  • Backward Compatibility: Mínimo 12 meses

5.2 Deprecação

deprecationPolicy:
  noticePeriod:
    type: string
    enum: [30d, 60d, 90d]
  sunsetDate:
    type: string
    format: date
  migrationGuide:
    type: string
    format: uri

5.3 Compatibilidade

compatibility:
  supportedVersions:
    - "1.0"
    - "1.1"
    - "1.2"
  defaultVersion:
    type: string
    default: "1.2"
  minSupportedVersion:
    type: string
    default: "1.0"

6. Políticas de Erro

6.1 Códigos de Status HTTP

CódigoSignificadoAção Recomendada
200SucessoProcessar resposta
201CriadoRecuperar ID do recurso
400Requisição InválidaCorrigir dados de entrada
401Não AutorizadoRenovar token
403ProibidoVerificar permissões
404Não EncontradoVerificar ID do recurso
409ConflitoResolver conflito de dados
422Entidade Não ProcessávelCorrigir validação
429Muitas RequisiçõesImplementar backoff
500Erro InternoRetry com backoff
503Serviço IndisponívelRetry após intervalo

6.2 Estrutura de Erro

ErrorResponse:
  type: object
  properties:
    error:
      type: object
      properties:
        code:
          type: string
          example: "VALIDATION_ERROR"
        message:
          type: string
          example: "Dados de entrada inválidos"
        details:
          type: array
          items:
            type: object
            properties:
              field:
                type: string
              message:
                type: string
              code:
                type: string
        timestamp:
          type: string
          format: date-time
        requestId:
          type: string
          format: uuid
        traceId:
          type: string

6.3 Retry e Circuit Breaker

retryPolicy:
  exponentialBackoff:
    initialDelay: 1000
    maxDelay: 30000
    multiplier: 2.0
  maxAttempts: 3
  retryableErrors:
    - 500
    - 502
    - 503
    - 504
    - "TIMEOUT"
    - "CONNECTION_ERROR"

circuitBreaker:
  failureThreshold: 5
  recoveryTimeout: 60000
  halfOpenMaxCalls: 3

📚 Exemplos de Uso

Exemplo 1: Criação de Manifestação MP

curl -X POST "https://api.aegistech.com.br/api/v1/mp/manifestations" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "X-Tenant-ID: mp-sp" \
  -H "X-Request-ID: 550e8400-e29b-41d4-a716-446655440000" \
  -H "X-Trace-ID: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" \
  -d '{
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "tipo": "denuncia",
    "conteudo": {
      "texto": "Denúncia sobre possível irregularidade em licitação...",
      "resumo": "Irregularidade em licitação pública",
      "entidades": [
        {
          "tipo": "organizacao",
          "valor": "Prefeitura Municipal",
          "confianca": 0.95
        }
      ]
    },
    "prioridade": {
      "score": 85,
      "motivo": "Alta confiança em entidades identificadas + palavras-chave de alta gravidade"
    },
    "metadata": {
      "tenant": "mp-sp",
      "timestamp": "2024-01-15T10:30:00Z",
      "hashMidia": "sha256:a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
      "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
    }
  }'

Exemplo 2: Webhook de Notificação

curl -X POST "https://sistema-externo.com/webhooks/aegistech" \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Signature: sha256=..." \
  -d '{
    "event": "manifestation.triaged",
    "data": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "prioridade": 85,
      "motivo": "Alta confiança em entidades identificadas",
      "analista": "promotor.joao.silva"
    },
    "timestamp": "2024-01-15T10:35:00Z"
  }'

📚 Referências