juampisor commited on
Commit
d53b1d7
·
1 Parent(s): 4bd44c0

Documentacion

Browse files
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
docs/.DS_Store ADDED
Binary file (6.15 kB). View file
 
docs/superpowers/.DS_Store ADDED
Binary file (6.15 kB). View file
 
documentation/.DS_Store ADDED
Binary file (6.15 kB). View file
 
documentation/M1_docs.html ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="es">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <title>API Módulo 1 - Historia Clínica Electrónica (HCE) - Swagger UI</title>
6
+ <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
7
+ <style>
8
+ body {
9
+ margin: 0;
10
+ padding: 0;
11
+ background-color: #f7f9fc;
12
+ }
13
+ </style>
14
+ </head>
15
+ <body>
16
+ <div id="swagger-ui"></div>
17
+ <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
18
+ <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-standalone-preset.js"></script>
19
+ <script>
20
+ window.onload = () => {
21
+ window.ui = SwaggerUIBundle({
22
+ url: './openapi.json',
23
+ spec: {"openapi": "3.1.0", "info": {"title": "API Módulo 1 - Historia Clínica Electrónica (HCE)", "description": "Repositorio central de datos médicos del sistema Health Grid. Gestiona consultas, diagnósticos, tratamientos y fichas médicas.", "version": "1.0.0"}, "paths": {"/api/v1/dev/login": {"post": {"tags": ["🔧 Desarrollo"], "summary": "[DEV] Obtener token JWT de desarrollo", "description": "Genera un JWT firmado con la misma clave que Core (M10). El token funciona en todos los endpoints protegidos.\n\n**Sin body**: genera token con el usuario por defecto (dr.dev, rol médico, todos los permisos).\n\n**Con body**: permite personalizar sub, username, role, permissions y duración.", "operationId": "dev_login_api_v1_dev_login_post", "requestBody": {"content": {"application/json": {"schema": {"anyOf": [{"$ref": "#/components/schemas/DevLoginRequest"}, {"type": "null"}], "title": "Body"}}}}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/DevLoginResponse"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/pacientes/{id_paciente}/ficha-medica": {"post": {"tags": ["Ficha Médica (HCE)"], "summary": "Crear ficha médica de un paciente", "description": "Crea la ficha médica permanente de un paciente en la Historia Clínica. Contiene datos clínicos estáticos como grupo sanguíneo, peso, altura y observaciones generales. Solo puede existir una ficha por paciente.", "operationId": "crear_ficha_medica_api_v1_pacientes__id_paciente__ficha_medica_post", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/FichaMedicaCreate"}}}}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/FichaMedicaSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "409": {"description": "Ya existe una ficha médica para este paciente.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "get": {"tags": ["Ficha Médica (HCE)"], "summary": "Obtener ficha médica de un paciente", "description": "Retorna los datos clínicos permanentes del paciente registrados en su ficha médica.", "operationId": "obtener_ficha_medica_api_v1_pacientes__id_paciente__ficha_medica_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/FichaMedicaSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "patch": {"tags": ["Ficha Médica (HCE)"], "summary": "Actualizar ficha médica de un paciente", "description": "Actualiza parcialmente la ficha médica del paciente. Solo se modifican los campos enviados en el body.", "operationId": "actualizar_ficha_medica_api_v1_pacientes__id_paciente__ficha_medica_patch", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/FichaMedicaUpdate"}}}}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/FichaMedicaSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/pacientes/{id_paciente}/antecedentes": {"get": {"tags": ["Ficha Médica — Antecedentes"], "summary": "Listar antecedentes clínicos de un paciente", "description": "Retorna todos los antecedentes registrados del paciente.", "operationId": "listar_antecedentes_api_v1_pacientes__id_paciente__antecedentes_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/AntecedenteSchema"}, "title": "Response Listar Antecedentes Api V1 Pacientes Id Paciente Antecedentes Get"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"description": "Paciente no encontrado.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "post": {"tags": ["Ficha Médica — Antecedentes"], "summary": "Registrar un antecedente clínico", "description": "Agrega un nuevo antecedente al historial clínico del paciente.", "operationId": "crear_antecedente_api_v1_pacientes__id_paciente__antecedentes_post", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AntecedenteCreate"}}}}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AntecedenteSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"description": "Paciente no encontrado.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/pacientes/{id_paciente}/antecedentes/{id_antecedente}": {"patch": {"tags": ["Ficha Médica — Antecedentes"], "summary": "Actualizar un antecedente clínico", "description": "Actualización parcial de un antecedente. Solo se pisan los campos enviados.", "operationId": "actualizar_antecedente_api_v1_pacientes__id_paciente__antecedentes__id_antecedente__patch", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_antecedente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Antecedente"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AntecedenteUpdate"}}}}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AntecedenteSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/pacientes/{id_paciente}/alertas": {"get": {"tags": ["Ficha Médica — Alertas Clínicas"], "summary": "Listar alertas clínicas de un paciente", "description": "Retorna todas las alertas del paciente (Activas y Resueltas).", "operationId": "listar_alertas_api_v1_pacientes__id_paciente__alertas_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/AlertaSchema"}, "title": "Response Listar Alertas Api V1 Pacientes Id Paciente Alertas Get"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"description": "Paciente no encontrado.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "post": {"tags": ["Ficha Médica — Alertas Clínicas"], "summary": "Registrar una alerta clínica", "description": "Crea una nueva consideración/alerta de seguridad para el paciente.", "operationId": "crear_alerta_api_v1_pacientes__id_paciente__alertas_post", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AlertaCreate"}}}}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AlertaSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"description": "Paciente no encontrado.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/pacientes/{id_paciente}/alertas/{id_alerta}": {"patch": {"tags": ["Ficha Médica — Alertas Clínicas"], "summary": "Resolver una alerta clínica", "description": "Cambia el estado de la alerta a Resuelta y registra la resolución.", "operationId": "resolver_alerta_api_v1_pacientes__id_paciente__alertas__id_alerta__patch", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_alerta", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Alerta"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AlertaUpdate"}}}}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AlertaSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/patients/{id_paciente}/episodes": {"get": {"tags": ["Atención Clínica — Episodios"], "summary": "Listar episodios médicos de un paciente", "description": "Permite a Facturación obtener el listado de episodios de un paciente para recopilar todos los actos médicos a liquidar.", "operationId": "listar_episodios_api_v1_patients__id_paciente__episodes_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "estado", "in": "query", "required": false, "schema": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Estado"}}, {"name": "desde_fecha", "in": "query", "required": false, "schema": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Desde Fecha"}}, {"name": "hasta_fecha", "in": "query", "required": false, "schema": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Hasta Fecha"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EpisodioListResponse"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "post": {"tags": ["Atención Clínica — Episodios"], "summary": "Abrir un nuevo episodio médico", "description": "Permite registrar/abrir un nuevo episodio de atención (guardia, consulta externa, etc.) para el paciente.", "operationId": "crear_episodio_api_v1_patients__id_paciente__episodes_post", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EpisodioCreate"}}}}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EpisodioDetalle"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/patients/{id_paciente}/episodes/{id_episodio}": {"get": {"tags": ["Atención Clínica — Episodios"], "summary": "Obtener detalle completo de un episodio", "description": "Retorna el detalle de un episodio médico específico incluyendo todos los actos médicos registrados. Principal insumo para liquidación.", "operationId": "obtener_episodio_api_v1_patients__id_paciente__episodes__id_episodio__get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EpisodioDetalle"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "patch": {"tags": ["Atención Clínica — Episodios"], "summary": "Actualizar parcialmente un episodio médico", "description": "Permite realizar modificaciones parciales en el episodio o cerrarlo enviando estado='closed'.", "operationId": "actualizar_episodio_api_v1_patients__id_paciente__episodes__id_episodio__patch", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EpisodioUpdate"}}}}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EpisodioDetalle"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/patients/{id_paciente}/episodes/{id_episodio}/medical-acts": {"get": {"tags": ["Atención Clínica — Actos Médicos"], "summary": "Listar actos médicos de un episodio", "description": "Lista todos los actos médicos registrados dentro de un episodio. Cada acto incluye el codigo_nomenclador para facturación.", "operationId": "listar_actos_medicos_api_v1_patients__id_paciente__episodes__id_episodio__medical_acts_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ActoMedicoListResponse"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "post": {"tags": ["Atención Clínica — Actos Médicos"], "summary": "Registrar un acto médico en un episodio", "description": "Permite registrar prestaciones/actos médicos dentro de un episodio activo de atención.", "operationId": "crear_acto_medico_api_v1_patients__id_paciente__episodes__id_episodio__medical_acts_post", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ActoMedicoCreate"}}}}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ActoMedicoSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unprocessable Entity"}}}}, "/api/v1/patients/{id_paciente}/episodes/{id_episodio}/evoluciones": {"get": {"tags": ["Atención Clínica — Evoluciones"], "summary": "Listar evoluciones médicas de un episodio", "description": "Lista todas las notas de evolución registradas dentro de un episodio, ordenadas cronológicamente.", "operationId": "listar_evoluciones_api_v1_patients__id_paciente__episodes__id_episodio__evoluciones_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EvolucionListResponse"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "post": {"tags": ["Atención Clínica — Evoluciones"], "summary": "Registrar una evolución médica en un episodio", "description": "Permite registrar una nota de evolución clínica dentro de un episodio activo. El profesional autor se obtiene automáticamente del token JWT.", "operationId": "crear_evolucion_api_v1_patients__id_paciente__episodes__id_episodio__evoluciones_post", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EvolucionCreate"}}}}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EvolucionSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unprocessable Entity"}}}}, "/api/v1/patients/{id_paciente}/episodes/{id_episodio}/evoluciones/{id_evolucion}": {"get": {"tags": ["Atención Clínica — Evoluciones"], "summary": "Obtener detalle de una evolución médica", "description": "Retorna el contenido completo de una nota de evolución específica.", "operationId": "obtener_evolucion_api_v1_patients__id_paciente__episodes__id_episodio__evoluciones__id_evolucion__get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}, {"name": "id_evolucion", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Evolucion"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EvolucionSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}, "patch": {"tags": ["Atención Clínica — Evoluciones"], "summary": "Actualizar parcialmente una evolución médica", "description": "Permite corregir el contenido de una nota de evolución existente.", "operationId": "actualizar_evolucion_api_v1_patients__id_paciente__episodes__id_episodio__evoluciones__id_evolucion__patch", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}, {"name": "id_evolucion", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Evolucion"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EvolucionUpdate"}}}}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/EvolucionSchema"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/recetas": {"get": {"tags": ["Atención Clínica — Recetas"], "summary": "Consultar listado de recetas (sincronización masiva)", "description": "Permite al Módulo 3 (Farmacia) obtener todas las recetas generadas. Útil para auditorías, cierres de lote o recuperación de datos tras caídas de Kafka.", "operationId": "listar_recetas_api_v1_recetas_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "estado", "in": "query", "required": false, "schema": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Estado"}}, {"name": "id_paciente", "in": "query", "required": false, "schema": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Paciente"}}, {"name": "desde_fecha", "in": "query", "required": false, "schema": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Desde Fecha"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RecetaListResponse"}}}}, "401": {"description": "Token JWT ausente, inválido o expirado.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "403": {"description": "Sin permiso requerido.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/recetas/{id_receta}": {"get": {"tags": ["Atención Clínica — Recetas"], "summary": "Obtener detalles de receta (con alertas farmacológicas)", "description": "Endpoint al que Farmacia llama tras recibir el evento Kafka clinica.farmacia.receta_creada para obtener la medicación recetada y cruzarla con las alergias del paciente.", "operationId": "obtener_receta_api_v1_recetas__id_receta__get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_receta", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Receta"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RecetaMedicaDetallada"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/patients/{id_paciente}/episodes/{id_episodio}/evoluciones/{id_evolucion}/recetas": {"post": {"tags": ["Atención Clínica — Recetas"], "summary": "Registrar una receta médica", "description": "Permite al médico registrar una receta electrónica asociada a la nota de evolución. Admite múltiples medicamentos. Al guardarse, se notifica automáticamente a Farmacia.", "operationId": "crear_receta_api_v1_patients__id_paciente__episodes__id_episodio__evoluciones__id_evolucion__recetas_post", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}, {"name": "id_episodio", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Episodio"}}, {"name": "id_evolucion", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Evolucion"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RecetaCreate"}}}}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RecetaMedicaDetallada"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unprocessable Entity"}}}}, "/api/v1/hce/health": {"get": {"tags": ["Integración M10 (Core)"], "summary": "Health check del módulo HCE", "description": "Endpoint de estado que Core puede usar para monitorear la disponibilidad del módulo HCE. No requiere autenticación.", "operationId": "health_check_api_v1_hce_health_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HealthResponse"}}}}}}}, "/api/v1/hce/notify-permission-change": {"post": {"tags": ["Integración M10 (Core)"], "summary": "Notificar a Core un cambio de permisos originado en HCE", "description": "Proxy que reenvía la notificación al Módulo 10 (Core).", "operationId": "notify_permission_change_api_v1_hce_notify_permission_change_post", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/PermissionChangeNotification"}}}, "required": true}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/PermissionChangeResponse"}}}}, "401": {"description": "Unauthorized", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Unprocessable Entity", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}}, "security": [{"JWT Bearer": []}]}}, "/api/v1/ordenes": {"get": {"tags": ["Integración M4/M5 (Estudios)"], "summary": "Consultar órdenes pendientes (sincronización masiva)", "description": "Endpoint utilizado por M4 y M5 como red de seguridad para consultar lotes completos de estudios pendientes.", "operationId": "listar_ordenes_api_v1_ordenes_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "tipo_estudio", "in": "query", "required": true, "schema": {"type": "string", "title": "Tipo Estudio"}}, {"name": "estado", "in": "query", "required": false, "schema": {"anyOf": [{"type": "string"}, {"type": "null"}], "default": "Pendiente", "title": "Estado"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OrdenListResponse"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/ordenes/{id_orden}": {"get": {"tags": ["Integración M4/M5 (Estudios)"], "summary": "Obtener detalles de orden (Smart Payload con alertas clínicas)", "description": "Endpoint utilizado por M4 y M5 para descargar la información clínica de la orden y las alertas de seguridad.", "operationId": "obtener_orden_api_v1_ordenes__id_orden__get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_orden", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Orden"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OrdenMedicaCompleta"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/resultados": {"post": {"tags": ["Integración M4/M5 (Estudios)"], "summary": "Registrar resultado de estudio", "description": "Endpoint utilizado por M4 (Laboratorio) y M5 (Imágenes) para enviar los resultados de un estudio médico finalizado a la HCE.", "operationId": "registrar_resultado_api_v1_resultados_post", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ResultadoEstudioRequest"}}}, "required": true}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ResultadoCreatedResponse"}}}}, "401": {"description": "Unauthorized", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "403": {"description": "Forbidden", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Datos inválidos.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}}, "security": [{"JWT Bearer": []}]}}, "/api/v1/internacion/ingreso": {"post": {"tags": ["Integración M6 (Camas)"], "summary": "Notificar ingreso de paciente (M6 → HCE)", "description": "Endpoint utilizado por el Módulo 6 para notificar a la HCE que un paciente fue ingresado físicamente a una cama. Esto dispara la creación del Episodio de Internación en la Historia Clínica.", "operationId": "notificar_ingreso_api_v1_internacion_ingreso_post", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/IngresoInternacionRequest"}}}, "required": true}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IngresoInternacionResponse"}}}}, "401": {"description": "Unauthorized", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "403": {"description": "Forbidden", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}, "422": {"description": "Datos de ingreso inválidos.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}}}, "security": [{"JWT Bearer": []}]}}, "/api/v1/patients/{id_paciente}/insurance": {"get": {"tags": ["Integración M7 (Facturación)"], "summary": "Obtener cobertura médica vigente del paciente", "description": "Retorna la obra social o prepaga vigente del paciente. Facturación necesita este dato para aplicar el nomenclador correcto.", "operationId": "obtener_cobertura_api_v1_patients__id_paciente__insurance_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/InsuranceResponse"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/pacientes/{id_paciente}/historial/recetas": {"get": {"tags": ["Integración M8 (Portal del Paciente)"], "summary": "Consultar historial de recetas del paciente (Para M8)", "description": "Endpoint sincrónico consumido por el Portal del Paciente (M8) para renderizar la sección 'Mi Salud', listando todas las recetas.", "operationId": "historial_recetas_api_v1_pacientes__id_paciente__historial_recetas_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/RecetaMedicaDetallada"}, "title": "Response Historial Recetas Api V1 Pacientes Id Paciente Historial Recetas Get"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/api/v1/pacientes/{id_paciente}/historial/resultados": {"get": {"tags": ["Integración M8 (Portal del Paciente)"], "summary": "Consultar resultados de estudios del paciente (Para M8)", "description": "Endpoint sincrónico consumido por el Portal del Paciente (M8) para mostrar los resultados de estudios médicos finalizados.", "operationId": "historial_resultados_api_v1_pacientes__id_paciente__historial_resultados_get", "security": [{"JWT Bearer": []}], "parameters": [{"name": "id_paciente", "in": "path", "required": true, "schema": {"type": "integer", "title": "Id Paciente"}}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/ResultadoEstudioResumen"}, "title": "Response Historial Resultados Api V1 Pacientes Id Paciente Historial Resultados Get"}}}}, "401": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Unauthorized"}, "403": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Forbidden"}, "404": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorResponse"}}}, "description": "Not Found"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}}, "components": {"schemas": {"ActoMedicoCreate": {"properties": {"codigo_nomenclador": {"anyOf": [{"type": "string", "maxLength": 20}, {"type": "null"}], "title": "Codigo Nomenclador", "examples": ["01.01.01"]}, "descripcion": {"anyOf": [{"type": "string", "maxLength": 500}, {"type": "null"}], "title": "Descripcion", "examples": ["Consulta médica ambulatoria"]}, "tipo": {"$ref": "#/components/schemas/TipoActoMedico", "examples": ["consulta"]}, "id_profesional": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Profesional", "examples": [42]}, "fecha_realizacion": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Fecha Realizacion", "description": "Fecha de realización. Si no se envía, se usa la fecha/hora actual."}, "cantidad": {"type": "integer", "exclusiveMinimum": 0.0, "title": "Cantidad", "default": 1, "examples": [1]}, "observaciones": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones"}}, "type": "object", "required": ["tipo"], "title": "ActoMedicoCreate", "description": "Payload para registrar un nuevo acto médico en un episodio."}, "ActoMedicoListResponse": {"properties": {"id_episodio": {"type": "integer", "title": "Id Episodio", "examples": [700]}, "total": {"type": "integer", "title": "Total", "examples": [4]}, "actos_medicos": {"items": {"$ref": "#/components/schemas/ActoMedicoSchema"}, "type": "array", "title": "Actos Medicos"}}, "type": "object", "required": ["id_episodio", "total", "actos_medicos"], "title": "ActoMedicoListResponse", "description": "Lista de actos médicos de un episodio."}, "ActoMedicoSchema": {"properties": {"id_acto_medico": {"type": "integer", "title": "Id Acto Medico", "examples": [9001]}, "id_episodio": {"type": "integer", "title": "Id Episodio", "examples": [700]}, "codigo_nomenclador": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Codigo Nomenclador", "examples": ["01.01.01"]}, "descripcion": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Descripcion", "examples": ["Consulta médica ambulatoria - primera vez"]}, "tipo": {"$ref": "#/components/schemas/TipoActoMedico", "examples": ["consulta"]}, "id_profesional": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Profesional", "examples": [42]}, "fecha_realizacion": {"type": "string", "format": "date-time", "title": "Fecha Realizacion", "examples": ["2025-03-10T09:15:00Z"]}, "cantidad": {"type": "integer", "title": "Cantidad", "default": 1, "examples": [1]}, "observaciones": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones"}}, "type": "object", "required": ["id_acto_medico", "id_episodio", "tipo", "fecha_realizacion"], "title": "ActoMedicoSchema", "description": "Acto médico registrado dentro de un episodio."}, "AlertaCreate": {"properties": {"tipo": {"$ref": "#/components/schemas/TipoConsideracion", "examples": ["Alergia"]}, "severidad": {"$ref": "#/components/schemas/SeveridadAlerta", "examples": ["Severa"]}, "descripcion": {"type": "string", "title": "Descripcion", "examples": ["Alergia severa a penicilina y derivados."]}}, "type": "object", "required": ["tipo", "severidad", "descripcion"], "title": "AlertaCreate", "description": "Body para crear una nueva alerta clínica."}, "AlertaSchema": {"properties": {"id": {"type": "integer", "title": "Id"}, "id_paciente": {"type": "integer", "title": "Id Paciente"}, "tipo": {"$ref": "#/components/schemas/TipoConsideracion"}, "severidad": {"$ref": "#/components/schemas/SeveridadAlerta"}, "descripcion": {"type": "string", "title": "Descripcion"}, "estado": {"$ref": "#/components/schemas/EstadoAlerta"}, "fecha_registro": {"type": "string", "format": "date-time", "title": "Fecha Registro"}, "id_medico_registro": {"type": "integer", "title": "Id Medico Registro"}, "fecha_resolucion": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Fecha Resolucion"}, "id_medico_resolucion": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Medico Resolucion"}, "motivo_resolucion": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Motivo Resolucion"}}, "type": "object", "required": ["id", "id_paciente", "tipo", "severidad", "descripcion", "estado", "fecha_registro", "id_medico_registro"], "title": "AlertaSchema", "description": "Respuesta completa de una alerta clínica."}, "AlertaSmartPayload": {"properties": {"tipo": {"$ref": "#/components/schemas/TipoConsideracion"}, "severidad": {"$ref": "#/components/schemas/SeveridadAlerta"}, "descripcion": {"type": "string", "title": "Descripcion"}}, "type": "object", "required": ["tipo", "severidad", "descripcion"], "title": "AlertaSmartPayload", "description": "Schema reducido para Smart Payload en órdenes y recetas.\nSolo incluye lo necesario para que M3/M4/M5 tomen decisiones clínicas."}, "AlertaUpdate": {"properties": {"estado": {"$ref": "#/components/schemas/EstadoAlerta", "examples": ["Resuelta"]}, "motivo_resolucion": {"type": "string", "title": "Motivo Resolucion", "examples": ["Alergia superada, confirmado por alergista."]}}, "type": "object", "required": ["estado", "motivo_resolucion"], "title": "AlertaUpdate", "description": "Body para resolver una alerta clínica (PATCH)."}, "AntecedenteCreate": {"properties": {"tipo": {"$ref": "#/components/schemas/TipoAntecedente", "examples": ["Quirurgico"]}, "descripcion": {"type": "string", "title": "Descripcion", "examples": ["Colecistectomía laparoscópica"]}, "fecha_suceso": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Fecha Suceso", "examples": ["2018-04-15"]}, "observaciones": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones", "examples": ["Sin complicaciones postoperatorias."]}}, "type": "object", "required": ["tipo", "descripcion"], "title": "AntecedenteCreate", "description": "Body para registrar un nuevo antecedente."}, "AntecedenteSchema": {"properties": {"id": {"type": "integer", "title": "Id"}, "id_paciente": {"type": "integer", "title": "Id Paciente"}, "tipo": {"$ref": "#/components/schemas/TipoAntecedente"}, "descripcion": {"type": "string", "title": "Descripcion"}, "fecha_suceso": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Fecha Suceso"}, "observaciones": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones"}, "fecha_registro": {"type": "string", "format": "date-time", "title": "Fecha Registro"}, "id_medico_registro": {"type": "integer", "title": "Id Medico Registro"}}, "type": "object", "required": ["id", "id_paciente", "tipo", "descripcion", "fecha_registro", "id_medico_registro"], "title": "AntecedenteSchema", "description": "Respuesta completa de un antecedente clínico."}, "AntecedenteUpdate": {"properties": {"descripcion": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Descripcion"}, "fecha_suceso": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Fecha Suceso"}, "observaciones": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones"}}, "type": "object", "title": "AntecedenteUpdate", "description": "Body para actualización parcial de un antecedente (PATCH)."}, "DevLoginRequest": {"properties": {"sub": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Sub", "description": "ID del usuario (médico)", "examples": [1]}, "username": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Username", "description": "Nombre de usuario", "examples": ["dr.dev"]}, "role": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Role", "description": "Rol del usuario", "examples": ["medico"]}, "permissions": {"anyOf": [{"items": {"type": "string"}, "type": "array"}, {"type": "null"}], "title": "Permissions", "description": "Lista de permisos", "examples": [["hce:read", "hce:write", "hce:alertas:read", "hce:alertas:write", "hce:antecedentes:read", "hce:antecedentes:write", "hce:ficha-medica:read", "hce:ficha-medica:write", "hce:recetas:read", "hce:recetas:write", "hce:ordenes:read", "hce:resultados:write", "hce:internacion:write", "hce:episodes:read", "hce:medical-acts:read", "hce:insurance:read", "hce:evoluciones:read", "hce:evoluciones:write"]]}, "sede_id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Sede Id", "description": "ID de la sede", "examples": [1]}, "expire_hours": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Expire Hours", "description": "Horas de validez del token (default: 24)", "examples": [24]}}, "type": "object", "title": "DevLoginRequest", "description": "Body opcional para personalizar el token de desarrollo.\nSi no se envía ningún campo, se usan los valores por defecto de settings."}, "DevLoginResponse": {"properties": {"access_token": {"type": "string", "title": "Access Token"}, "token_type": {"type": "string", "title": "Token Type", "default": "bearer"}, "expires_in_hours": {"type": "integer", "title": "Expires In Hours"}, "user": {"additionalProperties": true, "type": "object", "title": "User"}}, "type": "object", "required": ["access_token", "expires_in_hours", "user"], "title": "DevLoginResponse", "description": "Respuesta del endpoint de login de desarrollo."}, "EpisodioCreate": {"properties": {"tipo": {"$ref": "#/components/schemas/TipoEpisodio", "examples": ["internacion"]}, "estado": {"$ref": "#/components/schemas/EstadoEpisodio", "default": "open", "examples": ["open"]}, "id_sede": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Sede", "examples": [3]}, "diagnostico_principal": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Diagnostico Principal", "examples": ["J18.9 - Neumonía no especificada"]}}, "type": "object", "required": ["tipo"], "title": "EpisodioCreate", "description": "Creación de episodio médico."}, "EpisodioDetalle": {"properties": {"id_episodio": {"type": "integer", "title": "Id Episodio", "examples": [700]}, "id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}, "tipo": {"$ref": "#/components/schemas/TipoEpisodio", "examples": ["internacion"]}, "estado": {"$ref": "#/components/schemas/EstadoEpisodio", "examples": ["closed"]}, "id_sede": {"type": "integer", "title": "Id Sede", "examples": [3]}, "id_medico_responsable": {"type": "integer", "title": "Id Medico Responsable", "examples": [42]}, "diagnostico_principal": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Diagnostico Principal", "examples": ["J18.9 - Neumonía no especificada"]}, "fecha_apertura": {"type": "string", "format": "date-time", "title": "Fecha Apertura", "examples": ["2025-03-10T09:00:00Z"]}, "fecha_cierre": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Fecha Cierre", "examples": ["2025-03-15T11:00:00Z"]}, "actos_medicos": {"items": {"$ref": "#/components/schemas/ActoMedicoSchema"}, "type": "array", "title": "Actos Medicos"}}, "type": "object", "required": ["id_episodio", "id_paciente", "tipo", "estado", "id_sede", "id_medico_responsable", "fecha_apertura"], "title": "EpisodioDetalle", "description": "Detalle completo de un episodio con actos médicos."}, "EpisodioListResponse": {"properties": {"id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}, "total": {"type": "integer", "title": "Total", "examples": [5]}, "episodios": {"items": {"$ref": "#/components/schemas/EpisodioResumen"}, "type": "array", "title": "Episodios"}}, "type": "object", "required": ["id_paciente", "total", "episodios"], "title": "EpisodioListResponse", "description": "Lista de episodios de un paciente."}, "EpisodioResumen": {"properties": {"id_episodio": {"type": "integer", "title": "Id Episodio", "examples": [700]}, "tipo": {"$ref": "#/components/schemas/TipoEpisodio", "examples": ["internacion"]}, "estado": {"$ref": "#/components/schemas/EstadoEpisodio", "examples": ["closed"]}, "id_sede": {"type": "integer", "title": "Id Sede", "examples": [3]}, "fecha_apertura": {"type": "string", "format": "date-time", "title": "Fecha Apertura", "examples": ["2025-03-10T09:00:00Z"]}, "fecha_cierre": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Fecha Cierre", "examples": ["2025-03-15T11:00:00Z"]}, "id_medico_responsable": {"type": "integer", "title": "Id Medico Responsable", "examples": [42]}}, "type": "object", "required": ["id_episodio", "tipo", "estado", "id_sede", "fecha_apertura", "id_medico_responsable"], "title": "EpisodioResumen", "description": "Resumen de un episodio para listados."}, "EpisodioUpdate": {"properties": {"tipo": {"anyOf": [{"$ref": "#/components/schemas/TipoEpisodio"}, {"type": "null"}]}, "estado": {"anyOf": [{"$ref": "#/components/schemas/EstadoEpisodio"}, {"type": "null"}]}, "id_sede": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Sede"}, "id_medico_responsable": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Medico Responsable"}, "diagnostico_principal": {"anyOf": [{"type": "string", "maxLength": 500}, {"type": "null"}], "title": "Diagnostico Principal"}, "fecha_cierre": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Fecha Cierre"}}, "type": "object", "title": "EpisodioUpdate", "description": "Payload para actualizar un episodio médico (ej. cerrar o cambiar médico)."}, "ErrorResponse": {"properties": {"error": {"type": "string", "title": "Error", "examples": ["NOT_FOUND"]}, "message": {"type": "string", "title": "Message", "examples": ["El recurso solicitado no fue encontrado."]}, "timestamp": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Timestamp"}}, "type": "object", "required": ["error", "message"], "title": "ErrorResponse", "description": "Respuesta estándar de error del módulo HCE."}, "EstadoAlerta": {"type": "string", "enum": ["Activa", "Resuelta"], "title": "EstadoAlerta", "description": "Estado del ciclo de vida de la alerta."}, "EstadoEpisodio": {"type": "string", "enum": ["open", "closed"], "title": "EstadoEpisodio"}, "EstadoReceta": {"type": "string", "enum": ["Activa", "Suspendida", "Dispensada"], "title": "EstadoReceta"}, "EvolucionCreate": {"properties": {"contenido": {"type": "string", "title": "Contenido", "description": "Texto libre con la nota clínica del profesional.", "examples": ["Paciente refiere mejoría del cuadro respiratorio. Se auscultan campos pulmonares limpios. Se indica continuar tratamiento."]}, "fecha": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Fecha", "description": "Fecha/hora de la evolución. Si no se envía, se usa la fecha/hora actual."}}, "type": "object", "required": ["contenido"], "title": "EvolucionCreate", "description": "Body para registrar una nueva evolución médica en un episodio."}, "EvolucionListResponse": {"properties": {"id_episodio": {"type": "integer", "title": "Id Episodio"}, "total": {"type": "integer", "title": "Total"}, "evoluciones": {"items": {"$ref": "#/components/schemas/EvolucionSchema"}, "type": "array", "title": "Evoluciones"}}, "type": "object", "required": ["id_episodio", "total", "evoluciones"], "title": "EvolucionListResponse", "description": "Respuesta de listado de evoluciones de un episodio."}, "EvolucionSchema": {"properties": {"id_evolucion": {"type": "integer", "title": "Id Evolucion"}, "id_episodio": {"type": "integer", "title": "Id Episodio"}, "id_profesional": {"type": "integer", "title": "Id Profesional"}, "contenido": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Contenido"}, "fecha": {"type": "string", "format": "date-time", "title": "Fecha"}}, "type": "object", "required": ["id_evolucion", "id_episodio", "id_profesional", "fecha"], "title": "EvolucionSchema", "description": "Schema de respuesta completo de una evolución médica."}, "EvolucionUpdate": {"properties": {"contenido": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Contenido", "description": "Texto libre con la nota clínica corregida."}}, "type": "object", "title": "EvolucionUpdate", "description": "Body para actualizar parcialmente una evolución médica (PATCH)."}, "FichaMedicaCreate": {"properties": {"grupo_sanguineo": {"anyOf": [{"type": "string", "maxLength": 10}, {"type": "null"}], "title": "Grupo Sanguineo", "description": "Grupo sanguíneo y factor Rh del paciente.", "examples": ["A+"]}, "peso_kg": {"anyOf": [{"type": "number"}, {"type": "null"}], "title": "Peso Kg", "description": "Peso del paciente en kilogramos.", "examples": [72.5]}, "altura_cm": {"anyOf": [{"type": "number"}, {"type": "null"}], "title": "Altura Cm", "description": "Altura del paciente en centímetros.", "examples": [175.0]}, "observaciones_generales": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones Generales", "description": "Notas generales y antecedentes del paciente visibles en la cabecera de la ficha.", "examples": ["Paciente con antecedentes de hipertensión arterial. Diabético tipo 2."]}}, "type": "object", "title": "FichaMedicaCreate", "description": "Payload para crear/registrar la ficha médica de un paciente."}, "FichaMedicaSchema": {"properties": {"grupo_sanguineo": {"anyOf": [{"type": "string", "maxLength": 10}, {"type": "null"}], "title": "Grupo Sanguineo", "description": "Grupo sanguíneo y factor Rh del paciente.", "examples": ["A+"]}, "peso_kg": {"anyOf": [{"type": "number"}, {"type": "null"}], "title": "Peso Kg", "description": "Peso del paciente en kilogramos.", "examples": [72.5]}, "altura_cm": {"anyOf": [{"type": "number"}, {"type": "null"}], "title": "Altura Cm", "description": "Altura del paciente en centímetros.", "examples": [175.0]}, "observaciones_generales": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones Generales", "description": "Notas generales y antecedentes del paciente visibles en la cabecera de la ficha.", "examples": ["Paciente con antecedentes de hipertensión arterial. Diabético tipo 2."]}, "id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}}, "type": "object", "required": ["id_paciente"], "title": "FichaMedicaSchema", "description": "Schema de respuesta completo de la ficha médica."}, "FichaMedicaUpdate": {"properties": {"grupo_sanguineo": {"anyOf": [{"type": "string", "maxLength": 10}, {"type": "null"}], "title": "Grupo Sanguineo", "description": "Grupo sanguíneo y factor Rh del paciente.", "examples": ["A+"]}, "peso_kg": {"anyOf": [{"type": "number"}, {"type": "null"}], "title": "Peso Kg", "description": "Peso del paciente en kilogramos.", "examples": [72.5]}, "altura_cm": {"anyOf": [{"type": "number"}, {"type": "null"}], "title": "Altura Cm", "description": "Altura del paciente en centímetros.", "examples": [175.0]}, "observaciones_generales": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Observaciones Generales", "description": "Notas generales y antecedentes del paciente visibles en la cabecera de la ficha.", "examples": ["Paciente con antecedentes de hipertensión arterial. Diabético tipo 2."]}}, "type": "object", "title": "FichaMedicaUpdate", "description": "Payload para actualizar parcialmente la ficha médica. Todos los campos son opcionales."}, "HTTPValidationError": {"properties": {"detail": {"items": {"$ref": "#/components/schemas/ValidationError"}, "type": "array", "title": "Detail"}}, "type": "object", "title": "HTTPValidationError"}, "HealthResponse": {"properties": {"status": {"type": "string", "title": "Status", "examples": ["UP"]}, "module": {"type": "string", "title": "Module", "examples": ["hce"]}, "timestamp": {"type": "string", "format": "date-time", "title": "Timestamp"}}, "type": "object", "required": ["status", "module", "timestamp"], "title": "HealthResponse", "description": "Respuesta del health check."}, "IngresoInternacionRequest": {"properties": {"id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}, "sector": {"type": "string", "title": "Sector", "examples": ["UTI"]}, "habitacion": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Habitacion", "examples": ["Terapia A"]}, "cama": {"type": "string", "title": "Cama", "examples": ["Cama 4"]}, "fecha_ingreso": {"type": "string", "format": "date-time", "title": "Fecha Ingreso", "examples": ["2026-04-17T14:30:00Z"]}, "medico_solicitante": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Medico Solicitante", "examples": ["Dr. Pérez"]}}, "type": "object", "required": ["id_paciente", "sector", "cama", "fecha_ingreso"], "title": "IngresoInternacionRequest", "description": "Payload enviado por M6 para notificar ingreso de paciente a cama."}, "IngresoInternacionResponse": {"properties": {"status": {"type": "string", "title": "Status", "default": "success", "examples": ["success"]}, "mensaje": {"type": "string", "title": "Mensaje", "default": "Episodio creado y cama asignada correctamente.", "examples": ["Episodio creado y cama asignada correctamente."]}, "data": {"anyOf": [{"additionalProperties": true, "type": "object"}, {"type": "null"}], "title": "Data", "examples": [{"id_episodio": 700, "id_movimiento": 1}]}}, "type": "object", "title": "IngresoInternacionResponse", "description": "Respuesta tras crear episodio de internación."}, "InsuranceResponse": {"properties": {"id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}, "id_obra_social": {"type": "integer", "title": "Id Obra Social", "examples": [15]}, "nombre_obra_social": {"type": "string", "title": "Nombre Obra Social", "examples": ["OSDE"]}, "codigo_plan": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Codigo Plan", "examples": ["OSDE-210"]}, "numero_afiliado": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Numero Afiliado", "examples": ["1234567890"]}, "vigente_desde": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Vigente Desde", "examples": ["2024-01-01"]}, "vigente_hasta": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}], "title": "Vigente Hasta"}}, "type": "object", "required": ["id_paciente", "id_obra_social", "nombre_obra_social"], "title": "InsuranceResponse", "description": "Cobertura médica vigente del paciente."}, "ItemRecetaCreate": {"properties": {"medicamento": {"type": "string", "maxLength": 300, "title": "Medicamento", "examples": ["Amoxicilina 500mg"]}, "indicaciones": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Indicaciones", "examples": ["Tomar 1 comprimido cada 8 horas por 7 días."]}, "cantidad": {"type": "integer", "minimum": 1.0, "title": "Cantidad", "default": 1, "examples": [1]}}, "type": "object", "required": ["medicamento"], "title": "ItemRecetaCreate", "description": "Schema para crear un ítem de receta."}, "ItemRecetaSchema": {"properties": {"medicamento": {"type": "string", "maxLength": 300, "title": "Medicamento", "examples": ["Amoxicilina 500mg"]}, "indicaciones": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Indicaciones", "examples": ["Tomar 1 comprimido cada 8 horas por 7 días."]}, "cantidad": {"type": "integer", "minimum": 1.0, "title": "Cantidad", "default": 1, "examples": [1]}, "id_item": {"type": "integer", "title": "Id Item", "examples": [1]}, "id_receta": {"type": "integer", "title": "Id Receta", "examples": [8502]}}, "type": "object", "required": ["medicamento", "id_item", "id_receta"], "title": "ItemRecetaSchema", "description": "Schema para leer un ítem de receta."}, "OrdenListResponse": {"properties": {"status": {"type": "string", "title": "Status", "default": "success", "examples": ["success"]}, "cantidad": {"type": "integer", "title": "Cantidad", "examples": [1]}, "data": {"items": {"$ref": "#/components/schemas/OrdenMedicaCompleta"}, "type": "array", "title": "Data"}}, "type": "object", "required": ["cantidad", "data"], "title": "OrdenListResponse", "description": "Respuesta de listado de órdenes."}, "OrdenMedicaCompleta": {"properties": {"id_orden": {"type": "integer", "title": "Id Orden", "examples": [4050]}, "id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}, "tipo_estudio": {"$ref": "#/components/schemas/TipoEstudio", "examples": ["Imagen"]}, "descripcion_pedido": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Descripcion Pedido", "examples": ["Resonancia Magnética de Cerebro"]}, "prioridad": {"$ref": "#/components/schemas/PrioridadOrden", "examples": ["Urgente"]}, "alertas_clinicas": {"items": {"$ref": "#/components/schemas/AlertaSmartPayload"}, "type": "array", "title": "Alertas Clinicas"}}, "type": "object", "required": ["id_orden", "id_paciente", "tipo_estudio", "prioridad"], "title": "OrdenMedicaCompleta", "description": "Orden médica con Smart Payload de alertas clínicas activas."}, "PermissionChangeNotification": {"properties": {"id_usuario_afectado": {"type": "integer", "title": "Id Usuario Afectado", "examples": [42]}, "tipo_cambio": {"$ref": "#/components/schemas/TipoCambioPermiso", "examples": ["revoke-access"]}, "recurso_afectado": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Recurso Afectado", "examples": ["hce:write"]}, "motivo": {"type": "string", "title": "Motivo", "examples": ["Profesional suspendido por auditoría interna."]}, "id_usuario_notificador": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Usuario Notificador", "examples": [10]}, "fecha_ocurrencia": {"anyOf": [{"type": "string", "format": "date-time"}, {"type": "null"}], "title": "Fecha Ocurrencia"}}, "type": "object", "required": ["id_usuario_afectado", "tipo_cambio", "motivo"], "title": "PermissionChangeNotification", "description": "Payload que HCE envía a Core para notificar cambio de permisos."}, "PermissionChangeResponse": {"properties": {"acknowledged": {"type": "boolean", "title": "Acknowledged", "examples": [true]}}, "type": "object", "required": ["acknowledged"], "title": "PermissionChangeResponse", "description": "Respuesta de Core tras recibir la notificación."}, "PrioridadOrden": {"type": "string", "enum": ["Normal", "Urgente", "Emergencia"], "title": "PrioridadOrden"}, "RecetaCreate": {"properties": {"items": {"items": {"$ref": "#/components/schemas/ItemRecetaCreate"}, "type": "array", "minItems": 1, "title": "Items"}}, "type": "object", "required": ["items"], "title": "RecetaCreate", "description": "Payload para que un médico cree una receta completa con múltiples medicamentos."}, "RecetaListResponse": {"properties": {"total": {"type": "integer", "title": "Total", "examples": [15]}, "data": {"items": {"$ref": "#/components/schemas/RecetaMedicaDetallada"}, "type": "array", "title": "Data"}}, "type": "object", "required": ["total", "data"], "title": "RecetaListResponse", "description": "Respuesta paginada de recetas."}, "RecetaMedicaDetallada": {"properties": {"id_receta": {"type": "integer", "title": "Id Receta", "examples": [8502]}, "id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}, "id_evolucion": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Evolucion", "examples": [302]}, "estado": {"$ref": "#/components/schemas/EstadoReceta", "examples": ["Activa"]}, "items": {"items": {"$ref": "#/components/schemas/ItemRecetaSchema"}, "type": "array", "title": "Items"}, "alertas_clinicas": {"items": {"$ref": "#/components/schemas/AlertaSmartPayload"}, "type": "array", "title": "Alertas Clinicas"}}, "type": "object", "required": ["id_receta", "id_paciente", "estado"], "title": "RecetaMedicaDetallada", "description": "Receta electrónica con Smart Payload de alertas clínicas activas del paciente."}, "ResultadoCreatedResponse": {"properties": {"status": {"type": "string", "title": "Status", "default": "success", "examples": ["success"]}, "message": {"type": "string", "title": "Message", "default": "Resultado vinculado correctamente a la Historia Clínica.", "examples": ["Resultado vinculado correctamente a la Historia Clínica."]}}, "type": "object", "title": "ResultadoCreatedResponse", "description": "Respuesta tras registrar un resultado."}, "ResultadoEstudioRequest": {"properties": {"id_orden": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "Id Orden", "examples": [4050]}, "id_paciente": {"type": "integer", "title": "Id Paciente", "examples": [10500]}, "tipo_estudio": {"$ref": "#/components/schemas/TipoEstudio", "examples": ["Imagen"]}, "id_profesional_firmante": {"type": "string", "title": "Id Profesional Firmante", "examples": ["Dra. Gomez (Radiología)"]}, "fecha_resultado": {"type": "string", "format": "date-time", "title": "Fecha Resultado", "examples": ["2026-04-17T11:00:00Z"]}, "informe_resumen": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Informe Resumen", "examples": ["RM de Cerebro: Sin hallazgos patológicos."]}, "id_externo_estudio": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Id Externo Estudio", "examples": ["550e8400-e29b-41d4-a716-446655440000"]}}, "type": "object", "required": ["id_paciente", "tipo_estudio", "id_profesional_firmante", "fecha_resultado"], "title": "ResultadoEstudioRequest", "description": "Payload enviado por M4/M5 para registrar un resultado en la HCE."}, "ResultadoEstudioResumen": {"properties": {"id_resultado": {"type": "integer", "title": "Id Resultado", "examples": [9021]}, "tipo_estudio": {"type": "string", "title": "Tipo Estudio", "examples": ["Laboratorio"]}, "fecha_resultado": {"type": "string", "format": "date-time", "title": "Fecha Resultado", "examples": ["2026-04-20T10:00:00Z"]}, "titulo": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Titulo", "examples": ["Hemograma Completo"]}, "resumen": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Resumen", "examples": ["Valores dentro de los rangos normales. Sin observaciones."]}, "profesional_firmante": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Profesional Firmante", "examples": ["Dr. Bioq. Fernandez"]}}, "type": "object", "required": ["id_resultado", "tipo_estudio", "fecha_resultado"], "title": "ResultadoEstudioResumen", "description": "Resumen de resultado para el Portal del Paciente (M8)."}, "SeveridadAlerta": {"type": "string", "enum": ["Leve", "Moderada", "Severa", "Critica"], "title": "SeveridadAlerta", "description": "Nivel de severidad de la alerta."}, "TipoActoMedico": {"type": "string", "enum": ["consulta", "estudio-laboratorio", "estudio-imagen", "procedimiento", "cirugia", "medicacion", "descartable"], "title": "TipoActoMedico"}, "TipoAntecedente": {"type": "string", "enum": ["Quirurgico", "Familiar", "Patologico", "Habito"], "title": "TipoAntecedente", "description": "Tipo de antecedente clínico del paciente."}, "TipoCambioPermiso": {"type": "string", "enum": ["revoke-access", "role-change", "deactivate-user"], "title": "TipoCambioPermiso"}, "TipoConsideracion": {"type": "string", "enum": ["Alergia", "Dispositivo_Implantado", "Condicion_Critica", "Riesgo_Infeccioso", "Contraindicacion"], "title": "TipoConsideracion", "description": "Tipo de consideración/alerta clínica del paciente."}, "TipoEpisodio": {"type": "string", "enum": ["consulta-externa", "internacion", "guardia", "cirugia"], "title": "TipoEpisodio"}, "TipoEstudio": {"type": "string", "enum": ["Laboratorio", "Imagen", "Anatomia_Patologica"], "title": "TipoEstudio"}, "ValidationError": {"properties": {"loc": {"items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, "type": "array", "title": "Location"}, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, "input": {"title": "Input"}, "ctx": {"type": "object", "title": "Context"}}, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError"}}, "securitySchemes": {"JWT Bearer": {"type": "http", "description": "JWT emitido por Módulo 10 (Core). Header: Authorization: Bearer <token>", "scheme": "bearer"}}}},
24
+ dom_id: '#swagger-ui',
25
+ deepLinking: true,
26
+ presets: [
27
+ SwaggerUIBundle.presets.apis,
28
+ SwaggerUIStandalonePreset
29
+ ],
30
+ layout: "StandaloneLayout"
31
+ });
32
+ };
33
+ </script>
34
+ </body>
35
+ </html>
documentation/M1_openapi.yaml DELETED
@@ -1,2864 +0,0 @@
1
- basePath: /
2
- definitions:
3
- models.AdminCreateUserRequest:
4
- properties:
5
- email:
6
- type: string
7
- first_name:
8
- type: string
9
- last_name:
10
- type: string
11
- role_id:
12
- minimum: 1
13
- type: integer
14
- required:
15
- - email
16
- - first_name
17
- - last_name
18
- - role_id
19
- type: object
20
- models.AssignLocationRequest:
21
- properties:
22
- location_id:
23
- example: 1
24
- type: integer
25
- required:
26
- - location_id
27
- type: object
28
- models.AssignPermissionToRoleRequest:
29
- properties:
30
- permission_id:
31
- type: integer
32
- required:
33
- - permission_id
34
- type: object
35
- models.AssignRoleRequest:
36
- properties:
37
- role_id:
38
- example: 1
39
- type: integer
40
- required:
41
- - role_id
42
- type: object
43
- models.AssignSpecialityRequest:
44
- properties:
45
- speciality_id:
46
- example: 1
47
- type: integer
48
- required:
49
- - speciality_id
50
- type: object
51
- models.AuthResponse:
52
- properties:
53
- token:
54
- type: string
55
- user:
56
- $ref: '#/definitions/models.User'
57
- type: object
58
- models.ChangePasswordRequest:
59
- properties:
60
- current_password:
61
- type: string
62
- new_password:
63
- minLength: 6
64
- type: string
65
- required:
66
- - current_password
67
- - new_password
68
- type: object
69
- models.CreateEventLogRequest:
70
- properties:
71
- event_type_id:
72
- type: integer
73
- payload:
74
- type: string
75
- publisher_module:
76
- type: string
77
- required:
78
- - event_type_id
79
- - publisher_module
80
- type: object
81
- models.CreateEventSubscriptionRequest:
82
- properties:
83
- endpoint_url:
84
- type: string
85
- event_type_id:
86
- type: integer
87
- subscriber_module:
88
- type: string
89
- required:
90
- - endpoint_url
91
- - event_type_id
92
- - subscriber_module
93
- type: object
94
- models.CreateEventTypeRequest:
95
- properties:
96
- description:
97
- type: string
98
- name:
99
- type: string
100
- source_module:
101
- type: string
102
- required:
103
- - name
104
- - source_module
105
- type: object
106
- models.CreateLocationRequest:
107
- properties:
108
- address:
109
- type: string
110
- city:
111
- type: string
112
- country:
113
- type: string
114
- name:
115
- type: string
116
- required:
117
- - address
118
- - city
119
- - country
120
- - name
121
- type: object
122
- models.CreatePermissionRequest:
123
- properties:
124
- name:
125
- type: string
126
- required:
127
- - name
128
- type: object
129
- models.CreateRoleRequest:
130
- properties:
131
- name:
132
- type: string
133
- required:
134
- - name
135
- type: object
136
- models.CreateSpecialityRequest:
137
- properties:
138
- name:
139
- type: string
140
- required:
141
- - name
142
- type: object
143
- models.CreateUserRequest:
144
- properties:
145
- email:
146
- type: string
147
- first_name:
148
- type: string
149
- last_name:
150
- type: string
151
- password:
152
- minLength: 6
153
- type: string
154
- required:
155
- - email
156
- - first_name
157
- - last_name
158
- - password
159
- type: object
160
- models.ErrorResponse:
161
- properties:
162
- error:
163
- type: string
164
- type: object
165
- models.EventLog:
166
- properties:
167
- created_at:
168
- type: string
169
- event_type:
170
- $ref: '#/definitions/models.EventType'
171
- event_type_id:
172
- type: integer
173
- id:
174
- type: integer
175
- payload:
176
- type: string
177
- publisher_module:
178
- type: string
179
- status:
180
- description: pending, delivered, failed
181
- type: string
182
- type: object
183
- models.EventLogListResponse:
184
- properties:
185
- data:
186
- items:
187
- $ref: '#/definitions/models.EventLog'
188
- type: array
189
- pagination:
190
- $ref: '#/definitions/models.Pagination'
191
- total:
192
- type: integer
193
- type: object
194
- models.EventSubscription:
195
- properties:
196
- created_at:
197
- type: string
198
- deleted_at:
199
- type: string
200
- endpoint_url:
201
- type: string
202
- event_type:
203
- $ref: '#/definitions/models.EventType'
204
- event_type_id:
205
- type: integer
206
- id:
207
- type: integer
208
- is_active:
209
- type: boolean
210
- subscriber_module:
211
- type: string
212
- type: object
213
- models.EventSubscriptionListResponse:
214
- properties:
215
- data:
216
- items:
217
- $ref: '#/definitions/models.EventSubscription'
218
- type: array
219
- pagination:
220
- $ref: '#/definitions/models.Pagination'
221
- total:
222
- type: integer
223
- type: object
224
- models.EventType:
225
- properties:
226
- created_at:
227
- type: string
228
- deleted_at:
229
- type: string
230
- description:
231
- type: string
232
- id:
233
- type: integer
234
- name:
235
- type: string
236
- source_module:
237
- type: string
238
- type: object
239
- models.EventTypeListResponse:
240
- properties:
241
- data:
242
- items:
243
- $ref: '#/definitions/models.EventType'
244
- type: array
245
- pagination:
246
- $ref: '#/definitions/models.Pagination'
247
- total:
248
- type: integer
249
- type: object
250
- models.ForgotPasswordRequest:
251
- properties:
252
- email:
253
- type: string
254
- required:
255
- - email
256
- type: object
257
- models.JWK:
258
- properties:
259
- alg:
260
- type: string
261
- e:
262
- type: string
263
- kid:
264
- type: string
265
- kty:
266
- type: string
267
- "n":
268
- type: string
269
- use:
270
- type: string
271
- type: object
272
- models.JWKS:
273
- properties:
274
- keys:
275
- items:
276
- $ref: '#/definitions/models.JWK'
277
- type: array
278
- type: object
279
- models.Location:
280
- properties:
281
- address:
282
- type: string
283
- city:
284
- type: string
285
- country:
286
- type: string
287
- created_at:
288
- type: string
289
- deleted_at:
290
- type: string
291
- id:
292
- type: integer
293
- name:
294
- type: string
295
- type: object
296
- models.LocationListResponse:
297
- properties:
298
- data:
299
- items:
300
- $ref: '#/definitions/models.Location'
301
- type: array
302
- pagination:
303
- $ref: '#/definitions/models.Pagination'
304
- total:
305
- type: integer
306
- type: object
307
- models.LoginRequest:
308
- properties:
309
- email:
310
- type: string
311
- password:
312
- type: string
313
- required:
314
- - email
315
- - password
316
- type: object
317
- models.MessageResponse:
318
- properties:
319
- message:
320
- type: string
321
- type: object
322
- models.Pagination:
323
- properties:
324
- page:
325
- type: integer
326
- pageSize:
327
- type: integer
328
- type: object
329
- models.Permission:
330
- properties:
331
- deleted_at:
332
- type: string
333
- id:
334
- type: integer
335
- name:
336
- type: string
337
- roles:
338
- items:
339
- $ref: '#/definitions/models.Role'
340
- type: array
341
- type: object
342
- models.PermissionListResponse:
343
- properties:
344
- data:
345
- items:
346
- $ref: '#/definitions/models.Permission'
347
- type: array
348
- pagination:
349
- $ref: '#/definitions/models.Pagination'
350
- total:
351
- type: integer
352
- type: object
353
- models.ResetPasswordRequest:
354
- properties:
355
- code:
356
- type: string
357
- email:
358
- type: string
359
- new_password:
360
- minLength: 6
361
- type: string
362
- required:
363
- - code
364
- - email
365
- - new_password
366
- type: object
367
- models.Role:
368
- properties:
369
- deleted_at:
370
- type: string
371
- id:
372
- type: integer
373
- name:
374
- type: string
375
- permissions:
376
- items:
377
- $ref: '#/definitions/models.Permission'
378
- type: array
379
- users:
380
- items:
381
- $ref: '#/definitions/models.User'
382
- type: array
383
- type: object
384
- models.RoleListResponse:
385
- properties:
386
- data:
387
- items:
388
- $ref: '#/definitions/models.Role'
389
- type: array
390
- pagination:
391
- $ref: '#/definitions/models.Pagination'
392
- total:
393
- type: integer
394
- type: object
395
- models.Speciality:
396
- properties:
397
- deleted_at:
398
- type: string
399
- id:
400
- type: integer
401
- name:
402
- type: string
403
- type: object
404
- models.SpecialityListResponse:
405
- properties:
406
- data:
407
- items:
408
- $ref: '#/definitions/models.Speciality'
409
- type: array
410
- pagination:
411
- $ref: '#/definitions/models.Pagination'
412
- total:
413
- type: integer
414
- type: object
415
- models.UpdateEventLogStatusRequest:
416
- properties:
417
- status:
418
- description: 'Status must be one of: pending, delivered, failed'
419
- enum:
420
- - pending
421
- - delivered
422
- - failed
423
- example: delivered
424
- type: string
425
- required:
426
- - status
427
- type: object
428
- models.UpdateEventSubscriptionRequest:
429
- properties:
430
- endpoint_url:
431
- type: string
432
- is_active:
433
- type: boolean
434
- type: object
435
- models.UpdateEventTypeRequest:
436
- properties:
437
- description:
438
- type: string
439
- name:
440
- type: string
441
- source_module:
442
- type: string
443
- type: object
444
- models.UpdateLocationRequest:
445
- properties:
446
- address:
447
- type: string
448
- city:
449
- type: string
450
- country:
451
- type: string
452
- name:
453
- type: string
454
- type: object
455
- models.UpdatePermissionRequest:
456
- properties:
457
- name:
458
- type: string
459
- type: object
460
- models.UpdateRoleRequest:
461
- properties:
462
- name:
463
- type: string
464
- type: object
465
- models.UpdateSpecialityRequest:
466
- properties:
467
- name:
468
- type: string
469
- type: object
470
- models.UpdateUserRequest:
471
- properties:
472
- email:
473
- type: string
474
- first_name:
475
- type: string
476
- last_name:
477
- type: string
478
- type: object
479
- models.User:
480
- properties:
481
- created_at:
482
- type: string
483
- deleted_at:
484
- type: string
485
- email:
486
- type: string
487
- first_name:
488
- type: string
489
- has_credentials:
490
- type: boolean
491
- id:
492
- type: integer
493
- last_name:
494
- type: string
495
- locations:
496
- items:
497
- $ref: '#/definitions/models.Location'
498
- type: array
499
- roles:
500
- items:
501
- $ref: '#/definitions/models.Role'
502
- type: array
503
- specialities:
504
- items:
505
- $ref: '#/definitions/models.Speciality'
506
- type: array
507
- updated_at:
508
- type: string
509
- type: object
510
- models.UserListResponse:
511
- properties:
512
- data:
513
- items:
514
- $ref: '#/definitions/models.User'
515
- type: array
516
- pagination:
517
- $ref: '#/definitions/models.Pagination'
518
- total:
519
- type: integer
520
- type: object
521
- models.ValidateTokenResponse:
522
- properties:
523
- user_id:
524
- type: integer
525
- valid:
526
- type: boolean
527
- type: object
528
- models.VerifyAccountRequest:
529
- properties:
530
- password:
531
- minLength: 6
532
- type: string
533
- token:
534
- type: string
535
- required:
536
- - password
537
- - token
538
- type: object
539
- host: api.healthcare.cantero.ar
540
- info:
541
- contact: {}
542
- description: API principal del sistema. Gestiona autenticación, usuarios, roles,
543
- permisos, especialidades, locaciones y eventos.
544
- title: Core API
545
- version: 1.0.0
546
- paths:
547
- /.well-known/jwks.json:
548
- get:
549
- description: Returns the JSON Web Key Set (JWKS) for verifying JWT signatures
550
- issued by this service. Used by other services to validate tokens without
551
- contacting this API.
552
- produces:
553
- - application/json
554
- responses:
555
- "200":
556
- description: OK
557
- schema:
558
- $ref: '#/definitions/models.JWKS'
559
- "500":
560
- description: Internal Server Error
561
- schema:
562
- $ref: '#/definitions/models.ErrorResponse'
563
- summary: JWKS
564
- tags:
565
- - Auth
566
- /auth/forgot-password:
567
- post:
568
- consumes:
569
- - application/json
570
- description: Sends a one-time password reset code to the user's email address.
571
- parameters:
572
- - description: Email address
573
- in: body
574
- name: body
575
- required: true
576
- schema:
577
- $ref: '#/definitions/models.ForgotPasswordRequest'
578
- produces:
579
- - application/json
580
- responses:
581
- "200":
582
- description: Reset code sent to email
583
- schema:
584
- $ref: '#/definitions/models.MessageResponse'
585
- "400":
586
- description: Invalid email format
587
- schema:
588
- $ref: '#/definitions/models.ErrorResponse'
589
- "404":
590
- description: No user found with that email
591
- schema:
592
- $ref: '#/definitions/models.ErrorResponse'
593
- summary: Request password reset
594
- tags:
595
- - Auth
596
- /auth/login:
597
- post:
598
- consumes:
599
- - application/json
600
- description: Authenticates a user with email and password. Returns a JWT token
601
- and user data.
602
- parameters:
603
- - description: Login credentials
604
- in: body
605
- name: body
606
- required: true
607
- schema:
608
- $ref: '#/definitions/models.LoginRequest'
609
- produces:
610
- - application/json
611
- responses:
612
- "200":
613
- description: OK
614
- schema:
615
- $ref: '#/definitions/models.AuthResponse'
616
- "400":
617
- description: Invalid request body
618
- schema:
619
- $ref: '#/definitions/models.ErrorResponse'
620
- "401":
621
- description: Invalid credentials
622
- schema:
623
- $ref: '#/definitions/models.ErrorResponse'
624
- summary: Login
625
- tags:
626
- - Auth
627
- /auth/logout:
628
- post:
629
- description: Invalidates the current JWT token. Requires a valid Bearer token
630
- in the Authorization header.
631
- produces:
632
- - application/json
633
- responses:
634
- "200":
635
- description: OK
636
- schema:
637
- $ref: '#/definitions/models.MessageResponse'
638
- "400":
639
- description: Missing or malformed Authorization header
640
- schema:
641
- $ref: '#/definitions/models.ErrorResponse'
642
- "401":
643
- description: Invalid or expired token
644
- schema:
645
- $ref: '#/definitions/models.ErrorResponse'
646
- "500":
647
- description: Internal Server Error
648
- schema:
649
- $ref: '#/definitions/models.ErrorResponse'
650
- security:
651
- - Bearer: []
652
- summary: Logout
653
- tags:
654
- - Auth
655
- /auth/refresh:
656
- post:
657
- description: Issues a new JWT token using the current (still valid) token. Requires
658
- a valid Bearer token in the Authorization header.
659
- produces:
660
- - application/json
661
- responses:
662
- "200":
663
- description: OK
664
- schema:
665
- $ref: '#/definitions/models.AuthResponse'
666
- "400":
667
- description: Missing or malformed Authorization header
668
- schema:
669
- $ref: '#/definitions/models.ErrorResponse'
670
- "401":
671
- description: Invalid or expired token
672
- schema:
673
- $ref: '#/definitions/models.ErrorResponse'
674
- security:
675
- - Bearer: []
676
- summary: Refresh token
677
- tags:
678
- - Auth
679
- /auth/register:
680
- post:
681
- consumes:
682
- - application/json
683
- description: Creates a new user account with email and password. Returns a JWT
684
- token and user data.
685
- parameters:
686
- - description: Registration data
687
- in: body
688
- name: body
689
- required: true
690
- schema:
691
- $ref: '#/definitions/models.CreateUserRequest'
692
- produces:
693
- - application/json
694
- responses:
695
- "201":
696
- description: Created
697
- schema:
698
- $ref: '#/definitions/models.AuthResponse'
699
- "400":
700
- description: Invalid request or email already exists
701
- schema:
702
- $ref: '#/definitions/models.ErrorResponse'
703
- summary: Register
704
- tags:
705
- - Auth
706
- /auth/reset-password:
707
- post:
708
- consumes:
709
- - application/json
710
- description: Resets the user's password using the code sent via email. The code
711
- expires after a limited time.
712
- parameters:
713
- - description: Reset data (email, code, new password)
714
- in: body
715
- name: body
716
- required: true
717
- schema:
718
- $ref: '#/definitions/models.ResetPasswordRequest'
719
- produces:
720
- - application/json
721
- responses:
722
- "200":
723
- description: Password changed successfully
724
- schema:
725
- $ref: '#/definitions/models.MessageResponse'
726
- "400":
727
- description: Invalid or expired code, or password does not meet requirements
728
- schema:
729
- $ref: '#/definitions/models.ErrorResponse'
730
- "404":
731
- description: No user found with that email
732
- schema:
733
- $ref: '#/definitions/models.ErrorResponse'
734
- summary: Reset password
735
- tags:
736
- - Auth
737
- /auth/validate:
738
- get:
739
- description: Verifies whether a JWT token is valid and returns the associated
740
- user ID. Requires a valid Bearer token in the Authorization header.
741
- produces:
742
- - application/json
743
- responses:
744
- "200":
745
- description: OK
746
- schema:
747
- $ref: '#/definitions/models.ValidateTokenResponse'
748
- "400":
749
- description: Missing or malformed Authorization header
750
- schema:
751
- $ref: '#/definitions/models.ErrorResponse'
752
- "401":
753
- description: Invalid or expired token
754
- schema:
755
- $ref: '#/definitions/models.ErrorResponse'
756
- security:
757
- - Bearer: []
758
- summary: Validate token
759
- tags:
760
- - Auth
761
- /auth/verify-account:
762
- post:
763
- consumes:
764
- - application/json
765
- description: Activates an account created by an admin. The user sets their password
766
- using the token received by email and receives a JWT token to start their
767
- session immediately.
768
- parameters:
769
- - description: Verification token and chosen password
770
- in: body
771
- name: body
772
- required: true
773
- schema:
774
- $ref: '#/definitions/models.VerifyAccountRequest'
775
- produces:
776
- - application/json
777
- responses:
778
- "200":
779
- description: OK
780
- schema:
781
- $ref: '#/definitions/models.AuthResponse'
782
- "400":
783
- description: Token invalid, already used, or expired
784
- schema:
785
- $ref: '#/definitions/models.ErrorResponse'
786
- "500":
787
- description: Internal Server Error
788
- schema:
789
- $ref: '#/definitions/models.ErrorResponse'
790
- summary: Verify account
791
- tags:
792
- - Auth
793
- /events/log:
794
- get:
795
- description: 'Returns a paginated audit log of all published events. Optionally
796
- filter by event_type_id or publisher_module. Requires permission: `events:log:read`'
797
- parameters:
798
- - default: 1
799
- description: 'Page number (default: 1)'
800
- in: query
801
- minimum: 1
802
- name: page
803
- type: integer
804
- - default: 10
805
- description: 'Items per page (default: 10)'
806
- in: query
807
- minimum: 1
808
- name: pageSize
809
- type: integer
810
- - description: Filter by event type ID
811
- in: query
812
- name: event_type_id
813
- type: integer
814
- - description: Filter by publisher module name
815
- in: query
816
- name: publisher_module
817
- type: string
818
- produces:
819
- - application/json
820
- responses:
821
- "200":
822
- description: OK
823
- schema:
824
- $ref: '#/definitions/models.EventLogListResponse'
825
- "400":
826
- description: Invalid pagination or filter parameters
827
- schema:
828
- $ref: '#/definitions/models.ErrorResponse'
829
- "401":
830
- description: Unauthenticated
831
- schema:
832
- $ref: '#/definitions/models.ErrorResponse'
833
- "403":
834
- description: 'Missing permission: events:log:read'
835
- schema:
836
- $ref: '#/definitions/models.ErrorResponse'
837
- "500":
838
- description: Internal Server Error
839
- schema:
840
- $ref: '#/definitions/models.ErrorResponse'
841
- security:
842
- - Bearer: []
843
- summary: List event log
844
- tags:
845
- - Events
846
- post:
847
- consumes:
848
- - application/json
849
- description: 'Publishes an event to the bus. Creates an event log entry with
850
- status `pending` and notifies all active subscribers. Requires permission:
851
- `events:log:publish`'
852
- parameters:
853
- - description: Event data
854
- in: body
855
- name: body
856
- required: true
857
- schema:
858
- $ref: '#/definitions/models.CreateEventLogRequest'
859
- produces:
860
- - application/json
861
- responses:
862
- "201":
863
- description: Created
864
- schema:
865
- $ref: '#/definitions/models.EventLog'
866
- "400":
867
- description: Invalid request body
868
- schema:
869
- $ref: '#/definitions/models.ErrorResponse'
870
- "401":
871
- description: Unauthenticated
872
- schema:
873
- $ref: '#/definitions/models.ErrorResponse'
874
- "403":
875
- description: 'Missing permission: events:log:publish'
876
- schema:
877
- $ref: '#/definitions/models.ErrorResponse'
878
- security:
879
- - Bearer: []
880
- summary: Publish event
881
- tags:
882
- - Events
883
- /events/log/{id}:
884
- get:
885
- description: 'Returns a single event log entry by ID. Requires permission: `events:log:read`'
886
- parameters:
887
- - description: Event log entry ID
888
- in: path
889
- name: id
890
- required: true
891
- type: integer
892
- produces:
893
- - application/json
894
- responses:
895
- "200":
896
- description: OK
897
- schema:
898
- $ref: '#/definitions/models.EventLog'
899
- "400":
900
- description: Invalid ID
901
- schema:
902
- $ref: '#/definitions/models.ErrorResponse'
903
- "401":
904
- description: Unauthenticated
905
- schema:
906
- $ref: '#/definitions/models.ErrorResponse'
907
- "403":
908
- description: 'Missing permission: events:log:read'
909
- schema:
910
- $ref: '#/definitions/models.ErrorResponse'
911
- "404":
912
- description: Event log entry not found
913
- schema:
914
- $ref: '#/definitions/models.ErrorResponse'
915
- "500":
916
- description: Internal Server Error
917
- schema:
918
- $ref: '#/definitions/models.ErrorResponse'
919
- security:
920
- - Bearer: []
921
- summary: Get event log entry
922
- tags:
923
- - Events
924
- /events/log/{id}/status:
925
- patch:
926
- consumes:
927
- - application/json
928
- description: 'Updates the delivery status of an event log entry. Used by subscribers
929
- to report whether the event was delivered successfully. Requires permission:
930
- `events:log:update-status`'
931
- parameters:
932
- - description: Event log entry ID
933
- in: path
934
- name: id
935
- required: true
936
- type: integer
937
- - description: New status
938
- in: body
939
- name: body
940
- required: true
941
- schema:
942
- $ref: '#/definitions/models.UpdateEventLogStatusRequest'
943
- produces:
944
- - application/json
945
- responses:
946
- "200":
947
- description: OK
948
- schema:
949
- $ref: '#/definitions/models.EventLog'
950
- "400":
951
- description: Invalid ID or status value
952
- schema:
953
- $ref: '#/definitions/models.ErrorResponse'
954
- "401":
955
- description: Unauthenticated
956
- schema:
957
- $ref: '#/definitions/models.ErrorResponse'
958
- "403":
959
- description: 'Missing permission: events:log:update-status'
960
- schema:
961
- $ref: '#/definitions/models.ErrorResponse'
962
- "404":
963
- description: Event log entry not found
964
- schema:
965
- $ref: '#/definitions/models.ErrorResponse'
966
- "500":
967
- description: Internal Server Error
968
- schema:
969
- $ref: '#/definitions/models.ErrorResponse'
970
- security:
971
- - Bearer: []
972
- summary: Update event delivery status
973
- tags:
974
- - Events
975
- /events/subscriptions:
976
- get:
977
- description: 'Returns a paginated list of event subscriptions. Optionally filter
978
- by event_type_id. Requires permission: `events:subscriptions:read`'
979
- parameters:
980
- - default: 1
981
- description: 'Page number (default: 1)'
982
- in: query
983
- minimum: 1
984
- name: page
985
- type: integer
986
- - default: 10
987
- description: 'Items per page (default: 10)'
988
- in: query
989
- minimum: 1
990
- name: pageSize
991
- type: integer
992
- - description: Filter by event type ID
993
- in: query
994
- name: event_type_id
995
- type: integer
996
- produces:
997
- - application/json
998
- responses:
999
- "200":
1000
- description: OK
1001
- schema:
1002
- $ref: '#/definitions/models.EventSubscriptionListResponse'
1003
- "400":
1004
- description: Invalid pagination or filter parameters
1005
- schema:
1006
- $ref: '#/definitions/models.ErrorResponse'
1007
- "401":
1008
- description: Unauthenticated
1009
- schema:
1010
- $ref: '#/definitions/models.ErrorResponse'
1011
- "403":
1012
- description: 'Missing permission: events:subscriptions:read'
1013
- schema:
1014
- $ref: '#/definitions/models.ErrorResponse'
1015
- "500":
1016
- description: Internal Server Error
1017
- schema:
1018
- $ref: '#/definitions/models.ErrorResponse'
1019
- security:
1020
- - Bearer: []
1021
- summary: List event subscriptions
1022
- tags:
1023
- - Events
1024
- post:
1025
- consumes:
1026
- - application/json
1027
- description: 'Subscribes a module to an event type. The API gateway uses this
1028
- to route published events to the correct endpoint. Requires permission: `events:subscriptions:manage`'
1029
- parameters:
1030
- - description: Subscription data
1031
- in: body
1032
- name: body
1033
- required: true
1034
- schema:
1035
- $ref: '#/definitions/models.CreateEventSubscriptionRequest'
1036
- produces:
1037
- - application/json
1038
- responses:
1039
- "201":
1040
- description: Created
1041
- schema:
1042
- $ref: '#/definitions/models.EventSubscription'
1043
- "400":
1044
- description: Invalid request body
1045
- schema:
1046
- $ref: '#/definitions/models.ErrorResponse'
1047
- "401":
1048
- description: Unauthenticated
1049
- schema:
1050
- $ref: '#/definitions/models.ErrorResponse'
1051
- "403":
1052
- description: 'Missing permission: events:subscriptions:manage'
1053
- schema:
1054
- $ref: '#/definitions/models.ErrorResponse'
1055
- security:
1056
- - Bearer: []
1057
- summary: Create event subscription
1058
- tags:
1059
- - Events
1060
- /events/subscriptions/{id}:
1061
- delete:
1062
- description: 'Deletes an event subscription by ID. Requires permission: `events:subscriptions:manage`'
1063
- parameters:
1064
- - description: Subscription ID
1065
- in: path
1066
- name: id
1067
- required: true
1068
- type: integer
1069
- produces:
1070
- - application/json
1071
- responses:
1072
- "200":
1073
- description: OK
1074
- schema:
1075
- $ref: '#/definitions/models.MessageResponse'
1076
- "400":
1077
- description: Invalid ID
1078
- schema:
1079
- $ref: '#/definitions/models.ErrorResponse'
1080
- "401":
1081
- description: Unauthenticated
1082
- schema:
1083
- $ref: '#/definitions/models.ErrorResponse'
1084
- "403":
1085
- description: 'Missing permission: events:subscriptions:manage'
1086
- schema:
1087
- $ref: '#/definitions/models.ErrorResponse'
1088
- "500":
1089
- description: Internal Server Error
1090
- schema:
1091
- $ref: '#/definitions/models.ErrorResponse'
1092
- security:
1093
- - Bearer: []
1094
- summary: Delete event subscription
1095
- tags:
1096
- - Events
1097
- get:
1098
- description: 'Returns an event subscription by ID. Requires permission: `events:subscriptions:read`'
1099
- parameters:
1100
- - description: Subscription ID
1101
- in: path
1102
- name: id
1103
- required: true
1104
- type: integer
1105
- produces:
1106
- - application/json
1107
- responses:
1108
- "200":
1109
- description: OK
1110
- schema:
1111
- $ref: '#/definitions/models.EventSubscription'
1112
- "400":
1113
- description: Invalid ID
1114
- schema:
1115
- $ref: '#/definitions/models.ErrorResponse'
1116
- "401":
1117
- description: Unauthenticated
1118
- schema:
1119
- $ref: '#/definitions/models.ErrorResponse'
1120
- "403":
1121
- description: 'Missing permission: events:subscriptions:read'
1122
- schema:
1123
- $ref: '#/definitions/models.ErrorResponse'
1124
- "404":
1125
- description: Subscription not found
1126
- schema:
1127
- $ref: '#/definitions/models.ErrorResponse'
1128
- "500":
1129
- description: Internal Server Error
1130
- schema:
1131
- $ref: '#/definitions/models.ErrorResponse'
1132
- security:
1133
- - Bearer: []
1134
- summary: Get event subscription
1135
- tags:
1136
- - Events
1137
- put:
1138
- consumes:
1139
- - application/json
1140
- description: 'Updates a subscription''s endpoint URL or active status. All fields
1141
- are optional. Requires permission: `events:subscriptions:manage`'
1142
- parameters:
1143
- - description: Subscription ID
1144
- in: path
1145
- name: id
1146
- required: true
1147
- type: integer
1148
- - description: Fields to update (all optional)
1149
- in: body
1150
- name: body
1151
- required: true
1152
- schema:
1153
- $ref: '#/definitions/models.UpdateEventSubscriptionRequest'
1154
- produces:
1155
- - application/json
1156
- responses:
1157
- "200":
1158
- description: OK
1159
- schema:
1160
- $ref: '#/definitions/models.EventSubscription'
1161
- "400":
1162
- description: Invalid ID or request body
1163
- schema:
1164
- $ref: '#/definitions/models.ErrorResponse'
1165
- "401":
1166
- description: Unauthenticated
1167
- schema:
1168
- $ref: '#/definitions/models.ErrorResponse'
1169
- "403":
1170
- description: 'Missing permission: events:subscriptions:manage'
1171
- schema:
1172
- $ref: '#/definitions/models.ErrorResponse'
1173
- "404":
1174
- description: Subscription not found
1175
- schema:
1176
- $ref: '#/definitions/models.ErrorResponse'
1177
- "500":
1178
- description: Internal Server Error
1179
- schema:
1180
- $ref: '#/definitions/models.ErrorResponse'
1181
- security:
1182
- - Bearer: []
1183
- summary: Update event subscription
1184
- tags:
1185
- - Events
1186
- /events/types:
1187
- get:
1188
- description: 'Returns a paginated list of all registered event types. Requires
1189
- permission: `events:types:read`'
1190
- parameters:
1191
- - default: 1
1192
- description: 'Page number (default: 1)'
1193
- in: query
1194
- minimum: 1
1195
- name: page
1196
- type: integer
1197
- - default: 10
1198
- description: 'Items per page (default: 10)'
1199
- in: query
1200
- minimum: 1
1201
- name: pageSize
1202
- type: integer
1203
- produces:
1204
- - application/json
1205
- responses:
1206
- "200":
1207
- description: OK
1208
- schema:
1209
- $ref: '#/definitions/models.EventTypeListResponse'
1210
- "400":
1211
- description: Invalid pagination parameters
1212
- schema:
1213
- $ref: '#/definitions/models.ErrorResponse'
1214
- "401":
1215
- description: Unauthenticated
1216
- schema:
1217
- $ref: '#/definitions/models.ErrorResponse'
1218
- "403":
1219
- description: 'Missing permission: events:types:read'
1220
- schema:
1221
- $ref: '#/definitions/models.ErrorResponse'
1222
- "500":
1223
- description: Internal Server Error
1224
- schema:
1225
- $ref: '#/definitions/models.ErrorResponse'
1226
- security:
1227
- - Bearer: []
1228
- summary: List event types
1229
- tags:
1230
- - Events
1231
- post:
1232
- consumes:
1233
- - application/json
1234
- description: 'Registers a new event type in the system. Requires permission:
1235
- `events:types:manage`'
1236
- parameters:
1237
- - description: Event type data
1238
- in: body
1239
- name: body
1240
- required: true
1241
- schema:
1242
- $ref: '#/definitions/models.CreateEventTypeRequest'
1243
- produces:
1244
- - application/json
1245
- responses:
1246
- "201":
1247
- description: Created
1248
- schema:
1249
- $ref: '#/definitions/models.EventType'
1250
- "400":
1251
- description: Invalid request body
1252
- schema:
1253
- $ref: '#/definitions/models.ErrorResponse'
1254
- "401":
1255
- description: Unauthenticated
1256
- schema:
1257
- $ref: '#/definitions/models.ErrorResponse'
1258
- "403":
1259
- description: 'Missing permission: events:types:manage'
1260
- schema:
1261
- $ref: '#/definitions/models.ErrorResponse'
1262
- "500":
1263
- description: Internal Server Error
1264
- schema:
1265
- $ref: '#/definitions/models.ErrorResponse'
1266
- security:
1267
- - Bearer: []
1268
- summary: Create event type
1269
- tags:
1270
- - Events
1271
- /events/types/{id}:
1272
- delete:
1273
- description: 'Soft-deletes an event type by ID. Requires permission: `events:types:manage`'
1274
- parameters:
1275
- - description: Event type ID
1276
- in: path
1277
- name: id
1278
- required: true
1279
- type: integer
1280
- produces:
1281
- - application/json
1282
- responses:
1283
- "200":
1284
- description: OK
1285
- schema:
1286
- $ref: '#/definitions/models.MessageResponse'
1287
- "400":
1288
- description: Invalid ID
1289
- schema:
1290
- $ref: '#/definitions/models.ErrorResponse'
1291
- "401":
1292
- description: Unauthenticated
1293
- schema:
1294
- $ref: '#/definitions/models.ErrorResponse'
1295
- "403":
1296
- description: 'Missing permission: events:types:manage'
1297
- schema:
1298
- $ref: '#/definitions/models.ErrorResponse'
1299
- "500":
1300
- description: Internal Server Error
1301
- schema:
1302
- $ref: '#/definitions/models.ErrorResponse'
1303
- security:
1304
- - Bearer: []
1305
- summary: Delete event type
1306
- tags:
1307
- - Events
1308
- get:
1309
- description: 'Returns an event type by ID. Requires permission: `events:types:read`'
1310
- parameters:
1311
- - description: Event type ID
1312
- in: path
1313
- name: id
1314
- required: true
1315
- type: integer
1316
- produces:
1317
- - application/json
1318
- responses:
1319
- "200":
1320
- description: OK
1321
- schema:
1322
- $ref: '#/definitions/models.EventType'
1323
- "400":
1324
- description: Invalid ID
1325
- schema:
1326
- $ref: '#/definitions/models.ErrorResponse'
1327
- "401":
1328
- description: Unauthenticated
1329
- schema:
1330
- $ref: '#/definitions/models.ErrorResponse'
1331
- "403":
1332
- description: 'Missing permission: events:types:read'
1333
- schema:
1334
- $ref: '#/definitions/models.ErrorResponse'
1335
- "404":
1336
- description: Event type not found
1337
- schema:
1338
- $ref: '#/definitions/models.ErrorResponse'
1339
- "500":
1340
- description: Internal Server Error
1341
- schema:
1342
- $ref: '#/definitions/models.ErrorResponse'
1343
- security:
1344
- - Bearer: []
1345
- summary: Get event type
1346
- tags:
1347
- - Events
1348
- put:
1349
- consumes:
1350
- - application/json
1351
- description: 'Updates an event type''s fields. All fields are optional. Requires
1352
- permission: `events:types:manage`'
1353
- parameters:
1354
- - description: Event type ID
1355
- in: path
1356
- name: id
1357
- required: true
1358
- type: integer
1359
- - description: Fields to update (all optional)
1360
- in: body
1361
- name: body
1362
- required: true
1363
- schema:
1364
- $ref: '#/definitions/models.UpdateEventTypeRequest'
1365
- produces:
1366
- - application/json
1367
- responses:
1368
- "200":
1369
- description: OK
1370
- schema:
1371
- $ref: '#/definitions/models.EventType'
1372
- "400":
1373
- description: Invalid ID or request body
1374
- schema:
1375
- $ref: '#/definitions/models.ErrorResponse'
1376
- "401":
1377
- description: Unauthenticated
1378
- schema:
1379
- $ref: '#/definitions/models.ErrorResponse'
1380
- "403":
1381
- description: 'Missing permission: events:types:manage'
1382
- schema:
1383
- $ref: '#/definitions/models.ErrorResponse'
1384
- "404":
1385
- description: Event type not found
1386
- schema:
1387
- $ref: '#/definitions/models.ErrorResponse'
1388
- "500":
1389
- description: Internal Server Error
1390
- schema:
1391
- $ref: '#/definitions/models.ErrorResponse'
1392
- security:
1393
- - Bearer: []
1394
- summary: Update event type
1395
- tags:
1396
- - Events
1397
- /locations:
1398
- get:
1399
- description: 'Returns a paginated list of all locations. Requires permission:
1400
- `locations:read`'
1401
- parameters:
1402
- - default: 1
1403
- description: 'Page number (default: 1)'
1404
- in: query
1405
- minimum: 1
1406
- name: page
1407
- type: integer
1408
- - default: 10
1409
- description: 'Items per page (default: 10)'
1410
- in: query
1411
- minimum: 1
1412
- name: pageSize
1413
- type: integer
1414
- produces:
1415
- - application/json
1416
- responses:
1417
- "200":
1418
- description: OK
1419
- schema:
1420
- $ref: '#/definitions/models.LocationListResponse'
1421
- "400":
1422
- description: Invalid pagination parameters
1423
- schema:
1424
- $ref: '#/definitions/models.ErrorResponse'
1425
- "401":
1426
- description: Unauthenticated
1427
- schema:
1428
- $ref: '#/definitions/models.ErrorResponse'
1429
- "403":
1430
- description: 'Missing permission: locations:read'
1431
- schema:
1432
- $ref: '#/definitions/models.ErrorResponse'
1433
- "500":
1434
- description: Internal Server Error
1435
- schema:
1436
- $ref: '#/definitions/models.ErrorResponse'
1437
- security:
1438
- - Bearer: []
1439
- summary: List locations
1440
- tags:
1441
- - Locations
1442
- post:
1443
- consumes:
1444
- - application/json
1445
- description: 'Creates a new location. Requires permission: `locations:manage`'
1446
- parameters:
1447
- - description: Location data
1448
- in: body
1449
- name: body
1450
- required: true
1451
- schema:
1452
- $ref: '#/definitions/models.CreateLocationRequest'
1453
- produces:
1454
- - application/json
1455
- responses:
1456
- "201":
1457
- description: Created
1458
- schema:
1459
- $ref: '#/definitions/models.Location'
1460
- "400":
1461
- description: Invalid request body
1462
- schema:
1463
- $ref: '#/definitions/models.ErrorResponse'
1464
- "401":
1465
- description: Unauthenticated
1466
- schema:
1467
- $ref: '#/definitions/models.ErrorResponse'
1468
- "403":
1469
- description: 'Missing permission: locations:manage'
1470
- schema:
1471
- $ref: '#/definitions/models.ErrorResponse'
1472
- security:
1473
- - Bearer: []
1474
- summary: Create location
1475
- tags:
1476
- - Locations
1477
- /locations/{id}:
1478
- delete:
1479
- description: 'Soft-deletes a location by ID. Requires permission: `locations:manage`'
1480
- parameters:
1481
- - description: Location ID
1482
- in: path
1483
- name: id
1484
- required: true
1485
- type: integer
1486
- produces:
1487
- - application/json
1488
- responses:
1489
- "200":
1490
- description: OK
1491
- schema:
1492
- $ref: '#/definitions/models.MessageResponse'
1493
- "400":
1494
- description: Invalid location ID
1495
- schema:
1496
- $ref: '#/definitions/models.ErrorResponse'
1497
- "401":
1498
- description: Unauthenticated
1499
- schema:
1500
- $ref: '#/definitions/models.ErrorResponse'
1501
- "403":
1502
- description: 'Missing permission: locations:manage'
1503
- schema:
1504
- $ref: '#/definitions/models.ErrorResponse'
1505
- "404":
1506
- description: Location not found
1507
- schema:
1508
- $ref: '#/definitions/models.ErrorResponse'
1509
- "500":
1510
- description: Internal Server Error
1511
- schema:
1512
- $ref: '#/definitions/models.ErrorResponse'
1513
- security:
1514
- - Bearer: []
1515
- summary: Delete location
1516
- tags:
1517
- - Locations
1518
- get:
1519
- description: 'Returns a location by ID. Requires permission: `locations:read`'
1520
- parameters:
1521
- - description: Location ID
1522
- in: path
1523
- name: id
1524
- required: true
1525
- type: integer
1526
- produces:
1527
- - application/json
1528
- responses:
1529
- "200":
1530
- description: OK
1531
- schema:
1532
- $ref: '#/definitions/models.Location'
1533
- "400":
1534
- description: Invalid location ID
1535
- schema:
1536
- $ref: '#/definitions/models.ErrorResponse'
1537
- "401":
1538
- description: Unauthenticated
1539
- schema:
1540
- $ref: '#/definitions/models.ErrorResponse'
1541
- "403":
1542
- description: 'Missing permission: locations:read'
1543
- schema:
1544
- $ref: '#/definitions/models.ErrorResponse'
1545
- "404":
1546
- description: Location not found
1547
- schema:
1548
- $ref: '#/definitions/models.ErrorResponse'
1549
- "500":
1550
- description: Internal Server Error
1551
- schema:
1552
- $ref: '#/definitions/models.ErrorResponse'
1553
- security:
1554
- - Bearer: []
1555
- summary: Get location
1556
- tags:
1557
- - Locations
1558
- put:
1559
- consumes:
1560
- - application/json
1561
- description: 'Updates a location''s fields. All fields are optional. Requires
1562
- permission: `locations:manage`'
1563
- parameters:
1564
- - description: Location ID
1565
- in: path
1566
- name: id
1567
- required: true
1568
- type: integer
1569
- - description: Fields to update (all optional)
1570
- in: body
1571
- name: body
1572
- required: true
1573
- schema:
1574
- $ref: '#/definitions/models.UpdateLocationRequest'
1575
- produces:
1576
- - application/json
1577
- responses:
1578
- "200":
1579
- description: OK
1580
- schema:
1581
- $ref: '#/definitions/models.Location'
1582
- "400":
1583
- description: Invalid location ID or request body
1584
- schema:
1585
- $ref: '#/definitions/models.ErrorResponse'
1586
- "401":
1587
- description: Unauthenticated
1588
- schema:
1589
- $ref: '#/definitions/models.ErrorResponse'
1590
- "403":
1591
- description: 'Missing permission: locations:manage'
1592
- schema:
1593
- $ref: '#/definitions/models.ErrorResponse'
1594
- "404":
1595
- description: Location not found
1596
- schema:
1597
- $ref: '#/definitions/models.ErrorResponse'
1598
- "500":
1599
- description: Internal Server Error
1600
- schema:
1601
- $ref: '#/definitions/models.ErrorResponse'
1602
- security:
1603
- - Bearer: []
1604
- summary: Update location
1605
- tags:
1606
- - Locations
1607
- /permissions:
1608
- get:
1609
- description: 'Returns a paginated list of all permissions. Requires permission:
1610
- `permissions:read`'
1611
- parameters:
1612
- - default: 1
1613
- description: 'Page number (default: 1)'
1614
- in: query
1615
- minimum: 1
1616
- name: page
1617
- type: integer
1618
- - default: 10
1619
- description: 'Items per page (default: 10)'
1620
- in: query
1621
- minimum: 1
1622
- name: pageSize
1623
- type: integer
1624
- produces:
1625
- - application/json
1626
- responses:
1627
- "200":
1628
- description: OK
1629
- schema:
1630
- $ref: '#/definitions/models.PermissionListResponse'
1631
- "400":
1632
- description: Invalid pagination parameters
1633
- schema:
1634
- $ref: '#/definitions/models.ErrorResponse'
1635
- "401":
1636
- description: Unauthenticated
1637
- schema:
1638
- $ref: '#/definitions/models.ErrorResponse'
1639
- "403":
1640
- description: 'Missing permission: permissions:read'
1641
- schema:
1642
- $ref: '#/definitions/models.ErrorResponse'
1643
- "500":
1644
- description: Internal Server Error
1645
- schema:
1646
- $ref: '#/definitions/models.ErrorResponse'
1647
- security:
1648
- - Bearer: []
1649
- summary: List permissions
1650
- tags:
1651
- - Permissions
1652
- post:
1653
- consumes:
1654
- - application/json
1655
- description: 'Creates a new permission. Permission names follow the format `resource:action`
1656
- or `resource:action:sub-action` (e.g. `users:read`, `users:roles:manage`).
1657
- Requires permission: `permissions:manage`'
1658
- parameters:
1659
- - description: Permission data
1660
- in: body
1661
- name: body
1662
- required: true
1663
- schema:
1664
- $ref: '#/definitions/models.CreatePermissionRequest'
1665
- produces:
1666
- - application/json
1667
- responses:
1668
- "201":
1669
- description: Created
1670
- schema:
1671
- $ref: '#/definitions/models.Permission'
1672
- "400":
1673
- description: Invalid request body
1674
- schema:
1675
- $ref: '#/definitions/models.ErrorResponse'
1676
- "401":
1677
- description: Unauthenticated
1678
- schema:
1679
- $ref: '#/definitions/models.ErrorResponse'
1680
- "403":
1681
- description: 'Missing permission: permissions:manage'
1682
- schema:
1683
- $ref: '#/definitions/models.ErrorResponse'
1684
- security:
1685
- - Bearer: []
1686
- summary: Create permission
1687
- tags:
1688
- - Permissions
1689
- /permissions/{id}:
1690
- delete:
1691
- description: 'Soft-deletes a permission by ID. Requires permission: `permissions:manage`'
1692
- parameters:
1693
- - description: Permission ID
1694
- in: path
1695
- name: id
1696
- required: true
1697
- type: integer
1698
- produces:
1699
- - application/json
1700
- responses:
1701
- "200":
1702
- description: OK
1703
- schema:
1704
- $ref: '#/definitions/models.MessageResponse'
1705
- "400":
1706
- description: Invalid permission ID
1707
- schema:
1708
- $ref: '#/definitions/models.ErrorResponse'
1709
- "401":
1710
- description: Unauthenticated
1711
- schema:
1712
- $ref: '#/definitions/models.ErrorResponse'
1713
- "403":
1714
- description: 'Missing permission: permissions:manage'
1715
- schema:
1716
- $ref: '#/definitions/models.ErrorResponse'
1717
- "500":
1718
- description: Internal Server Error
1719
- schema:
1720
- $ref: '#/definitions/models.ErrorResponse'
1721
- security:
1722
- - Bearer: []
1723
- summary: Delete permission
1724
- tags:
1725
- - Permissions
1726
- get:
1727
- description: 'Returns a permission by ID including the roles it is assigned
1728
- to. Requires permission: `permissions:read`'
1729
- parameters:
1730
- - description: Permission ID
1731
- in: path
1732
- name: id
1733
- required: true
1734
- type: integer
1735
- produces:
1736
- - application/json
1737
- responses:
1738
- "200":
1739
- description: OK
1740
- schema:
1741
- $ref: '#/definitions/models.Permission'
1742
- "400":
1743
- description: Invalid permission ID
1744
- schema:
1745
- $ref: '#/definitions/models.ErrorResponse'
1746
- "401":
1747
- description: Unauthenticated
1748
- schema:
1749
- $ref: '#/definitions/models.ErrorResponse'
1750
- "403":
1751
- description: 'Missing permission: permissions:read'
1752
- schema:
1753
- $ref: '#/definitions/models.ErrorResponse'
1754
- "404":
1755
- description: Permission not found
1756
- schema:
1757
- $ref: '#/definitions/models.ErrorResponse'
1758
- "500":
1759
- description: Internal Server Error
1760
- schema:
1761
- $ref: '#/definitions/models.ErrorResponse'
1762
- security:
1763
- - Bearer: []
1764
- summary: Get permission
1765
- tags:
1766
- - Permissions
1767
- put:
1768
- consumes:
1769
- - application/json
1770
- description: 'Updates a permission''s name. Requires permission: `permissions:manage`'
1771
- parameters:
1772
- - description: Permission ID
1773
- in: path
1774
- name: id
1775
- required: true
1776
- type: integer
1777
- - description: Fields to update
1778
- in: body
1779
- name: body
1780
- required: true
1781
- schema:
1782
- $ref: '#/definitions/models.UpdatePermissionRequest'
1783
- produces:
1784
- - application/json
1785
- responses:
1786
- "200":
1787
- description: OK
1788
- schema:
1789
- $ref: '#/definitions/models.Permission'
1790
- "400":
1791
- description: Invalid permission ID or request body
1792
- schema:
1793
- $ref: '#/definitions/models.ErrorResponse'
1794
- "401":
1795
- description: Unauthenticated
1796
- schema:
1797
- $ref: '#/definitions/models.ErrorResponse'
1798
- "403":
1799
- description: 'Missing permission: permissions:manage'
1800
- schema:
1801
- $ref: '#/definitions/models.ErrorResponse'
1802
- "500":
1803
- description: Internal Server Error
1804
- schema:
1805
- $ref: '#/definitions/models.ErrorResponse'
1806
- security:
1807
- - Bearer: []
1808
- summary: Update permission
1809
- tags:
1810
- - Permissions
1811
- /roles:
1812
- get:
1813
- description: 'Returns a paginated list of all roles. Requires permission: `roles:read`'
1814
- parameters:
1815
- - default: 1
1816
- description: 'Page number (default: 1)'
1817
- in: query
1818
- minimum: 1
1819
- name: page
1820
- type: integer
1821
- - default: 10
1822
- description: 'Items per page (default: 10)'
1823
- in: query
1824
- minimum: 1
1825
- name: pageSize
1826
- type: integer
1827
- produces:
1828
- - application/json
1829
- responses:
1830
- "200":
1831
- description: OK
1832
- schema:
1833
- $ref: '#/definitions/models.RoleListResponse'
1834
- "400":
1835
- description: Invalid pagination parameters
1836
- schema:
1837
- $ref: '#/definitions/models.ErrorResponse'
1838
- "401":
1839
- description: Unauthenticated
1840
- schema:
1841
- $ref: '#/definitions/models.ErrorResponse'
1842
- "403":
1843
- description: 'Missing permission: roles:read'
1844
- schema:
1845
- $ref: '#/definitions/models.ErrorResponse'
1846
- "500":
1847
- description: Internal Server Error
1848
- schema:
1849
- $ref: '#/definitions/models.ErrorResponse'
1850
- security:
1851
- - Bearer: []
1852
- summary: List roles
1853
- tags:
1854
- - Roles
1855
- post:
1856
- consumes:
1857
- - application/json
1858
- description: 'Creates a new role. Requires permission: `roles:manage`'
1859
- parameters:
1860
- - description: Role data
1861
- in: body
1862
- name: body
1863
- required: true
1864
- schema:
1865
- $ref: '#/definitions/models.CreateRoleRequest'
1866
- produces:
1867
- - application/json
1868
- responses:
1869
- "201":
1870
- description: Created
1871
- schema:
1872
- $ref: '#/definitions/models.Role'
1873
- "400":
1874
- description: Invalid request body
1875
- schema:
1876
- $ref: '#/definitions/models.ErrorResponse'
1877
- "401":
1878
- description: Unauthenticated
1879
- schema:
1880
- $ref: '#/definitions/models.ErrorResponse'
1881
- "403":
1882
- description: 'Missing permission: roles:manage'
1883
- schema:
1884
- $ref: '#/definitions/models.ErrorResponse'
1885
- security:
1886
- - Bearer: []
1887
- summary: Create role
1888
- tags:
1889
- - Roles
1890
- /roles/{id}:
1891
- delete:
1892
- description: 'Soft-deletes a role by ID. Requires permission: `roles:manage`'
1893
- parameters:
1894
- - description: Role ID
1895
- in: path
1896
- name: id
1897
- required: true
1898
- type: integer
1899
- produces:
1900
- - application/json
1901
- responses:
1902
- "200":
1903
- description: OK
1904
- schema:
1905
- $ref: '#/definitions/models.MessageResponse'
1906
- "400":
1907
- description: Invalid role ID
1908
- schema:
1909
- $ref: '#/definitions/models.ErrorResponse'
1910
- "401":
1911
- description: Unauthenticated
1912
- schema:
1913
- $ref: '#/definitions/models.ErrorResponse'
1914
- "403":
1915
- description: 'Missing permission: roles:manage'
1916
- schema:
1917
- $ref: '#/definitions/models.ErrorResponse'
1918
- "500":
1919
- description: Internal Server Error
1920
- schema:
1921
- $ref: '#/definitions/models.ErrorResponse'
1922
- security:
1923
- - Bearer: []
1924
- summary: Delete role
1925
- tags:
1926
- - Roles
1927
- get:
1928
- description: 'Returns a role by ID including its assigned permissions. Requires
1929
- permission: `roles:read`'
1930
- parameters:
1931
- - description: Role ID
1932
- in: path
1933
- name: id
1934
- required: true
1935
- type: integer
1936
- produces:
1937
- - application/json
1938
- responses:
1939
- "200":
1940
- description: OK
1941
- schema:
1942
- $ref: '#/definitions/models.Role'
1943
- "400":
1944
- description: Invalid role ID
1945
- schema:
1946
- $ref: '#/definitions/models.ErrorResponse'
1947
- "401":
1948
- description: Unauthenticated
1949
- schema:
1950
- $ref: '#/definitions/models.ErrorResponse'
1951
- "403":
1952
- description: 'Missing permission: roles:read'
1953
- schema:
1954
- $ref: '#/definitions/models.ErrorResponse'
1955
- "404":
1956
- description: Role not found
1957
- schema:
1958
- $ref: '#/definitions/models.ErrorResponse'
1959
- "500":
1960
- description: Internal Server Error
1961
- schema:
1962
- $ref: '#/definitions/models.ErrorResponse'
1963
- security:
1964
- - Bearer: []
1965
- summary: Get role
1966
- tags:
1967
- - Roles
1968
- put:
1969
- consumes:
1970
- - application/json
1971
- description: 'Updates a role''s name. Requires permission: `roles:manage`'
1972
- parameters:
1973
- - description: Role ID
1974
- in: path
1975
- name: id
1976
- required: true
1977
- type: integer
1978
- - description: Fields to update
1979
- in: body
1980
- name: body
1981
- required: true
1982
- schema:
1983
- $ref: '#/definitions/models.UpdateRoleRequest'
1984
- produces:
1985
- - application/json
1986
- responses:
1987
- "200":
1988
- description: OK
1989
- schema:
1990
- $ref: '#/definitions/models.Role'
1991
- "400":
1992
- description: Invalid role ID or request body
1993
- schema:
1994
- $ref: '#/definitions/models.ErrorResponse'
1995
- "401":
1996
- description: Unauthenticated
1997
- schema:
1998
- $ref: '#/definitions/models.ErrorResponse'
1999
- "403":
2000
- description: 'Missing permission: roles:manage'
2001
- schema:
2002
- $ref: '#/definitions/models.ErrorResponse'
2003
- "500":
2004
- description: Internal Server Error
2005
- schema:
2006
- $ref: '#/definitions/models.ErrorResponse'
2007
- security:
2008
- - Bearer: []
2009
- summary: Update role
2010
- tags:
2011
- - Roles
2012
- /roles/{id}/permissions:
2013
- post:
2014
- consumes:
2015
- - application/json
2016
- description: 'Assigns an existing permission to a role. Users with this role
2017
- will gain that permission. Requires permission: `roles:permissions:manage`'
2018
- parameters:
2019
- - description: Role ID
2020
- in: path
2021
- name: id
2022
- required: true
2023
- type: integer
2024
- - description: Permission to assign
2025
- in: body
2026
- name: body
2027
- required: true
2028
- schema:
2029
- $ref: '#/definitions/models.AssignPermissionToRoleRequest'
2030
- produces:
2031
- - application/json
2032
- responses:
2033
- "200":
2034
- description: OK
2035
- schema:
2036
- $ref: '#/definitions/models.MessageResponse'
2037
- "400":
2038
- description: Invalid role ID or request body
2039
- schema:
2040
- $ref: '#/definitions/models.ErrorResponse'
2041
- "401":
2042
- description: Unauthenticated
2043
- schema:
2044
- $ref: '#/definitions/models.ErrorResponse'
2045
- "403":
2046
- description: 'Missing permission: roles:permissions:manage'
2047
- schema:
2048
- $ref: '#/definitions/models.ErrorResponse'
2049
- "500":
2050
- description: Internal Server Error
2051
- schema:
2052
- $ref: '#/definitions/models.ErrorResponse'
2053
- security:
2054
- - Bearer: []
2055
- summary: Assign permission to role
2056
- tags:
2057
- - Roles
2058
- /roles/{id}/permissions/{permissionId}:
2059
- delete:
2060
- description: 'Removes a permission from a role. Users with this role will lose
2061
- that permission. Requires permission: `roles:permissions:manage`'
2062
- parameters:
2063
- - description: Role ID
2064
- in: path
2065
- name: id
2066
- required: true
2067
- type: integer
2068
- - description: Permission ID
2069
- in: path
2070
- name: permissionId
2071
- required: true
2072
- type: integer
2073
- produces:
2074
- - application/json
2075
- responses:
2076
- "200":
2077
- description: OK
2078
- schema:
2079
- $ref: '#/definitions/models.MessageResponse'
2080
- "400":
2081
- description: Invalid role ID or permission ID
2082
- schema:
2083
- $ref: '#/definitions/models.ErrorResponse'
2084
- "401":
2085
- description: Unauthenticated
2086
- schema:
2087
- $ref: '#/definitions/models.ErrorResponse'
2088
- "403":
2089
- description: 'Missing permission: roles:permissions:manage'
2090
- schema:
2091
- $ref: '#/definitions/models.ErrorResponse'
2092
- "500":
2093
- description: Internal Server Error
2094
- schema:
2095
- $ref: '#/definitions/models.ErrorResponse'
2096
- security:
2097
- - Bearer: []
2098
- summary: Remove permission from role
2099
- tags:
2100
- - Roles
2101
- /specialities:
2102
- get:
2103
- description: 'Returns a paginated list of all specialities. Requires permission:
2104
- `specialities:read`'
2105
- parameters:
2106
- - default: 1
2107
- description: 'Page number (default: 1)'
2108
- in: query
2109
- minimum: 1
2110
- name: page
2111
- type: integer
2112
- - default: 10
2113
- description: 'Items per page (default: 10)'
2114
- in: query
2115
- minimum: 1
2116
- name: pageSize
2117
- type: integer
2118
- produces:
2119
- - application/json
2120
- responses:
2121
- "200":
2122
- description: OK
2123
- schema:
2124
- $ref: '#/definitions/models.SpecialityListResponse'
2125
- "400":
2126
- description: Invalid pagination parameters
2127
- schema:
2128
- $ref: '#/definitions/models.ErrorResponse'
2129
- "401":
2130
- description: Unauthenticated
2131
- schema:
2132
- $ref: '#/definitions/models.ErrorResponse'
2133
- "403":
2134
- description: 'Missing permission: specialities:read'
2135
- schema:
2136
- $ref: '#/definitions/models.ErrorResponse'
2137
- "500":
2138
- description: Internal Server Error
2139
- schema:
2140
- $ref: '#/definitions/models.ErrorResponse'
2141
- security:
2142
- - Bearer: []
2143
- summary: List specialities
2144
- tags:
2145
- - Specialities
2146
- post:
2147
- consumes:
2148
- - application/json
2149
- description: 'Creates a new speciality. Requires permission: `specialities:manage`'
2150
- parameters:
2151
- - description: Speciality data
2152
- in: body
2153
- name: body
2154
- required: true
2155
- schema:
2156
- $ref: '#/definitions/models.CreateSpecialityRequest'
2157
- produces:
2158
- - application/json
2159
- responses:
2160
- "201":
2161
- description: Created
2162
- schema:
2163
- $ref: '#/definitions/models.Speciality'
2164
- "400":
2165
- description: Invalid request body
2166
- schema:
2167
- $ref: '#/definitions/models.ErrorResponse'
2168
- "401":
2169
- description: Unauthenticated
2170
- schema:
2171
- $ref: '#/definitions/models.ErrorResponse'
2172
- "403":
2173
- description: 'Missing permission: specialities:manage'
2174
- schema:
2175
- $ref: '#/definitions/models.ErrorResponse'
2176
- security:
2177
- - Bearer: []
2178
- summary: Create speciality
2179
- tags:
2180
- - Specialities
2181
- /specialities/{id}:
2182
- delete:
2183
- description: 'Soft-deletes a speciality by ID. Requires permission: `specialities:manage`'
2184
- parameters:
2185
- - description: Speciality ID
2186
- in: path
2187
- name: id
2188
- required: true
2189
- type: integer
2190
- produces:
2191
- - application/json
2192
- responses:
2193
- "200":
2194
- description: OK
2195
- schema:
2196
- $ref: '#/definitions/models.MessageResponse'
2197
- "400":
2198
- description: Invalid speciality ID
2199
- schema:
2200
- $ref: '#/definitions/models.ErrorResponse'
2201
- "401":
2202
- description: Unauthenticated
2203
- schema:
2204
- $ref: '#/definitions/models.ErrorResponse'
2205
- "403":
2206
- description: 'Missing permission: specialities:manage'
2207
- schema:
2208
- $ref: '#/definitions/models.ErrorResponse'
2209
- "500":
2210
- description: Internal Server Error
2211
- schema:
2212
- $ref: '#/definitions/models.ErrorResponse'
2213
- security:
2214
- - Bearer: []
2215
- summary: Delete speciality
2216
- tags:
2217
- - Specialities
2218
- get:
2219
- description: 'Returns a speciality by ID. Requires permission: `specialities:read`'
2220
- parameters:
2221
- - description: Speciality ID
2222
- in: path
2223
- name: id
2224
- required: true
2225
- type: integer
2226
- produces:
2227
- - application/json
2228
- responses:
2229
- "200":
2230
- description: OK
2231
- schema:
2232
- $ref: '#/definitions/models.Speciality'
2233
- "400":
2234
- description: Invalid speciality ID
2235
- schema:
2236
- $ref: '#/definitions/models.ErrorResponse'
2237
- "401":
2238
- description: Unauthenticated
2239
- schema:
2240
- $ref: '#/definitions/models.ErrorResponse'
2241
- "403":
2242
- description: 'Missing permission: specialities:read'
2243
- schema:
2244
- $ref: '#/definitions/models.ErrorResponse'
2245
- "404":
2246
- description: Speciality not found
2247
- schema:
2248
- $ref: '#/definitions/models.ErrorResponse'
2249
- "500":
2250
- description: Internal Server Error
2251
- schema:
2252
- $ref: '#/definitions/models.ErrorResponse'
2253
- security:
2254
- - Bearer: []
2255
- summary: Get speciality
2256
- tags:
2257
- - Specialities
2258
- put:
2259
- consumes:
2260
- - application/json
2261
- description: 'Updates a speciality''s name. Requires permission: `specialities:manage`'
2262
- parameters:
2263
- - description: Speciality ID
2264
- in: path
2265
- name: id
2266
- required: true
2267
- type: integer
2268
- - description: Fields to update
2269
- in: body
2270
- name: body
2271
- required: true
2272
- schema:
2273
- $ref: '#/definitions/models.UpdateSpecialityRequest'
2274
- produces:
2275
- - application/json
2276
- responses:
2277
- "200":
2278
- description: OK
2279
- schema:
2280
- $ref: '#/definitions/models.Speciality'
2281
- "400":
2282
- description: Invalid speciality ID or request body
2283
- schema:
2284
- $ref: '#/definitions/models.ErrorResponse'
2285
- "401":
2286
- description: Unauthenticated
2287
- schema:
2288
- $ref: '#/definitions/models.ErrorResponse'
2289
- "403":
2290
- description: 'Missing permission: specialities:manage'
2291
- schema:
2292
- $ref: '#/definitions/models.ErrorResponse'
2293
- "500":
2294
- description: Internal Server Error
2295
- schema:
2296
- $ref: '#/definitions/models.ErrorResponse'
2297
- security:
2298
- - Bearer: []
2299
- summary: Update speciality
2300
- tags:
2301
- - Specialities
2302
- /users:
2303
- get:
2304
- description: 'Returns a paginated list of all users. Requires permission: `users:read`'
2305
- parameters:
2306
- - default: 1
2307
- description: 'Page number (default: 1)'
2308
- in: query
2309
- minimum: 1
2310
- name: page
2311
- type: integer
2312
- - default: 10
2313
- description: 'Items per page (default: 10)'
2314
- in: query
2315
- minimum: 1
2316
- name: pageSize
2317
- type: integer
2318
- produces:
2319
- - application/json
2320
- responses:
2321
- "200":
2322
- description: OK
2323
- schema:
2324
- $ref: '#/definitions/models.UserListResponse'
2325
- "400":
2326
- description: Invalid pagination parameters
2327
- schema:
2328
- $ref: '#/definitions/models.ErrorResponse'
2329
- "401":
2330
- description: Unauthenticated
2331
- schema:
2332
- $ref: '#/definitions/models.ErrorResponse'
2333
- "403":
2334
- description: 'Missing permission: users:read'
2335
- schema:
2336
- $ref: '#/definitions/models.ErrorResponse'
2337
- "500":
2338
- description: Internal Server Error
2339
- schema:
2340
- $ref: '#/definitions/models.ErrorResponse'
2341
- security:
2342
- - Bearer: []
2343
- summary: List users
2344
- tags:
2345
- - Users
2346
- post:
2347
- consumes:
2348
- - application/json
2349
- description: 'An admin creates an account for another person and assigns them
2350
- a role. The system sends a 48-hour activation email; the user sets their password
2351
- via /auth/verify-account. Requires permission: `users:create:role:{roleID}`'
2352
- parameters:
2353
- - description: New user data including role assignment
2354
- in: body
2355
- name: body
2356
- required: true
2357
- schema:
2358
- $ref: '#/definitions/models.AdminCreateUserRequest'
2359
- produces:
2360
- - application/json
2361
- responses:
2362
- "201":
2363
- description: Created
2364
- schema:
2365
- $ref: '#/definitions/models.User'
2366
- "400":
2367
- description: Bad Request
2368
- schema:
2369
- $ref: '#/definitions/models.ErrorResponse'
2370
- "401":
2371
- description: Unauthenticated
2372
- schema:
2373
- $ref: '#/definitions/models.ErrorResponse'
2374
- "403":
2375
- description: 'Missing permission: users:create:role:{roleID}'
2376
- schema:
2377
- $ref: '#/definitions/models.ErrorResponse'
2378
- "409":
2379
- description: Email already exists
2380
- schema:
2381
- $ref: '#/definitions/models.ErrorResponse'
2382
- "500":
2383
- description: Internal Server Error
2384
- schema:
2385
- $ref: '#/definitions/models.ErrorResponse'
2386
- security:
2387
- - Bearer: []
2388
- summary: Create user (admin)
2389
- tags:
2390
- - Users
2391
- /users/{id}:
2392
- delete:
2393
- description: 'Soft-deletes a user by ID. The user is marked as deleted but remains
2394
- in the database. Requires permission: `users:delete`'
2395
- parameters:
2396
- - description: User ID
2397
- in: path
2398
- name: id
2399
- required: true
2400
- type: integer
2401
- produces:
2402
- - application/json
2403
- responses:
2404
- "200":
2405
- description: OK
2406
- schema:
2407
- $ref: '#/definitions/models.MessageResponse'
2408
- "400":
2409
- description: Invalid user ID
2410
- schema:
2411
- $ref: '#/definitions/models.ErrorResponse'
2412
- "401":
2413
- description: Unauthenticated
2414
- schema:
2415
- $ref: '#/definitions/models.ErrorResponse'
2416
- "403":
2417
- description: 'Missing permission: users:delete'
2418
- schema:
2419
- $ref: '#/definitions/models.ErrorResponse'
2420
- "500":
2421
- description: Internal Server Error
2422
- schema:
2423
- $ref: '#/definitions/models.ErrorResponse'
2424
- security:
2425
- - Bearer: []
2426
- summary: Delete user
2427
- tags:
2428
- - Users
2429
- get:
2430
- description: 'Returns a user by ID including their roles, locations and specialities.
2431
- Requires permission: `users:read`'
2432
- parameters:
2433
- - description: User ID
2434
- in: path
2435
- name: id
2436
- required: true
2437
- type: integer
2438
- produces:
2439
- - application/json
2440
- responses:
2441
- "200":
2442
- description: OK
2443
- schema:
2444
- $ref: '#/definitions/models.User'
2445
- "400":
2446
- description: Invalid user ID
2447
- schema:
2448
- $ref: '#/definitions/models.ErrorResponse'
2449
- "401":
2450
- description: Unauthenticated
2451
- schema:
2452
- $ref: '#/definitions/models.ErrorResponse'
2453
- "403":
2454
- description: 'Missing permission: users:read'
2455
- schema:
2456
- $ref: '#/definitions/models.ErrorResponse'
2457
- "404":
2458
- description: User not found
2459
- schema:
2460
- $ref: '#/definitions/models.ErrorResponse'
2461
- "500":
2462
- description: Internal Server Error
2463
- schema:
2464
- $ref: '#/definitions/models.ErrorResponse'
2465
- security:
2466
- - Bearer: []
2467
- summary: Get user
2468
- tags:
2469
- - Users
2470
- put:
2471
- consumes:
2472
- - application/json
2473
- description: 'Updates a user''s profile fields (first name, last name, email).
2474
- All fields are optional. Requires permission: `users:write`'
2475
- parameters:
2476
- - description: User ID
2477
- in: path
2478
- name: id
2479
- required: true
2480
- type: integer
2481
- - description: Fields to update (all optional)
2482
- in: body
2483
- name: body
2484
- required: true
2485
- schema:
2486
- $ref: '#/definitions/models.UpdateUserRequest'
2487
- produces:
2488
- - application/json
2489
- responses:
2490
- "200":
2491
- description: OK
2492
- schema:
2493
- $ref: '#/definitions/models.User'
2494
- "400":
2495
- description: Invalid user ID or request body
2496
- schema:
2497
- $ref: '#/definitions/models.ErrorResponse'
2498
- "401":
2499
- description: Unauthenticated
2500
- schema:
2501
- $ref: '#/definitions/models.ErrorResponse'
2502
- "403":
2503
- description: 'Missing permission: users:write'
2504
- schema:
2505
- $ref: '#/definitions/models.ErrorResponse'
2506
- "500":
2507
- description: Internal Server Error
2508
- schema:
2509
- $ref: '#/definitions/models.ErrorResponse'
2510
- security:
2511
- - Bearer: []
2512
- summary: Update user
2513
- tags:
2514
- - Users
2515
- /users/{id}/locations:
2516
- post:
2517
- consumes:
2518
- - application/json
2519
- description: 'Assigns an existing location to a user. Requires permission: `users:locations:manage`'
2520
- parameters:
2521
- - description: User ID
2522
- in: path
2523
- name: id
2524
- required: true
2525
- type: integer
2526
- - description: Location to assign
2527
- in: body
2528
- name: body
2529
- required: true
2530
- schema:
2531
- $ref: '#/definitions/models.AssignLocationRequest'
2532
- produces:
2533
- - application/json
2534
- responses:
2535
- "200":
2536
- description: OK
2537
- schema:
2538
- $ref: '#/definitions/models.MessageResponse'
2539
- "400":
2540
- description: Invalid user ID or request body
2541
- schema:
2542
- $ref: '#/definitions/models.ErrorResponse'
2543
- "401":
2544
- description: Unauthenticated
2545
- schema:
2546
- $ref: '#/definitions/models.ErrorResponse'
2547
- "403":
2548
- description: 'Missing permission: users:locations:manage'
2549
- schema:
2550
- $ref: '#/definitions/models.ErrorResponse'
2551
- "500":
2552
- description: Internal Server Error
2553
- schema:
2554
- $ref: '#/definitions/models.ErrorResponse'
2555
- security:
2556
- - Bearer: []
2557
- summary: Assign location to user
2558
- tags:
2559
- - Users
2560
- /users/{id}/locations/{locationId}:
2561
- delete:
2562
- description: 'Removes a location from a user. Requires permission: `users:locations:manage`'
2563
- parameters:
2564
- - description: User ID
2565
- in: path
2566
- name: id
2567
- required: true
2568
- type: integer
2569
- - description: Location ID
2570
- in: path
2571
- name: locationId
2572
- required: true
2573
- type: integer
2574
- produces:
2575
- - application/json
2576
- responses:
2577
- "200":
2578
- description: OK
2579
- schema:
2580
- $ref: '#/definitions/models.MessageResponse'
2581
- "400":
2582
- description: Invalid user ID or location ID
2583
- schema:
2584
- $ref: '#/definitions/models.ErrorResponse'
2585
- "401":
2586
- description: Unauthenticated
2587
- schema:
2588
- $ref: '#/definitions/models.ErrorResponse'
2589
- "403":
2590
- description: 'Missing permission: users:locations:manage'
2591
- schema:
2592
- $ref: '#/definitions/models.ErrorResponse'
2593
- "500":
2594
- description: Internal Server Error
2595
- schema:
2596
- $ref: '#/definitions/models.ErrorResponse'
2597
- security:
2598
- - Bearer: []
2599
- summary: Remove location from user
2600
- tags:
2601
- - Users
2602
- /users/{id}/password:
2603
- put:
2604
- consumes:
2605
- - application/json
2606
- description: 'Changes the authenticated user''s own password. The `{id}` in
2607
- the path must match the authenticated user''s ID. Requires permission: `users:password:self`'
2608
- parameters:
2609
- - description: User ID (must match authenticated user)
2610
- in: path
2611
- name: id
2612
- required: true
2613
- type: integer
2614
- - description: Current and new password
2615
- in: body
2616
- name: body
2617
- required: true
2618
- schema:
2619
- $ref: '#/definitions/models.ChangePasswordRequest'
2620
- produces:
2621
- - application/json
2622
- responses:
2623
- "200":
2624
- description: OK
2625
- schema:
2626
- $ref: '#/definitions/models.MessageResponse'
2627
- "400":
2628
- description: Invalid request or incorrect current password
2629
- schema:
2630
- $ref: '#/definitions/models.ErrorResponse'
2631
- "401":
2632
- description: Unauthenticated
2633
- schema:
2634
- $ref: '#/definitions/models.ErrorResponse'
2635
- "403":
2636
- description: 'Missing permission: users:password:self, or ID mismatch'
2637
- schema:
2638
- $ref: '#/definitions/models.ErrorResponse'
2639
- security:
2640
- - Bearer: []
2641
- summary: Change password
2642
- tags:
2643
- - Users
2644
- /users/{id}/resend-verification:
2645
- post:
2646
- description: 'Resends the activation email if the user hasn''t used the previous
2647
- link (expires in 48h). Fails if the account is already verified. Requires
2648
- permission: `users:create`'
2649
- parameters:
2650
- - description: User ID
2651
- in: path
2652
- name: id
2653
- required: true
2654
- type: integer
2655
- produces:
2656
- - application/json
2657
- responses:
2658
- "200":
2659
- description: Verification email sent
2660
- schema:
2661
- $ref: '#/definitions/models.MessageResponse'
2662
- "401":
2663
- description: Unauthenticated
2664
- schema:
2665
- $ref: '#/definitions/models.ErrorResponse'
2666
- "403":
2667
- description: 'Missing permission: users:create'
2668
- schema:
2669
- $ref: '#/definitions/models.ErrorResponse'
2670
- "404":
2671
- description: User not found
2672
- schema:
2673
- $ref: '#/definitions/models.ErrorResponse'
2674
- "409":
2675
- description: Account already verified
2676
- schema:
2677
- $ref: '#/definitions/models.ErrorResponse'
2678
- security:
2679
- - Bearer: []
2680
- summary: Resend verification email
2681
- tags:
2682
- - Users
2683
- /users/{id}/roles:
2684
- post:
2685
- consumes:
2686
- - application/json
2687
- description: 'Assigns an existing role to a user. Requires permission: `users:roles:manage`'
2688
- parameters:
2689
- - description: User ID
2690
- in: path
2691
- name: id
2692
- required: true
2693
- type: integer
2694
- - description: Role to assign
2695
- in: body
2696
- name: body
2697
- required: true
2698
- schema:
2699
- $ref: '#/definitions/models.AssignRoleRequest'
2700
- produces:
2701
- - application/json
2702
- responses:
2703
- "200":
2704
- description: OK
2705
- schema:
2706
- $ref: '#/definitions/models.MessageResponse'
2707
- "400":
2708
- description: Invalid user ID or request body
2709
- schema:
2710
- $ref: '#/definitions/models.ErrorResponse'
2711
- "401":
2712
- description: Unauthenticated
2713
- schema:
2714
- $ref: '#/definitions/models.ErrorResponse'
2715
- "403":
2716
- description: 'Missing permission: users:roles:manage'
2717
- schema:
2718
- $ref: '#/definitions/models.ErrorResponse'
2719
- "500":
2720
- description: Internal Server Error
2721
- schema:
2722
- $ref: '#/definitions/models.ErrorResponse'
2723
- security:
2724
- - Bearer: []
2725
- summary: Assign role to user
2726
- tags:
2727
- - Users
2728
- /users/{id}/roles/{roleId}:
2729
- delete:
2730
- description: 'Removes a role from a user. Requires permission: `users:roles:manage`'
2731
- parameters:
2732
- - description: User ID
2733
- in: path
2734
- name: id
2735
- required: true
2736
- type: integer
2737
- - description: Role ID
2738
- in: path
2739
- name: roleId
2740
- required: true
2741
- type: integer
2742
- produces:
2743
- - application/json
2744
- responses:
2745
- "200":
2746
- description: OK
2747
- schema:
2748
- $ref: '#/definitions/models.MessageResponse'
2749
- "400":
2750
- description: Invalid user ID or role ID
2751
- schema:
2752
- $ref: '#/definitions/models.ErrorResponse'
2753
- "401":
2754
- description: Unauthenticated
2755
- schema:
2756
- $ref: '#/definitions/models.ErrorResponse'
2757
- "403":
2758
- description: 'Missing permission: users:roles:manage'
2759
- schema:
2760
- $ref: '#/definitions/models.ErrorResponse'
2761
- "500":
2762
- description: Internal Server Error
2763
- schema:
2764
- $ref: '#/definitions/models.ErrorResponse'
2765
- security:
2766
- - Bearer: []
2767
- summary: Remove role from user
2768
- tags:
2769
- - Users
2770
- /users/{id}/specialities:
2771
- post:
2772
- consumes:
2773
- - application/json
2774
- description: 'Assigns an existing speciality to a user. Requires permission:
2775
- `users:specialities:manage`'
2776
- parameters:
2777
- - description: User ID
2778
- in: path
2779
- name: id
2780
- required: true
2781
- type: integer
2782
- - description: Speciality to assign
2783
- in: body
2784
- name: body
2785
- required: true
2786
- schema:
2787
- $ref: '#/definitions/models.AssignSpecialityRequest'
2788
- produces:
2789
- - application/json
2790
- responses:
2791
- "200":
2792
- description: OK
2793
- schema:
2794
- $ref: '#/definitions/models.MessageResponse'
2795
- "400":
2796
- description: Invalid user ID or request body
2797
- schema:
2798
- $ref: '#/definitions/models.ErrorResponse'
2799
- "401":
2800
- description: Unauthenticated
2801
- schema:
2802
- $ref: '#/definitions/models.ErrorResponse'
2803
- "403":
2804
- description: 'Missing permission: users:specialities:manage'
2805
- schema:
2806
- $ref: '#/definitions/models.ErrorResponse'
2807
- "500":
2808
- description: Internal Server Error
2809
- schema:
2810
- $ref: '#/definitions/models.ErrorResponse'
2811
- security:
2812
- - Bearer: []
2813
- summary: Assign speciality to user
2814
- tags:
2815
- - Users
2816
- /users/{id}/specialities/{specialityId}:
2817
- delete:
2818
- description: 'Removes a speciality from a user. Requires permission: `users:specialities:manage`'
2819
- parameters:
2820
- - description: User ID
2821
- in: path
2822
- name: id
2823
- required: true
2824
- type: integer
2825
- - description: Speciality ID
2826
- in: path
2827
- name: specialityId
2828
- required: true
2829
- type: integer
2830
- produces:
2831
- - application/json
2832
- responses:
2833
- "200":
2834
- description: OK
2835
- schema:
2836
- $ref: '#/definitions/models.MessageResponse'
2837
- "400":
2838
- description: Invalid user ID or speciality ID
2839
- schema:
2840
- $ref: '#/definitions/models.ErrorResponse'
2841
- "401":
2842
- description: Unauthenticated
2843
- schema:
2844
- $ref: '#/definitions/models.ErrorResponse'
2845
- "403":
2846
- description: 'Missing permission: users:specialities:manage'
2847
- schema:
2848
- $ref: '#/definitions/models.ErrorResponse'
2849
- "500":
2850
- description: Internal Server Error
2851
- schema:
2852
- $ref: '#/definitions/models.ErrorResponse'
2853
- security:
2854
- - Bearer: []
2855
- summary: Remove speciality from user
2856
- tags:
2857
- - Users
2858
- securityDefinitions:
2859
- Bearer:
2860
- description: 'JWT token de autenticación. Formato: "Bearer {token}"'
2861
- in: header
2862
- name: Authorization
2863
- type: apiKey
2864
- swagger: "2.0"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
documentation/M6_DISEÑO.md CHANGED
@@ -29,11 +29,11 @@ Funcionalidades, según el enunciado:
29
 
