Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Imjuanisss/proyecto-melika/llms.txt

Use this file to discover all available pages before exploring further.

Clinical records (historias_clinicas) are the structured medical histories MELIKA generates per appointment. Each record is tightly coupled to a single appointment (id_cita is UNIQUE), ensuring a one-to-one relationship between a consultation and its clinical narrative. Only authenticated physicians (isMedico) may create or add notes; patients may read their own histories and manage the visibility of their own uploaded documents. All endpoints require a valid JWT (verifyToken).

Data Model

The historias_clinicas table captures the complete clinical encounter — from chief complaint and anamnesis through vital signs, ICD-10 diagnosis, and the prescribing physician’s legal signature block. The table supports three record types via tipo_registro: a primary history (historia_principal) and two note types (nota_aclaracion, nota_evolucion). Notes link back to their originating record through id_historia_original.
FieldTypeNotes
idintegerPrimary key
id_pacienteintegerFK → patients
id_medicointegerFK → doctors
id_citaintegerFK → appointments — UNIQUE per historia_principal
tipo_registroVARCHARhistoria_principal, nota_aclaracion, or nota_evolucion
estadoVARCHARactivo or anulado_por_aclaracion
id_historia_originalintegerFK → parent history (set on notes only)
tipo_consultaVARCHARpresencial or teleconsulta. Default presencial
eps_aseguradoraVARCHARHealth insurer name
contacto_responsable_nombreVARCHARName of responsible contact
contacto_responsable_telefonoVARCHARPhone of responsible contact
motivo_consultaTEXTRequired. Chief complaint
anamnesisTEXTMedical history narrative
antecedentes_patologicosTEXTPathological history
antecedentes_quirurgicosTEXTSurgical history
antecedentes_alergicosTEXTAllergy history
antecedentes_familiaresTEXTFamily medical history
antecedentes_ginecoobstetricosTEXTGyneco-obstetric history
habitosTEXTLifestyle habits (smoking, alcohol, etc.)
tension_arterial_sistolicaFLOATSystolic blood pressure (mmHg)
tension_arterial_diastolicaFLOATDiastolic blood pressure (mmHg)
frecuencia_cardiacaintegerHeart rate (bpm)
frecuencia_respiratoriaintegerRespiratory rate (breaths/min)
temperatura_corporalFLOATBody temperature (°C)
peso_kgFLOATWeight in kilograms
talla_cmFLOATHeight in centimetres
imcFLOATBMI — auto-calculated from peso_kg / (talla_cm/100)²
exploracion_por_sistemasTEXTSystems review findings
examen_fisicoTEXTPhysical examination findings
diagnostico_cie10VARCHAR(10)ICD-10 diagnosis code (uppercased on save)
descripcion_diagnosticoTEXTHuman-readable diagnosis description
plan_tratamientoTEXTTreatment plan
medicamentos_recetadosJSONBFree-text prescription stored as { "texto": "..." }
ordenes_medicasTEXTMedical orders
recomendacionesTEXTPatient recommendations
incapacidad_diasintegerDays of medical leave granted
observacionesTEXTAdditional observations
medico_nombre_firmaVARCHARRequired. Signing physician’s full name
medico_cedula_firmaVARCHARSigning physician’s ID number
medico_rethus_firmaVARCHARRequired. Physician’s RETHUS registry number
created_attimestampAuto-generated
updated_attimestampAuto-updated

medicamentos_recetados Format

Prescribed medications entered in the free-text clinical notes field are normalised and stored as a JSONB object with a single texto key. The API returns the value already unwrapped to the plain string.
{ "texto": "Ibuprofeno 400 mg cada 8 h por 5 días; Omeprazol 20 mg en ayunas" }
Individual prescription line items with dosage details are tracked in the separate recetas_medicas table via the recetas array in the request body (see below).

Endpoints

GET /historias/paciente/:id_paciente

Retrieves a summary list of all primary clinical records (tipo_registro = historia_principal) belonging to a specific patient. Each record is enriched with the physician’s full name, specialty, appointment date, and a count of attached notes. Patients may only request their own records; physicians may access records for patients with whom they share at least one appointment. Authentication: verifyToken
id_paciente
integer
required
The unique identifier of the patient whose clinical records are being requested.
[].id
integer
Clinical record identifier.
[].motivo_consulta
string
Chief complaint recorded during the consultation.
[].diagnostico_cie10
string
ICD-10 code assigned by the physician.
[].descripcion_diagnostico
string
Human-readable diagnosis description.
[].tipo_registro
string
Always historia_principal for records returned by this endpoint.
[].estado
string
Record state: activo or anulado_por_aclaracion.
[].total_aclaraciones
integer
Count of attached clarification/evolution notes.
[].medico_nombre
string
First name of the physician who created the record.
[].medico_apellido
string
First surname of the physician.
[].especialidad
string
Medical specialty of the attending physician.
[].fecha
string
Appointment date (YYYY-MM-DD).
[].hora_inicio
string
Appointment start time.
curl -X GET http://localhost:3000/historias/paciente/42 \
  -H "Authorization: Bearer <token>"

