{"openapi":"3.0.3","info":{"title":"Taimes - Public API","description":"\nAPI pública de Taimes para extracción inteligente de documentos.\n\n## Autenticación\n\nTodos los endpoints requieren una API Key en el header `X-API-Key`.\n\n```\nX-API-Key: kmz_your_api_key_here\n```\n\nLas API Keys se pueden generar desde el panel de configuración de Taimes.\n\n## Flujos principales\n\n### 1. Extracción con schema específico\n1. Obtener lista de schemas disponibles: `GET /api/public/schemas`\n2. Enviar documento con schemaId: `POST /api/public/extract`\n\n### 2. Extracción automática\n1. Enviar documento sin especificar schema: `POST /api/public/extract/auto`\n2. El sistema detecta automáticamente el tipo y extrae los datos\n\n### 3. Generar schema nuevo\n1. Enviar documento de ejemplo: `POST /api/public/analyze-schema`\n2. Obtener schema sugerido para ese tipo de documento\n    ","version":"1.0.0","contact":{"name":"Taimes Support","url":"https://taimes.app"}},"servers":[{"url":"http://localhost:3000","description":"Development"},{"url":"https://taimes.app","description":"Production"}],"tags":[{"name":"Extraction","description":"Endpoints para extraer datos de documentos"},{"name":"Schemas","description":"Endpoints para gestionar y analizar schemas"},{"name":"Webhooks","description":"Eventos enviados a tus endpoints configurados cuando se extraen documentos"},{"name":"Sub-Tenants","description":"CRUD de sub-tenants (sedes, sucursales, clientes) dentro de tu tenant"},{"name":"Users","description":"CRUD de usuarios dentro de tu tenant"}],"paths":{"/api/public/extract":{"post":{"tags":["Extraction"],"summary":"Extraer datos con schema específico","description":"Extrae datos estructurados de un documento usando un schema específico.","operationId":"extractWithSchema","security":[{"ApiKeyAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["file"],"properties":{"file":{"type":"string","format":"binary","description":"Documento a procesar (PDF, imagen, etc.)"},"schemaId":{"type":"string","format":"uuid","description":"ID del schema a usar (requerido si no se envía schema)"},"schema":{"type":"string","description":"JSON del schema personalizado (requerido si no se envía schemaId)"},"model":{"type":"string","enum":["google-gla:gemini-3-flash-preview","google-gla:gemini-2.5-flash-lite","google-gla:gemini-3-pro-preview","google-gla:gemini-3.1-flash-lite-preview"],"default":"google-gla:gemini-3-flash-preview","description":"Modelo LLM a usar"},"save":{"type":"string","enum":["true","false"],"default":"false","description":"Guardar documento en la base de datos"}}}}}},"responses":{"200":{"description":"Extracción exitosa","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtractionResponse"},"example":{"success":true,"extracted_data":{"invoice_number":"INV-2024-001","date":"2024-01-15","total_amount":150000,"vendor_name":"Empresa ABC"},"metadata":{"document_type":"invoice","confidence":0.95,"processing_time_seconds":3.2,"model_used":"gemini-3-flash-preview","schema_used":{"id":"uuid","name":"Factura","code":"invoice"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/InternalError"}}}},"/api/public/extract/auto":{"post":{"tags":["Extraction"],"summary":"Extracción automática","description":"Extrae datos detectando automáticamente el tipo de documento y el schema a usar.","operationId":"extractAuto","security":[{"ApiKeyAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["file"],"properties":{"file":{"type":"string","format":"binary","description":"Documento a procesar"},"model":{"type":"string","enum":["google-gla:gemini-3-flash-preview","google-gla:gemini-2.5-flash-lite","google-gla:gemini-3-pro-preview","google-gla:gemini-3.1-flash-lite-preview"],"default":"google-gla:gemini-3-flash-preview"},"save":{"type":"string","enum":["true","false"],"default":"false"}}}}}},"responses":{"200":{"description":"Extracción exitosa","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AutoExtractionResponse"},"example":{"success":true,"matched_schema":{"id":"uuid","name":"Recibo Nequi","code":"nequi_receipt"},"extracted_data":{"amount":85000,"sender_name":"Juan Pérez","reference":"NEQ123456"},"metadata":{"document_type":"bank_transfer","classification_confidence":0.92,"match_reasoning":"Detected Nequi transfer receipt","processing_time_seconds":4.1,"model_used":"gemini-3-flash-preview"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"500":{"$ref":"#/components/responses/InternalError"}}}},"/api/public/analyze-schema":{"post":{"tags":["Schemas"],"summary":"Analizar documento y generar schema","description":"Analiza un documento y genera un schema sugerido para extraer datos de documentos similares.","operationId":"analyzeSchema","security":[{"ApiKeyAuth":[]}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["file"],"properties":{"file":{"type":"string","format":"binary","description":"Documento de ejemplo"},"model":{"type":"string","enum":["google-gla:gemini-3-flash-preview","google-gla:gemini-2.5-flash-lite","google-gla:gemini-3-pro-preview","google-gla:gemini-3.1-flash-lite-preview"],"default":"google-gla:gemini-3-flash-preview"},"language":{"type":"string","enum":["es","en","pt"],"default":"es","description":"Idioma para las descripciones de campos"},"save":{"type":"string","enum":["true","false"],"default":"false","description":"Guardar el schema generado en la base de datos del tenant"},"name":{"type":"string","description":"Nombre personalizado para el schema (usado si save=true, si no se especifica usa document_type)"},"code":{"type":"string","description":"Código único para el schema (usado si save=true, auto-generado si no se especifica)"}}}}}},"responses":{"200":{"description":"Análisis exitoso","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SchemaAnalysisResponse"},"example":{"success":true,"schema":{"document_type":"invoice","description":"Factura de compra o venta","fields":{"invoice_number":{"name":"Número de factura","type":"string","required":true,"description":"Identificador único de la factura"},"total_amount":{"name":"Total","type":"number","required":true,"description":"Monto total de la factura"}}},"metadata":{"language":"es","confidence":0.88,"processing_time_seconds":5.3,"model_used":"gemini-3-flash-preview"},"saved_schema":{"id":"uuid","name":"invoice","code":"invoice"}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"409":{"$ref":"#/components/responses/Conflict"},"500":{"$ref":"#/components/responses/InternalError"}}}},"/api/public/schemas":{"get":{"tags":["Schemas"],"summary":"Listar schemas disponibles","description":"Obtiene la lista de schemas de extracción disponibles para el tenant.","operationId":"listSchemas","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"active","in":"query","schema":{"type":"string","enum":["true","false"]},"description":"Filtrar por estado activo"},{"name":"search","in":"query","schema":{"type":"string"},"description":"Buscar por nombre o código"}],"responses":{"200":{"description":"Lista de schemas","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"schemas":{"type":"array","items":{"$ref":"#/components/schemas/SchemaListItem"}},"count":{"type":"integer"}}},"example":{"success":true,"schemas":[{"id":"uuid-1","name":"Factura de compra","code":"purchase_invoice","description":"Facturas de proveedores","document_type":"invoice","field_count":12,"isActive":true},{"id":"uuid-2","name":"Recibo Nequi","code":"nequi_receipt","description":"Comprobantes de Nequi","document_type":"bank_transfer","field_count":8,"isActive":true}],"count":2}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"500":{"$ref":"#/components/responses/InternalError"}}}},"/api/public/sub-tenants":{"get":{"tags":["Sub-Tenants"],"summary":"Listar sub-tenants","operationId":"listSubTenants","security":[{"ApiKeyAuth":[]}],"responses":{"200":{"description":"Lista de sub-tenants","content":{"application/json":{"schema":{"type":"object","properties":{"subTenants":{"type":"array","items":{"$ref":"#/components/schemas/SubTenant"}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}},"post":{"tags":["Sub-Tenants"],"summary":"Crear sub-tenant","operationId":"createSubTenant","security":[{"ApiKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["name"],"properties":{"name":{"type":"string","description":"Nombre del sub-tenant"},"code":{"type":"string","description":"Codigo unico (auto-generado si no se envia)"},"metadata":{"type":"object","description":"Metadata adicional (JSON libre)"}}}}}},"responses":{"200":{"description":"Sub-tenant creado","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"subTenant":{"$ref":"#/components/schemas/SubTenant"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/api/public/sub-tenants/{id}":{"get":{"tags":["Sub-Tenants"],"summary":"Obtener sub-tenant por ID","operationId":"getSubTenant","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Sub-tenant encontrado","content":{"application/json":{"schema":{"type":"object","properties":{"subTenant":{"$ref":"#/components/schemas/SubTenant"}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}},"put":{"tags":["Sub-Tenants"],"summary":"Actualizar sub-tenant","operationId":"updateSubTenant","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"code":{"type":"string"},"isActive":{"type":"boolean"},"metadata":{"type":"object"}}}}}},"responses":{"200":{"description":"Sub-tenant actualizado","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"subTenant":{"$ref":"#/components/schemas/SubTenant"}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}},"delete":{"tags":["Sub-Tenants"],"summary":"Eliminar sub-tenant","operationId":"deleteSubTenant","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Sub-tenant eliminado","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"deleted":{"type":"string","format":"uuid"}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}},"/api/public/users":{"get":{"tags":["Users"],"summary":"Listar usuarios","operationId":"listUsers","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"subTenantId","in":"query","schema":{"type":"string","format":"uuid"},"description":"Filtrar por sub-tenant"}],"responses":{"200":{"description":"Lista de usuarios","content":{"application/json":{"schema":{"type":"object","properties":{"users":{"type":"array","items":{"$ref":"#/components/schemas/User"}}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"}}},"post":{"tags":["Users"],"summary":"Crear usuario","operationId":"createUser","security":[{"ApiKeyAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["email","password","phoneCountryCode","phoneNumber"],"properties":{"email":{"type":"string","format":"email"},"name":{"type":"string"},"password":{"type":"string","minLength":6},"role":{"type":"string","enum":["ADMIN","USER"],"default":"USER"},"phoneCountryCode":{"type":"string","example":"+57"},"phoneNumber":{"type":"string","example":"3001234567"},"subTenantId":{"type":"string","format":"uuid","description":"Asignar a un sub-tenant"}}}}}},"responses":{"200":{"description":"Usuario creado","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"user":{"$ref":"#/components/schemas/User"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"409":{"$ref":"#/components/responses/Conflict"}}}},"/api/public/users/{id}":{"get":{"tags":["Users"],"summary":"Obtener usuario por ID","operationId":"getUser","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Usuario encontrado","content":{"application/json":{"schema":{"type":"object","properties":{"user":{"$ref":"#/components/schemas/User"}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}},"put":{"tags":["Users"],"summary":"Actualizar usuario","operationId":"updateUser","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"email":{"type":"string","format":"email"},"password":{"type":"string","minLength":6},"role":{"type":"string","enum":["ADMIN","USER"]},"subTenantId":{"type":"string","format":"uuid","nullable":true},"phoneCountryCode":{"type":"string"},"phoneNumber":{"type":"string"}}}}}},"responses":{"200":{"description":"Usuario actualizado","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"user":{"$ref":"#/components/schemas/User"}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}},"delete":{"tags":["Users"],"summary":"Eliminar usuario","operationId":"deleteUser","security":[{"ApiKeyAuth":[]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"Usuario eliminado","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"deleted":{"type":"string","format":"uuid"}}}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"}}}}},"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","in":"header","name":"X-API-Key","description":"API Key generada desde el panel de Taimes"}},"schemas":{"ExtractionResponse":{"type":"object","properties":{"success":{"type":"boolean"},"extracted_data":{"type":"object","additionalProperties":true,"description":"Datos extraídos según el schema"},"metadata":{"type":"object","properties":{"document_type":{"type":"string"},"confidence":{"type":"number"},"processing_time_seconds":{"type":"number"},"model_used":{"type":"string"},"schema_used":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"code":{"type":"string"}}}}},"document":{"type":"object","nullable":true,"properties":{"id":{"type":"string"},"structureId":{"type":"string"}},"description":"Solo presente si save=true"}}},"AutoExtractionResponse":{"type":"object","properties":{"success":{"type":"boolean"},"matched_schema":{"type":"object","nullable":true,"properties":{"id":{"type":"string"},"name":{"type":"string"},"code":{"type":"string"}}},"extracted_data":{"type":"object","additionalProperties":true},"metadata":{"type":"object","properties":{"document_type":{"type":"string"},"classification_confidence":{"type":"number"},"match_reasoning":{"type":"string"},"processing_time_seconds":{"type":"number"},"model_used":{"type":"string"}}}}},"SchemaAnalysisResponse":{"type":"object","properties":{"success":{"type":"boolean"},"schema":{"type":"object","properties":{"document_type":{"type":"string"},"description":{"type":"string"},"fields":{"type":"object","additionalProperties":{"type":"object","properties":{"name":{"type":"string"},"type":{"type":"string","enum":["string","number","date","time","boolean","select","array","object"]},"format":{"type":"string","enum":["email","phone","url","currency","percentage","integer","datetime"],"nullable":true},"required":{"type":"boolean"},"description":{"type":"string"}}}}}},"metadata":{"type":"object","properties":{"language":{"type":"string"},"confidence":{"type":"number"},"processing_time_seconds":{"type":"number"},"model_used":{"type":"string"}}},"saved_schema":{"type":"object","nullable":true,"description":"Solo presente si save=true","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"code":{"type":"string"}}}}},"SchemaListItem":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"name":{"type":"string"},"code":{"type":"string"},"description":{"type":"string","nullable":true},"document_type":{"type":"string"},"field_count":{"type":"integer"},"isActive":{"type":"boolean"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"WebhookEvent":{"type":"object","description":"Payload enviado a tus webhook endpoints cuando se extrae un documento. Headers incluidos: webhook-id, webhook-timestamp, webhook-signature (HMAC SHA-256).","properties":{"id":{"type":"string","description":"ID del evento (evt_uuid)","example":"evt_a1b2c3d4-e5f6-7890-abcd-ef1234567890"},"type":{"type":"string","enum":["document.created"],"description":"Tipo de evento"},"api_version":{"type":"string","example":"2026-02-01"},"created_at":{"type":"string","format":"date-time"},"tenant_id":{"type":"string","format":"uuid"},"data":{"type":"object","properties":{"object":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"ID del documento extraido"},"schema_id":{"type":"string","format":"uuid","description":"ID del schema usado para extraccion"},"schema_code":{"type":"string","description":"Codigo del schema (e.g. bank_transfer)"},"schema_name":{"type":"string","description":"Nombre del schema (e.g. Transferencia Bancaria)"},"schema_fields":{"type":"object","additionalProperties":{"type":"object","properties":{"type":{"type":"string","enum":["string","number","date","time","boolean","select","array","object"]},"format":{"type":"string","enum":["email","phone","url","currency","percentage","integer","datetime"],"nullable":true},"name":{"type":"string"},"required":{"type":"boolean"},"currency_code":{"type":"string","nullable":true}}},"description":"Definicion completa de campos del schema con sus tipos y formatos. Permite mapear extracted_data sin una segunda llamada al API."},"file_name":{"type":"string"},"file_url":{"type":"string","format":"uri"},"source":{"type":"string","enum":["web","batch","whatsapp","drive","api","public_api_auto"],"description":"Origen de la extraccion"},"extracted_data":{"type":"object","additionalProperties":true,"description":"Datos extraidos segun el schema"},"extraction_metadata":{"type":"object","properties":{"model_used":{"type":"string","nullable":true,"description":"Modelo LLM usado (e.g. gemini-3-flash-preview)"},"confidence":{"type":"number","nullable":true},"fields_extracted":{"type":"integer"},"processing_time_seconds":{"type":"number","nullable":true},"batch_job_id":{"type":"string","nullable":true,"description":"Solo presente en extracciones batch"},"auto_match_used":{"type":"boolean","nullable":true}}},"taimes_tenant_id":{"type":"string","format":"uuid"},"taimes_sub_tenant":{"type":"object","nullable":true,"properties":{"id":{"type":"string"},"name":{"type":"string"},"code":{"type":"string"},"sender_name":{"type":"string","nullable":true}}},"created_at":{"type":"string","format":"date-time"}}}}}}},"SubTenant":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"tenantId":{"type":"string","format":"uuid"},"name":{"type":"string"},"code":{"type":"string"},"isActive":{"type":"boolean"},"metadata":{"type":"object"},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"},"_count":{"type":"object","properties":{"users":{"type":"integer"},"documents":{"type":"integer"}}}}},"User":{"type":"object","properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string","format":"email"},"name":{"type":"string","nullable":true},"role":{"type":"string","enum":["ADMIN","USER"]},"tenantId":{"type":"string","format":"uuid"},"subTenantId":{"type":"string","format":"uuid","nullable":true},"phoneCountryCode":{"type":"string"},"whatsappPhone":{"type":"string"},"createdAt":{"type":"string","format":"date-time"},"subTenant":{"type":"object","nullable":true,"properties":{"id":{"type":"string"},"name":{"type":"string"},"code":{"type":"string"}}}}},"Error":{"type":"object","properties":{"error":{"type":"string"},"details":{"type":"string"}}}},"responses":{"BadRequest":{"description":"Bad Request - Parámetros inválidos","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"File is required"}}}},"Unauthorized":{"description":"Unauthorized - API Key inválida o faltante","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"Missing X-API-Key header"}}}},"NotFound":{"description":"Not Found - Recurso no encontrado","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"Schema not found"}}}},"Conflict":{"description":"Conflict - El recurso ya existe","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"Schema code already exists","existing_schema_id":"uuid","suggestion":"Use a different code or update the existing schema"}}}},"InternalError":{"description":"Internal Server Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"Internal server error"}}}}}}}