30
  | Capa | Tecnología | Justificación |
31
  |------|-----------|---------------|
32
- | Frontend | React (JS) | SPA con actualización en vivo del mapa de camas vía WebSocket. Ecosistema maduro para dashboards operativos. |
33
  | Backend | Python + FastAPI | Tipado con Pydantic que valida los contratos en runtime, generación automática del OpenAPI que ya estamos usando como contrato, y soporte nativo de async para las llamadas salientes concurrentes. |
34
  | Cliente HTTP saliente | httpx | Cliente async, necesario para no bloquear el event loop al llamar a M1, M2, M7, M9 y M10. |
35
- | Persistencia | PostgreSQL | Datos relacionales con integridad transaccional. La asignación de cama y el cambio de estado deben ser atómicos para evitar doble ocupación. |
36
- | Tiempo real | WebSocket | El mapa de camas necesita push: cuando una cama cambia de estado, todos los tableros abiertos lo ven sin polling. |
37
 
38
  ### Por qué REST sincrónico + webhooks, y no solo uno
39
 
@@ -50,32 +50,35 @@ Esta separación es la decisión arquitectónica central del módulo y hay que p
50
 
51
  ```
52
  ┌─────────────────────────────────────────────────────────────┐
53
- │ FRONTEND — React │
54
- │ Mapa de camas · Ingresos · Solicitudes · Quirófanos │
55
  └───────────────┬─────────────────────────▲────────────────────┘
56
- REST API │ │ WebSocket (mapa)
57
- ┌───────────────▼─────────────────────────┴────────────────────┐
58
- │ BACKEND — FastAPI │
59
- │ Routers: Camas (CRUD + WS) · Quirófanos · Solicitudes · │
60
- │ Webhooks (entrantes M1/M9) │
61
- │ Capa de servicios: lógica de negocio · validaciones · │
62
- │ contraindicaciones · desplazamiento de reservas · │
63
- │ máquina de estados de cama · alta médica │
64
- │ Clientes HTTP (httpx): llamadas salientes a M1·M2·M7·M9·M10 │
65
- └───────────────┬───────────────────────────────────┬──────────┘
 
66
  PostgreSQL│ REST saliente│ + webhooks
67
  ┌───────────────▼──────────┐ ┌─────────────────────▼──────────┐
68
- │ PERSISTENCIA — Postgres │ │ MÓDULOS EXTERNOS │
69
- │ Camas · Quirófanos · │ │ M10 Core (call) │
70
- │ Reservas · Solicitudes ·│ │ M1 HCE (call + recv) │
71
- │ Episodios · Eventos │ │ M2 Turnos (call) │
72
- └──────────────────────────┘ │ M7 Facturación (call) │
73
- │ M9 Monitoreo (call + recv) │
74
  └─────────────────────────────────┘
75
  ```