GET /historias/cita/:id_cita

Returns the primary clinical record associated with a specific appointment, together with its attached clarification/evolution notes, prescription lines (recetas), and exam orders (examenes). If no record exists for the appointment yet, all arrays are returned empty. Authentication: verifyToken
id_cita
integer
required
The appointment ID for which to retrieve the clinical record.
historia
object
The primary clinical record object (all historias_clinicas columns) enriched with patient and physician demographics, specialty name, and appointment metadata (fecha_cita, hora_inicio, tipo_cita). Returns null if no record exists yet.
aclaraciones
array
Ordered list of nota_aclaracion and nota_evolucion records linked to this history.
recetas
array
Prescription line items from recetas_medicas for this history.
examenes
array
Exam orders from ordenes_examenes for this history.
curl -X GET http://localhost:3000/historias/cita/88 \
  -H "Authorization: Bearer <token>"

GET /historias/:id/completa

Retrieves a single primary clinical record by its own ID with full detail — including all columns expanded, any attached clarification/evolution notes, prescription lines, and exam orders. Authentication: verifyToken
id
integer
required
The clinical record’s own primary key.
historia
object
The complete primary clinical record with patient and physician demographics appended.
aclaraciones
array
Clarification and evolution notes attached to this history, ordered by creation date.
recetas
array
Prescription line items linked to this history.
examenes
array
Exam orders linked to this history.
curl -X GET http://localhost:3000/historias/15/completa \
  -H "Authorization: Bearer <token>"

POST /historias

Creates a new primary clinical record for an appointment. The record is permanently linked via id_cita. The controller runs full professional validation (vital-sign ranges, required clinical fields, patient-age coherence) before persisting. If recetas or examenes arrays are provided they are inserted transactionally in the same request. On success, the linked appointment’s estado is automatically updated to completada. Authentication: verifyToken + isMedico
id_cita
integer
required
The appointment this record belongs to. Must not already have an associated primary record.
motivo_consulta
string
required
Chief complaint — the patient’s primary reason for the consultation.
anamnesis
string
required
Medical history narrative gathered during the consultation.
antecedentes_alergicos
string
required
Allergy history.
examen_fisico
string
required
Findings from the physical examination.
diagnostico_cie10
string
required
ICD-10 diagnosis code (max 10 characters). Stored uppercased.
descripcion_diagnostico
string
required
Plain-language description of the diagnosis.
plan_tratamiento
string
required
Recommended treatment plan.
medico_nombre_firma
string
required
Full name of the signing physician as it should appear on the record.
medico_rethus_firma
string
required
Signing physician’s RETHUS registry number.
antecedentes_patologicos
string
Pathological history.
antecedentes_quirurgicos
string
Surgical history.
antecedentes_familiares
string
Family medical history.
antecedentes_ginecoobstetricos
string
Gyneco-obstetric history.
habitos
string
Lifestyle habits.
tipo_consulta
string
presencial (default) or teleconsulta.
eps_aseguradora
string
Health insurer name.
contacto_responsable_nombre
string
Responsible contact’s name.
contacto_responsable_telefono
string
Responsible contact’s phone.
tension_arterial_sistolica
number
Systolic blood pressure (mmHg).
tension_arterial_diastolica
number
Diastolic blood pressure (mmHg).
frecuencia_cardiaca
number
Heart rate (bpm).
frecuencia_respiratoria
number
Respiratory rate (breaths/min).
temperatura_corporal
number
Body temperature (°C).
peso_kg
number
Weight in kilograms. Used to auto-calculate imc.
talla_cm
number
Height in centimetres. Used to auto-calculate imc.
exploracion_por_sistemas
string
Systems review narrative.
medicamentos_recetados
string
Free-text prescription summary. Stored as { "texto": "..." } in the database.
ordenes_medicas
string
Medical orders text.
recomendaciones
string
Patient recommendations.
incapacidad_dias
integer
Days of medical leave granted.
observaciones
string
Additional observations.
medico_cedula_firma
string
Signing physician’s national ID number.
recetas
array
Array of prescription line items to insert into recetas_medicas. Each item: medicamento (required), dosis (required), frecuencia (required), duracion (required), via_administracion (optional), indicaciones (optional).
examenes
array
Array of exam orders to insert into ordenes_examenes. Each item: tipo_examen (required), nombre_examen (required), justificacion_clinica (optional).
mensaje
string
"Historia, recetas y exámenes guardados exitosamente."
historia
object
The newly created clinical record. medicamentos_recetados is returned as the unwrapped plain text string.
Each appointment can have exactly one primary clinical record. Submitting a second record for the same id_cita returns 409 Conflict. Use POST /historias/:id/aclaracion to add a clarification or evolution note.
curl -X POST http://localhost:3000/historias \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "id_cita": 88,
    "motivo_consulta": "Dolor abdominal recurrente",
    "anamnesis": "Paciente refiere episodios de dolor en FID desde hace 3 días.",
    "antecedentes_alergicos": "Ninguna conocida",
    "examen_fisico": "Abdomen blando, dolor a la palpación en FID, sin defensa muscular.",
    "diagnostico_cie10": "K37",
    "descripcion_diagnostico": "Apendicitis no especificada",
    "plan_tratamiento": "Referencia a cirugía general. Ayuno. Hidratación IV.",
    "medico_nombre_firma": "Dr. Juan Pérez",
    "medico_rethus_firma": "RETHUS-00421",
    "peso_kg": 70,
    "talla_cm": 175,
    "recetas": [
      {
        "medicamento": "Ketorolaco",
        "dosis": "30mg",
        "frecuencia": "cada 6 horas",
        "duracion": "2 días",
        "via_administracion": "IV"
      }
    ],
    "examenes": [
      {
        "tipo_examen": "Laboratorio",
        "nombre_examen": "Hemograma completo",
        "justificacion_clinica": "Descarte de leucocitosis"
      }
    ]
  }'