76
 
77
  **Regla de capas:** los routers solo orquestan (parsean request, llaman al servicio, arman response). Toda la lógica de negocio, las validaciones y las máquinas de estado viven en la capa de servicios. Las llamadas salientes pasan siempre por los clientes HTTP, nunca directo desde un router. Esto mantiene la lógica testeable sin levantar la red y permite mockear los módulos externos en la 2da entrega cambiando solo la capa de clientes.
78
 
 
 
79
  ---
80
 
81
  ## 4. Modelo de dominio
@@ -87,7 +90,7 @@ Esta separación es la decisión arquitectónica central del módulo y hay que p
87
  - **Solicitud:** pedido de internación o traslado originado en HCE (M1). Identificada por `id` string (`SOL-00123`) y vinculada al id de origen `solicitud_hce_id`. Vive en estado `PENDIENTE` hasta que un administrativo la resuelve.
88
  - **Reserva de quirófano:** ocupación de un quirófano en una ventana horaria, programada o de emergencia. Una urgente puede desplazar a una programada (`desplazada_por_reserva_id`).
89
  - **Episodio de internación:** abstracción de negocio que empieza cuando se aprueba una solicitud de internación (se asigna la primera cama) y termina cuando M1 notifica el alta médica. Atraviesa una o más camas (traslados). Es lo que se reporta a Facturación al cierre.