POST /historias/:id/aclaracion

Appends a clarification or evolution note (nota_aclaracion / nota_evolucion) to an existing primary clinical record. Both this route and PUT /historias/:id map to the same actualizarHistoria controller and accept the same request body. Only the original authoring physician may add notes. Authentication: verifyToken + isMedico
id
integer
required
The primary clinical record to annotate (tipo_registro = historia_principal).
tipo_registro
string
required
Note type: nota_aclaracion or nota_evolucion.
motivo_consulta
string
required
Reason for this note (e.g. summary of the clarification).
medico_nombre_firma
string
required
Signing physician’s full name.
medico_rethus_firma
string
required
Signing physician’s RETHUS number.
anamnesis
string
Updated or supplementary anamnesis.
examen_fisico
string
Updated physical examination findings.
diagnostico_cie10
string
Updated ICD-10 code.
descripcion_diagnostico
string
Updated diagnosis description.
plan_tratamiento
string
Updated treatment plan.
medicamentos_recetados
string
Updated free-text prescription summary.
peso_kg
number
Updated weight (kg).
talla_cm
number
Updated height (cm). imc is recalculated automatically.
observaciones
string
Additional observations.
medico_cedula_firma
string
Signing physician’s national ID.
recetas
array
New prescription line items to attach to this note.
examenes
array
New exam orders to attach to this note.
mensaje
string
"Nota de aclaración/evolución registrada exitosamente."
aclaracion
object
The newly created note record with medicamentos_recetados unwrapped to plain text.
curl -X POST http://localhost:3000/historias/15/aclaracion \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "tipo_registro": "nota_aclaracion",
    "motivo_consulta": "Aclaración: diagnóstico diferencial incluye colitis. Pendiente ultrasonido.",
    "medico_nombre_firma": "Dr. Juan Pérez",
    "medico_rethus_firma": "RETHUS-00421"
  }'

PUT /historias/:id

Alternative route for adding an evolution or clarification note. Accepts the identical request body as POST /historias/:id/aclaracion and routes to the same actualizarHistoria controller. Use whichever HTTP method is more natural for your client. Authentication: verifyToken + isMedico
id
integer
required
The primary clinical record to annotate.
The request body is identical to POST /historias/:id/aclaracion — see that section for the full field list.
mensaje
string
"Nota de aclaración/evolución registrada exitosamente."
aclaracion
object
The newly created note record.
curl -X PUT http://localhost:3000/historias/15 \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "tipo_registro": "nota_evolucion",
    "motivo_consulta": "Evolución satisfactoria. Se ajusta plan de tratamiento.",
    "plan_tratamiento": "Continuar manejo conservador. Control en 72 horas.",
    "medico_nombre_firma": "Dr. Juan Pérez",
    "medico_rethus_firma": "RETHUS-00421"
  }'

PATCH /historias/gestionar-cita/:id

Allows a physician to update the status of one of their appointments to completada or no_asistio, optionally recording medical notes. Authentication: verifyToken + isMedico
id
integer
required
The appointment ID to manage.
estado
string
required
New appointment status. Accepted values: completada, no_asistio.
notas_medicas
string
Optional clinical notes to record alongside the status update.
mensaje
string
"✅ Cita completada." or "📋 Paciente ausente."
curl -X PATCH http://localhost:3000/historias/gestionar-cita/88 \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"estado": "completada", "notas_medicas": "Paciente estable al cierre."}'

Document Endpoints

Clinical documents (lab results, imaging reports, referrals, external records) are stored separately from structured histories in the documentos_clinicos table and linked to patients by id_paciente. Patients may only upload documento_externo type; physicians may upload formula_medica, orden_examen, and historia_clinica types. Medical documents (origen = 'medico') are immutable — they can never be hidden or deleted.

GET /historias/documentos/paciente/:id_paciente

Lists all clinical documents on file for a patient. When the requesting user is a patient, documents where oculto_paciente = TRUE are automatically excluded from the response. Authentication: verifyToken
id_paciente
integer
required
The patient whose documents to retrieve.
[].id
integer
Document identifier.
[].id_historia
integer
Linked clinical history ID (nullable).
[].id_paciente
integer
Owning patient’s identifier.
[].id_medico
integer
Uploading physician’s ID (nullable for patient-uploaded documents).
[].tipo_documento
string
Document type: historia_clinica, formula_medica, orden_examen, or documento_externo.
[].origen
string
Who uploaded the document: medico or paciente.
[].nombre_archivo
string
Original filename (nullable).
[].url_pdf
string
URL to the stored document file.
[].descripcion
string
Human-readable document description.
[].oculto_paciente
boolean
Whether the patient has hidden this document from their view.
[].medico_nombre
string
First name of the uploading physician (joined from usuarios).
[].paciente_nombre
string
First name of the owning patient (joined from usuarios).
curl -X GET http://localhost:3000/historias/documentos/paciente/42 \
  -H "Authorization: Bearer <token>"

GET /historias/documentos/:id

Retrieves a single clinical document by its ID, with joined physician and patient name fields. Authentication: verifyToken
id
integer
required
The document’s unique identifier.
id
integer
Document identifier.
id_paciente
integer
Owning patient’s identifier.
tipo_documento
string
Document type.
origen
string
medico or paciente.
url_pdf
string
URL to the file.
descripcion
string
Document description.
oculto_paciente
boolean
Visibility flag.
curl -X GET http://localhost:3000/historias/documentos/7 \
  -H "Authorization: Bearer <token>"

POST /historias/documentos

Registers a new clinical document. Required fields depend on the caller’s role: patients may only register documento_externo for themselves; physicians may register formula_medica, orden_examen, or historia_clinica for patients under their care. Authentication: verifyToken
id_paciente
integer
required
The patient this document belongs to.
tipo_documento
string
required
Document type. Patient-allowed: documento_externo. Physician-allowed: formula_medica, orden_examen, historia_clinica.
url_pdf
string
required
Full URL pointing to the stored document file (e.g. a cloud storage URL).
id_historia
integer
ID of the linked clinical history (optional).
nombre_archivo
string
Original filename of the document.
descripcion
string
A brief human-readable description of the document contents.
mensaje
string
"Documento registrado."
documento
object
The newly created document object including its auto-generated id and all persisted fields.
curl -X POST http://localhost:3000/historias/documentos \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "id_paciente": 42,
    "tipo_documento": "documento_externo",
    "url_pdf": "https://storage.example.com/docs/hemo_42_nov24.pdf",
    "nombre_archivo": "hemograma_nov24.pdf",
    "descripcion": "Hemograma completo — Laboratorio Nacional"
  }'

PATCH /historias/documentos/:id/ocultar

Allows a patient to hide one of their own externally uploaded documents (origen = 'paciente'). Once hidden, the document remains in the database but is excluded from patient-facing document lists. Physician-uploaded documents (origen = 'medico') cannot be hidden. Authentication: verifyToken + isPaciente
id
integer
required
The ID of the document to hide. Must belong to the authenticated patient and have origen = 'paciente'.
mensaje
string
"Ocultado."
Hiding is a one-way patient action — it sets oculto_paciente = TRUE. There is no unhide route. Physicians and administrators may still access hidden documents through privileged views.
curl -X PATCH http://localhost:3000/historias/documentos/7/ocultar \
  -H "Authorization: Bearer <token>"

Build docs developers (and LLMs) love