90
- - **Evento:** registro de auditoría de cada cambio relevante (entrante o saliente), para trazabilidad y para el Bus de Eventos de Core.
91
 
92
  ### 4.2 Enumeraciones (catálogos cerrados)
93
 
@@ -167,7 +170,7 @@ Mientras la solicitud está `PENDIENTE`, los campos de resolución (`accion`, `m
167
  - `POST /hce/solicitudes/{solicitudHceId}/resultado` (sincrónico) y webhook `SOLICITUD_RESUELTA` a M1.
168
  - `POST /hce/movimientos` (sincrónico) si hubo asignación.
169
  - webhook `ALTA_MONITOREO` a M9 si hubo asignación.
170
- 5. El cambio de estado de la cama se emite por WebSocket al mapa.
171
 
172
  Si `origen = CIRUGIA_PROGRAMADA`, antes de aprobar se valida el turno quirúrgico contra M2 (`GET /api/v1/appointments/{appointmentId}`).
173
 
@@ -200,7 +203,7 @@ Si `origen = CIRUGIA_PROGRAMADA`, antes de aprobar se valida el turno quirúrgic
200
  ### 5.7 Código rojo (Monitoreo)
201
 
202
  1. M9 detecta emergencia y hace `POST /webhooks/monitoreo/alerta-emergencia` (`paciente_id`).
203
- 2. M6 localiza la cama del paciente, la pone en `CODIGO_ROJO`, notifica a enfermería (WebSocket al mapa) y registra el evento en HCE (`POST /hce/episodios/{episodioId}/eventos`).
204
  3. Al estabilizarse, M9 hace `POST /webhooks/monitoreo/alerta-resuelta` y la cama vuelve a `OCUPADA`.
205
 
206
  ---
@@ -280,25 +283,44 @@ Lista de endpoints implementados por M6. Para la forma exacta de cada body, ver
280
  - `GET /solicitudes/{solicitudId}` — detalle.
281
  - `PATCH /solicitudes/{solicitudId}` — resolver (`APROBAR` / `APROBAR_CON_CAMBIO` / `RECHAZAR`).
282
 
 
 
 
283
  **Webhooks entrantes** — ver §7.1.
284
 
 
 
285
  ---
286
 
287
- ## 9. Tiempo real (WebSocket)
 
 
 
 
 
288
 
289
- El mapa de camas se suscribe a un canal WebSocket. Cada vez que una cama cambia de estado (asignación, traslado, alta, limpieza, código rojo), el backend publica el delta y todos los tableros conectados se actualizan sin polling. El canal es solo de salida hacia el frontend; las acciones siguen yendo por REST. El WebSocket no se documenta en OpenAPI (la spec 3.0 no lo soporta); su contrato de mensajes se mantiene en este documento.
290
 
291
- Formato de mensaje propuesto (a confirmar): `{ "tipo": "CAMA_ACTUALIZADA", "cama_id", "estado", "paciente_id", "timestamp" }`.
 
 
 
 
 
 
 
 
 
292
 
293
  ---
294
 
295
  ## 10. Persistencia
296
 
297
- Tablas principales en PostgreSQL: `camas` (incluye quirófanos), `reservas_quirofano`, `solicitudes`, `episodios`, `eventos`.
298
 
299
  - **`camas`** guarda también los quirófanos (`sector=QUIROFANO`, `tipo=CIRUGIA`). Es la decisión de modelo que explica que `QuirofanoResponse.estado` use `EstadoCamaEnum` y que `ReservaQuirofanoResponse` referencie la cama. Alternativa rechazada: tabla `quirofanos` separada, que duplicaría la máquina de estados de disponibilidad.
300
  - **`episodios`** referencia al paciente y mantiene la lista de camas atravesadas para el reporte a Facturación.
301
- - **`eventos`** es el log de auditoría (entrante/saliente) para trazabilidad y para el Bus de Eventos de Core.
302
  - La asignación de cama (validar `DISPONIBLE` → set `OCUPADA` + `paciente_id`) se hace en una transacción con bloqueo de fila para evitar doble ocupación.
303
 
304
  ---
@@ -365,3 +387,10 @@ Autenticación por JWT centralizada en Core (M10). Un middleware en FastAPI vali
365
  1. **`security` global vacío.** El spec declara el esquema `BearerAuth` pero deja `security` vacío a nivel raíz. Falta declarar **`security: [{ BearerAuth: [] }]`** para que la protección sea explícita en el contrato.
366
  2. **`WebhookCamaLista` campos obligatorios.** Más allá del enum de `evento`, conviene marcar `evento` y `paciente_id` como `required`, en línea con los otros webhooks salientes.
367
  3. **Renombrar `cama_id` en reservas de quirófano.** `ReservaQuirofanoResponse.cama_id` apunta al quirófano. Renombrar a `quirofano_id` cuando se coordine con el frontend (ver §13).
 
 
 
 
 
 
 
 
29
 
30
  | Capa | Tecnología | Justificación |
31
  |------|-----------|---------------|
32
+ | Frontend | React / Next.js | SPA con actualización en vivo del mapa de camas y la auditoría vía Supabase Realtime. Ecosistema maduro para dashboards operativos. |
33
  | Backend | Python + FastAPI | Tipado con Pydantic que valida los contratos en runtime, generación automática del OpenAPI que ya estamos usando como contrato, y soporte nativo de async para las llamadas salientes concurrentes. |
34
  | Cliente HTTP saliente | httpx | Cliente async, necesario para no bloquear el event loop al llamar a M1, M2, M7, M9 y M10. |
35
+ | Persistencia | PostgreSQL (Supabase) | Datos relacionales con integridad transaccional. La asignación de cama y el cambio de estado deben ser atómicos para evitar doble ocupación. |
36
+ | Tiempo real | Supabase Realtime | El mapa de camas y el historial de auditoría necesitan push: cuando una cama cambia de estado o se registra un evento, todos los tableros abiertos lo ven sin polling. Se eligió por sobre un hub WebSocket in-process porque el backend corre en un único proceso uvicorn en HF Spaces sin estado compartido entre workers — Supabase Realtime hace el fan-out de cambios en `camas`/`auditoria` directamente a los clientes suscriptos, sin código adicional en el backend (ver §9). |
37
 
38
  ### Por qué REST sincrónico + webhooks, y no solo uno
39
 
 
50
 
51
  ```
52
  ┌─────────────────────────────────────────────────────────────┐
53
+ │ FRONTEND — React/Next.js │
54
+ │ Mapa de camas · Ingresos · Solicitudes · Quirófanos · Auditoría│
55
  └───────────────┬─────────────────────────▲────────────────────┘
56
+ REST API │ Supabase Realtime (cliente directo,
57
+ │ tablas `camas` y `auditoria`)
58
+ ┌───────────────▼────────────────────────────────────────────────┐
59
+ │ BACKEND — FastAPI │
60
+ │ Routers: Camas (CRUD) · Quirófanos · Solicitudes · Auditoría │
61
+ │ (GET) · Webhooks (entrantes M1/M9) │
62
+ │ Capa de servicios: lógica de negocio · validaciones · │
63
+ │ contraindicaciones · desplazamiento de reservas · │
64
+ │ máquina de estados de cama · alta médica │
65
+ │ Clientes HTTP (httpx): llamadas salientes a M1·M2·M7·M9·M10 │
66
+ └───────────────┬───────────────────────────────────┬───────────┘
67
  PostgreSQL│ REST saliente│ + webhooks
68
  ┌───────────────▼──────────┐ ┌─────────────────────▼──────────┐
69
+ │ PERSISTENCIA — Supabase │ │ MÓDULOS EXTERNOS │
70
+ │ (Postgres + Realtime) │ │ M10 Core (call) │
71
+ │ Camas · Quirófanos · │ │ M1 HCE (call + recv) │
72
+ │ Reservas · Solicitudes ·│ │ M2 Turnos (call) │
73
+ │ Auditoría │ │ M7 Facturación (call) │
74
+ └──────────────────────────┘ │ M9 Monitoreo (call + recv) │
75
  └─────────────────────────────────┘
76
  ```
77
 
78
  **Regla de capas:** los routers solo orquestan (parsean request, llaman al servicio, arman response). Toda la lógica de negocio, las validaciones y las máquinas de estado viven en la capa de servicios. Las llamadas salientes pasan siempre por los clientes HTTP, nunca directo desde un router. Esto mantiene la lógica testeable sin levantar la red y permite mockear los módulos externos en la 2da entrega cambiando solo la capa de clientes.
79
 
80
+ **El backend no implementa push en tiempo real.** El frontend se conecta directo a Supabase Realtime (con el anon key, de solo lectura vía RLS) y escucha cambios en las tablas `camas` y `auditoria`. El backend solo escribe en Postgres; Supabase hace el fan-out a los clientes suscriptos. Esto saca toda la complejidad de pub/sub del backend (no hay hub in-process, no hay problema de multi-worker) a cambio de exponer el anon key de Supabase al frontend, lo cual es seguro porque las políticas RLS de esas tablas son de solo `SELECT`.
81
+
82
  ---
83
 
84
  ## 4. Modelo de dominio
 
90
  - **Solicitud:** pedido de internación o traslado originado en HCE (M1). Identificada por `id` string (`SOL-00123`) y vinculada al id de origen `solicitud_hce_id`. Vive en estado `PENDIENTE` hasta que un administrativo la resuelve.
91
  - **Reserva de quirófano:** ocupación de un quirófano en una ventana horaria, programada o de emergencia. Una urgente puede desplazar a una programada (`desplazada_por_reserva_id`).
92
  - **Episodio de internación:** abstracción de negocio que empieza cuando se aprueba una solicitud de internación (se asigna la primera cama) y termina cuando M1 notifica el alta médica. Atraviesa una o más camas (traslados). Es lo que se reporta a Facturación al cierre.
93
+ - **Evento de auditoría:** registro append-only de cada mutación relevante sobre `CAMA`, `SOLICITUD` o `RESERVA_QUIROFANO` (solicitudes, aprobaciones/rechazos, asignaciones, traslados, cambios de estado, bajas, alta médica, código rojo, reservas de quirófano). Vive en la tabla `auditoria`, con `cama_id` denormalizado para poder recuperar "todo lo que pasó con la cama X" sin importar qué entidad originó el evento. Detalle completo del modelo y los eventos en `docs/superpowers/specs/2026-06-26-auditoria-cama-design.md`.
94
 
95
  ### 4.2 Enumeraciones (catálogos cerrados)
96
 
 
170
  - `POST /hce/solicitudes/{solicitudHceId}/resultado` (sincrónico) y webhook `SOLICITUD_RESUELTA` a M1.
171
  - `POST /hce/movimientos` (sincrónico) si hubo asignación.
172
  - webhook `ALTA_MONITOREO` a M9 si hubo asignación.
173
+ 5. El cambio de estado de la cama queda persistido en `camas`; Supabase Realtime lo propaga al mapa sin intervención adicional del backend (§9).
174
 
175
  Si `origen = CIRUGIA_PROGRAMADA`, antes de aprobar se valida el turno quirúrgico contra M2 (`GET /api/v1/appointments/{appointmentId}`).
176
 
 
203
  ### 5.7 Código rojo (Monitoreo)
204
 
205
  1. M9 detecta emergencia y hace `POST /webhooks/monitoreo/alerta-emergencia` (`paciente_id`).
206
+ 2. M6 localiza la cama del paciente, la pone en `CODIGO_ROJO` (Supabase Realtime lo propaga al mapa automáticamente) y registra el evento en HCE (`POST /hce/episodios/{episodioId}/eventos`).
207
  3. Al estabilizarse, M9 hace `POST /webhooks/monitoreo/alerta-resuelta` y la cama vuelve a `OCUPADA`.
208
 
209
  ---
 
283
  - `GET /solicitudes/{solicitudId}` — detalle.
284
  - `PATCH /solicitudes/{solicitudId}` — resolver (`APROBAR` / `APROBAR_CON_CAMBIO` / `RECHAZAR`).
285
 
286
+ **Auditoría** (`Auditoría`)
287
+ - `GET /auditoria` — historial de eventos con filtros (`cama_id`, `entidad`, `entidad_id`, `paciente_id`, `evento`, `rol`, `usuario_id`, `hospital_id`, `fecha_desde`, `fecha_hasta`, `limit`, `offset`). Roles `ADMINISTRATIVO`, `MEDICO`. Snapshot REST; el tiempo real lo entrega Supabase Realtime directamente al frontend (§9).
288
+
289
  **Webhooks entrantes** — ver §7.1.
290
 
291
+ Matriz completa de qué rol puede hacer qué en cada endpoint: ver `documentation/roles.md`.
292
+
293
  ---
294
 
295
+ ## 9. Tiempo real (Supabase Realtime)
296
+
297
+ El mapa de camas y el historial de auditoría se actualizan en vivo sin polling agresivo. La implementación **no pasa por el backend de M6**: el frontend se conecta directo a Supabase Realtime con el cliente JS (`@supabase/supabase-js`) usando el anon key, y se suscribe a cambios `postgres_changes` sobre dos tablas:
298
+
299
+ - **`camas`** — eventos `INSERT`/`UPDATE`. El mapa de camas escucha la tabla completa; el detalle de una cama escucha filtrado por `id=eq.{camaId}`.
300
+ - **`auditoria`** — evento `INSERT`. La pantalla de detalle de cama escucha filtrado por `cama_id=eq.{camaId}` para mostrar el historial de esa cama en vivo.
301
 
302
+ **Por qué no un WebSocket propio:** se evaluó y se descartó un hub in-process (`AuditoriaHub`) que mantuviera en memoria las conexiones WS activas y hubiera publicado los deltas. Se descartó porque solo es válido para un único proceso uvicorn (que es el caso hoy, sin `--workers`), pero rompe en cuanto se escale a múltiples workers o procesos — cada uno solo vería sus propias conexiones. Supabase Realtime resuelve el fan-out a nivel de base de datos, sin ese problema, y sin código de pub/sub que mantener en el backend.
303
 
304
+ **Habilitación (una vez, en Supabase):**
305
+ ```sql
306
+ ALTER PUBLICATION supabase_realtime ADD TABLE camas;
307
+ ALTER PUBLICATION supabase_realtime ADD TABLE auditoria;
308
+ ```
309
+ Ambas tablas necesitan una policy RLS de `SELECT` abierta (`USING (true)`) para que el cliente con el anon key —que no tiene una sesión de Supabase Auth— pueda recibir los eventos. El backend sigue escribiendo con la `service_role` key, que bypassea RLS; el anon key del frontend es de solo lectura por diseño de Supabase, así que exponerlo en el cliente no abre una vía de escritura no autorizada.
310
+
311
+ **Patch quirúrgico, no refetch:** el frontend no hace un `GET` completo cada vez que llega un evento. El payload del evento Realtime (`payload.new`) ya trae la fila actualizada; el frontend la normaliza y actualiza solo esa entidad en el estado local (hooks `use-beds.ts` / `use-bed.ts` / `use-auditoria.ts` del frontend `TPO-DA2`). Esto evita perder scroll o producir un parpadeo de pantalla completa en cada actualización.
312
+
313
+ **Fallback:** `use-beds.ts` mantiene un polling de seguridad cada 5 minutos por si se cae la conexión Realtime del cliente.
314
 
315
  ---
316
 
317
  ## 10. Persistencia
318
 
319
+ Tablas principales en PostgreSQL (Supabase): `camas` (incluye quirófanos), `reservas_quirofano`, `solicitudes`, `episodios`, `auditoria`.
320
 
321
  - **`camas`** guarda también los quirófanos (`sector=QUIROFANO`, `tipo=CIRUGIA`). Es la decisión de modelo que explica que `QuirofanoResponse.estado` use `EstadoCamaEnum` y que `ReservaQuirofanoResponse` referencie la cama. Alternativa rechazada: tabla `quirofanos` separada, que duplicaría la máquina de estados de disponibilidad.
322
  - **`episodios`** referencia al paciente y mantiene la lista de camas atravesadas para el reporte a Facturación.
323
+ - **`auditoria`** es el log append-only de auditoría de `CAMA`/`SOLICITUD`/`RESERVA_QUIROFANO`, instrumentado explícitamente en la capa de servicios (no triggers, no middleware) para capturar el actor del JWT y el contexto de negocio completo. Registrar un evento es *best-effort*: nunca propaga una excepción que rompa la operación de negocio. Habilitada para Supabase Realtime (§9). Modelo completo, enums y puntos de instrumentación en `docs/superpowers/specs/2026-06-26-auditoria-cama-design.md`.
324
  - La asignación de cama (validar `DISPONIBLE` → set `OCUPADA` + `paciente_id`) se hace en una transacción con bloqueo de fila para evitar doble ocupación.
325
 
326
  ---
 
387
  1. **`security` global vacío.** El spec declara el esquema `BearerAuth` pero deja `security` vacío a nivel raíz. Falta declarar **`security: [{ BearerAuth: [] }]`** para que la protección sea explícita en el contrato.
388
  2. **`WebhookCamaLista` campos obligatorios.** Más allá del enum de `evento`, conviene marcar `evento` y `paciente_id` como `required`, en línea con los otros webhooks salientes.
389
  3. **Renombrar `cama_id` en reservas de quirófano.** `ReservaQuirofanoResponse.cama_id` apunta al quirófano. Renombrar a `quirofano_id` cuando se coordine con el frontend (ver §13).
390
+
391
+ ### 14.3 Auditoría y tiempo real (2026-06)
392
+
393
+ 15. **Tabla `auditoria` agregada.** Nuevo recurso `GET /auditoria` (roles `ADMINISTRATIVO`, `MEDICO`) con historial filtrable de eventos sobre `CAMA`/`SOLICITUD`/`RESERVA_QUIROFANO`. Instrumentado en la capa de servicios, best-effort (nunca rompe la operación de negocio). Detalle en `docs/superpowers/specs/2026-06-26-auditoria-cama-design.md`.
394
+ 16. **Reemplazo de WebSocket in-process por Supabase Realtime.** La primera versión de auditoría en tiempo real se implementó con un hub WebSocket in-process (`app/realtime.py`, endpoint `WS /auditoria/ws`). Se **eliminó** y se reemplazó por Supabase Realtime, consumido directo por el frontend sobre las tablas `camas` y `auditoria` (§9). Razón: el hub in-process solo funciona con un único proceso uvicorn; Supabase Realtime no tiene esa limitación y elimina código de pub/sub del backend. El backend ya no expone ningún endpoint WebSocket.
395
+ 17. **Rol LIMPIEZA: alcance de lectura ampliado, escritura más restringida.** Antes, `GET /camas` filtraba para LIMPIEZA solo las camas en `EN_LIMPIEZA`. Ahora LIMPIEZA ve **todas** las camas (igual que MEDICO/ADMINISTRATIVO), pero la única escritura permitida es la transición `EN_LIMPIEZA → DISPONIBLE` vía `PATCH /camas/{camaId}`, enforced en `cama_service.update_cama` (no solo en el frontend). Se cerró además un loophole donde LIMPIEZA podía modificar `contraindicaciones_incompatibles` enviándolo sin acompañar un cambio de `estado`.
396
+ 18. **Rol MEDICO: removido permiso de escritura indebido.** `POST /quirofanos/{quirofanoId}/reservas` (crear reserva de quirófano) aceptaba el rol `MEDICO`, pese a que MEDICO debe ser estrictamente de solo lectura sobre todo el dominio de M6. Corregido a solo `ADMINISTRATIVO`. Matriz completa de permisos por rol en `documentation/roles.md`.
documentation/roles.md ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Roles y permisos — Módulo 6
2
+
3
+ **Health Grid · Internación y Gestión de Camas**
4
+
5
+ > Fuente de verdad de qué puede hacer cada rol en M6. La forma exacta de cada endpoint está en `M6_openapi.json`; las reglas de negocio y máquinas de estado, en `M6_DISEÑO.md`. Este documento es la matriz de autorización.
6
+
7
+ ---
8
+
9
+ ## 1. Roles del sistema
10
+
11
+ M6 reconoce tres roles, transportados en el JWT (`payload["rol"]`) y validados en cada endpoint con `require_roles(...)` (`app/dependencies.py`):
12
+
13
+ | Rol | Perfil | Alcance general |
14
+ |---|---|---|
15
+ | `ADMINISTRATIVO` | Gestión operativa de camas, quirófanos y solicitudes | Acceso total — lectura y escritura sobre todo el dominio de M6 |
16
+ | `MEDICO` | Personal médico | Estrictamente de **solo lectura** sobre todo el dominio de M6, salvo crear reservas de quirófano (caso intencional, ver §3) |
17
+ | `LIMPIEZA` | Personal de limpieza/mantenimiento de camas | Lee todas las camas; la única escritura permitida es finalizar la limpieza de una cama propia (`EN_LIMPIEZA → DISPONIBLE`) |
18
+
19
+ No hay rol `SISTEMA` autenticado por JWT: los eventos disparados por webhooks entrantes (M1 HCE, M9 Monitoreo, M2 Turnos) no llevan actor humano y se registran en la auditoría con `rol = SISTEMA`, `origen = WEBHOOK` (ver `docs/superpowers/specs/2026-06-26-auditoria-cama-design.md`).
20
+
21
+ ---
22
+
23
+ ## 2. Principios de diseño
24
+
25
+ - **MEDICO es de solo lectura.** Ningún endpoint de escritura (`POST`/`PATCH`/`DELETE`) sobre camas, quirófanos o solicitudes acepta el rol MEDICO. La única excepción intencional es crear reservas de cirugía — ver §3.
26
+ - **ADMINISTRATIVO tiene control total.** Es el único rol que puede dar de alta/baja camas y quirófanos, asignar pacientes, resolver solicitudes y modificar reservas.
27
+ - **LIMPIEZA está acotado al mínimo necesario.** Ve el mapa completo de camas (para saber dónde está parado y planificar), pero solo puede ejecutar una transición de estado muy específica. La restricción se aplica **a nivel de servicio** (`app/services/cama_service.py`), no solo en el frontend — un request directo a la API con un JWT de LIMPIEZA que intente otra cosa es rechazado igual.
28
+ - **La autorización es por rol, no por permisos granulares.** `require_roles(*roles)` es un dependency de FastAPI que compara `payload["rol"]` contra una lista fija por endpoint. No hay un sistema de permisos (`camas:read`, `camas:write`, etc.) — eso es parte del plan de integración con el Core API de auth (M10), documentado en `documentation/M1_integration.md`, todavía no ejecutado.
29
+
30
+ ---
31
+
32
+ ## 3. Matriz de permisos por endpoint
33
+
34
+ `✓` permitido · `✗` prohibido (403) · `✓*` permitido con restricción adicional aplicada en la capa de servicio
35
+
36
+ ### Camas
37
+
38
+ | Endpoint | ADMINISTRATIVO | MEDICO | LIMPIEZA |
39
+ |---|:---:|:---:|:---:|
40
+ | `GET /camas` — mapa completo | ✓ | ✓ | ✓ |
41
+ | `POST /camas` — alta de cama | ✓ | ✗ | ✗ |
42
+ | `GET /camas/{camaId}` — detalle | ✓ | ✓ | ✓ |
43
+ | `PATCH /camas/{camaId}` — cambiar estado / contraindicaciones | ✓ | ✗ | ✓* |
44
+ | `DELETE /camas/{camaId}` — baja permanente | ✓ | ✗ | ✗ |
45
+ | `POST /camas/{camaId}/asignar` — asignar/trasladar paciente | ✓ | ✗ | ✗ |
46
+
47
+ **`✓*` en `PATCH /camas/{camaId}` para LIMPIEZA** — restricción aplicada en `cama_service.update_cama`:
48
+ - Solo puede cambiar `estado`, y únicamente la transición `EN_LIMPIEZA → DISPONIBLE`. Cualquier otra transición devuelve `403 NO_AUTORIZADO`.
49
+ - No puede tocar `contraindicaciones_incompatibles` bajo ningún escenario — incluso si no manda `estado` en el mismo request. Devuelve `403 NO_AUTORIZADO`.
50
+
51
+ > Antes de la reforma de roles (2026-06), `GET /camas` filtraba para LIMPIEZA solo las camas en `EN_LIMPIEZA`. Ahora ve el mapa completo; lo que cambió es exclusivamente el alcance de escritura.
52
+
53
+ ### Quirófanos
54
+
55
+ | Endpoint | ADMINISTRATIVO | MEDICO | LIMPIEZA |
56
+ |---|:---:|:---:|:---:|
57
+ | `GET /quirofanos/disponibilidad` | ✓ | ✓ | ✗ |
58
+ | `GET /quirofanos` — listado | ✓ | ✓ | ✗ |
59
+ | `POST /quirofanos` — alta | ✓ | ✗ | ✗ |
60
+ | `GET /quirofanos/{quirofanoId}` — detalle | ✓ | ✓ | ✗ |
61
+ | `PATCH /quirofanos/{quirofanoId}` — actualizar | ✓ | ✗ | ✗ |
62
+ | `GET /quirofanos/{quirofanoId}/reservas` — listar reservas | ✓ | ✓ | ✗ |
63
+ | `POST /quirofanos/{quirofanoId}/reservas` — crear reserva | ✓ | ✗ | ✗ |
64
+ | `GET /quirofanos/{quirofanoId}/reservas/{reservaId}` — detalle reserva | ✓ | ✓ | ✗ |
65
+ | `PATCH /quirofanos/{quirofanoId}/reservas/{reservaId}` — cambiar estado reserva | ✓ | ✗ | ✗ |
66
+
67
+ LIMPIEZA no tiene ningún acceso a quirófanos — no es parte de su responsabilidad operativa.
68
+
69
+ > **Corrección 2026-06:** `POST /quirofanos/{quirofanoId}/reservas` aceptaba MEDICO. Era la única escritura que tenía ese rol en todo M6, inconsistente con el principio de "MEDICO solo lectura". Se removió — ver changelog §14.3 de `M6_DISEÑO.md`.
70
+
71
+ ### Solicitudes
72
+
73
+ | Endpoint | ADMINISTRATIVO | MEDICO | LIMPIEZA |
74
+ |---|:---:|:---:|:---:|
75
+ | `GET /solicitudes` — listado | ✓ | ✓ | ✗ |
76
+ | `GET /solicitudes/{solicitudId}` — detalle | ✓ | ✓ | ✗ |
77
+ | `PATCH /solicitudes/{solicitudId}` — aprobar/rechazar | ✓ | ✗ | ✗ |
78
+
79
+ Solo ADMINISTRATIVO resuelve solicitudes de internación/traslado, incluso si fue un médico quien las originó desde HCE (M1) — la decisión de qué cama concreta se asigna es administrativa, no clínica (ver `M6_DISEÑO.md` §1).
80
+
81
+ ### Auditoría
82
+
83
+ | Endpoint | ADMINISTRATIVO | MEDICO | LIMPIEZA |
84
+ |---|:---:|:---:|:---:|
85
+ | `GET /auditoria` — historial de eventos | ✓ | ✓ | ✗ |
86
+
87
+ LIMPIEZA no tiene acceso al historial de auditoría — no necesita visibilidad sobre el log completo de movimientos clínicos/administrativos para hacer su trabajo.
88
+
89
+ ### Webhooks entrantes
90
+
91
+ Los endpoints bajo `/webhooks/*` (recepción de eventos de M1 HCE, M9 Monitoreo, M2 Turnos) **no usan `require_roles`** — no hay un usuario humano autenticado por JWT en esas llamadas. La autenticación de webhooks entrantes es un punto pendiente de definir con el Bus de Eventos de Core (ver `M6_DISEÑO.md` §13).
92
+
93
+ ---
94
+
95
+ ## 4. Implementación
96
+
97
+ - **`app/dependencies.py`** — `require_roles(*roles)` es el dependency de FastAPI que se usa en cada router. Lee `payload["rol"]` del JWT decodificado y devuelve `403 NO_AUTORIZADO` si no matchea.
98
+ - **Routers** (`app/routers/camas.py`, `quirofanos.py`, `solicitudes.py`, `auditoria.py`) — declaran los roles permitidos por endpoint con `Depends(require_roles(...))`. Esta es la primera línea de defensa; cubre la mayoría de los casos porque la mayoría de las restricciones son "todo o nada" por endpoint.
99
+ - **Capa de servicio** (`app/services/cama_service.py::update_cama`) — segunda línea de defensa para LIMPIEZA, porque su restricción no es "todo o nada" sobre el endpoint: `PATCH /camas/{camaId}` está permitido para LIMPIEZA, pero con una regla fina sobre *qué* puede cambiar y *bajo qué condición de estado previo*. Esa lógica no se puede expresar en el dependency de FastAPI — vive donde está el contexto de negocio completo (estado actual de la cama, qué campos vinieron en el body).
100
+
101
+ **Regla general para agregar una restricción nueva:** si es "este rol no puede llamar a este endpoint en absoluto", va en el router con `require_roles`. Si es "este rol puede llamar al endpoint pero con una condición sobre el contenido del request o el estado del recurso", va en el servicio — nunca confiar solo en que el frontend oculte el botón.
102
+
103
+ ---
104
+
105
+ ## 5. Testing
106
+
107
+ Los tests de autorización por rol viven junto a los tests de cada router (`tests/test_camas.py`, `tests/test_quirofanos.py`, `tests/test_solicitudes.py`, `tests/test_auditoria.py`), usando los fixtures `admin_headers`, `medico_headers`, `limpieza_headers` de `tests/conftest.py`. Cada endpoint restringido tiene al menos un test que verifica `403` para el/los rol(es) sin permiso, y un test de happy path para el rol permitido.
108
+
109
+ ---
110
+
111
+ ## 6. Fuera de alcance / pendiente
112
+
113
+ - **Permisos granulares vía Core API (M10).** El JWT del Core API real no transporta un campo `rol` sino un array `permissions[]`. Migrar `require_roles` a un modelo de permisos (o a un shim que derive el rol interno desde los permisos) es el trabajo descripto en `documentation/M1_integration.md`, todavía no ejecutado.
114
+ - **Autenticación de webhooks entrantes.** Hoy no hay verificación de origen en `/webhooks/*` más allá de lo que ya documente cada integración puntual. Pendiente acordar mecanismo (secreto compartido o firma) con el Bus de Eventos de Core.