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.

MELIKA’s clinical records system (historias_clinicas) gives doctors a structured workspace to document every consultation — from chief complaint through diagnosis, vitals, and treatment plan. Records are tightly coupled to a completed appointment, can be supplemented with clarification or evolution notes at any time, and support external document attachments plus full PDF export. Strict role-based access ensures only the treating doctor can author a record, while the patient retains read-only visibility into their own health history.

What a Clinical Record Contains

Each historia_clinica is linked one-to-one with a managed appointment via id_cita. The table is broad and covers narrative, vitals, diagnosis, treatment, and administrative signature fields.

Core narrative fields

FieldTypeRequiredDescription
tipo_registrovarchar✅ Yes'historia_principal', 'nota_aclaracion', or 'nota_evolucion'
estadovarchar✅ YesRecord status — always 'activo' on creation
motivo_consultatext✅ YesChief complaint — the patient’s stated reason for the visit
anamnesistext✅ YesClinical history and symptom narrative taken from the patient
antecedentes_patologicostext✅ YesPathological background (chronic conditions, prior illnesses)
antecedentes_alergicostext✅ YesKnown allergies
examen_fisicotext✅ YesPhysical examination findings recorded by the doctor
diagnostico_cie10varchar✅ YesICD-10 / CIE-10 diagnostic code (e.g., I10 for hypertension)
descripcion_diagnosticotext✅ YesPlain-language description of the diagnosis
plan_tratamientotext✅ YesTreatment plan, follow-up instructions, referrals
antecedentes_quirurgicostextNoSurgical history
antecedentes_familiarestextNoRelevant family medical history
antecedentes_ginecoobstetricostextNoGynecological / obstetric history
habitostextNoLifestyle habits (smoking, alcohol, exercise)
exploracion_por_sistemastextNoSystems review findings
ordenes_medicastextNoSupplementary medical orders
recomendacionestextNoPatient recommendations and aftercare instructions
incapacidad_diasintegerNoMedical leave days granted
observacionestextNoAdditional clinical observations
eps_aseguradoravarcharNoPatient’s health insurer
contacto_responsable_nombrevarcharNoName of responsible contact
contacto_responsable_telefonovarcharNoPhone of responsible contact

Vitals fields

FieldTypeDescription
tension_arterial_sistolicanumericSystolic blood pressure (mmHg)
tension_arterial_diastolicanumericDiastolic blood pressure (mmHg)
frecuencia_cardiacanumericHeart rate (bpm)
frecuencia_respiratorianumericRespiratory rate (breaths/min)
temperatura_corporalnumericBody temperature (°C)
peso_kgnumericWeight in kilograms
talla_cmnumericHeight in centimeters
imcnumericBody Mass Index — calculated automatically from peso_kg and talla_cm

Prescription and signature fields

FieldTypeDescription
medicamentos_recetadosjsonbPrescribed medications stored as { "texto": "..." } — see Prescribed Medications below
medico_nombre_firmavarchar✅ Required — Doctor’s full name for the record signature
medico_cedula_firmavarcharDoctor’s ID number for the signature
medico_rethus_firmavarchar✅ Required — Doctor’s RETHUS professional registration number
id_historia_originalintegerFK to the parent historia_principal — set on clarification/evolution notes
The imc (BMI) is always computed server-side from peso_kg and talla_cm. Do not send it in the request body — it will be calculated and stored automatically.

Doctor Workflow

1

Complete the Appointment

Once a patient’s appointment reaches its scheduled time, the treating doctor navigates to the appointment and selects Gestionar, marking the cita as completada or no_asistio via PATCH /historias/gestionar-cita/:id.
2

Create the Clinical Record

The doctor fills in the historia_clinica fields. The mandatory fields listed above must all be present. The request also accepts optional recetas and examenes arrays, which are inserted into separate recetas_medicas and ordenes_examenes tables within the same database transaction.Creating a clinical record automatically sets the linked cita.estado to 'completada'.
POST /historias
Content-Type: application/json

{
  "id_cita": 42,
  "motivo_consulta": "Dolor de cabeza recurrente con náuseas",
  "anamnesis": "Paciente refiere episodios de cefalea 3 veces por semana durante el último mes",
  "antecedentes_patologicos": "Hipertensión arterial diagnosticada hace 5 años",
  "antecedentes_alergicos": "Alergia a penicilina",
  "examen_fisico": "TA 130/85 mmHg, FC 78 lpm. Sin déficit neurológico focal.",
  "diagnostico_cie10": "G43.9",
  "descripcion_diagnostico": "Migraña sin aura, sin mención de estado migrañoso",
  "plan_tratamiento": "Iniciar profilaxis con Amitriptilina 10mg/noche. Control en 4 semanas.",
  "medicamentos_recetados": "Amitriptilina 10mg, 1 tableta vía oral cada noche por 30 días",
  "medico_nombre_firma": "Dr. Carlos Vargas Mejía",
  "medico_rethus_firma": "RM-2019-04521",
  "peso_kg": 72,
  "talla_cm": 170,
  "recetas": [
    {
      "medicamento": "Amitriptilina",
      "dosis": "10mg",
      "frecuencia": "cada noche",
      "duracion": "30 días",
      "via_administracion": "oral"
    }
  ],
  "examenes": []
}
3

Add Clarification or Evolution Notes (Optional)

After saving the record, the doctor can append a clarification (nota_aclaracion) or evolution (nota_evolucion) note at any time. The note is a new row in historias_clinicas linked to the original via id_historia_original. Both routes reach the same controller.
POST /historias/:id/aclaracion
Content-Type: application/json

{
  "tipo_registro": "nota_aclaracion",
  "motivo_consulta": "Actualización tras resultados de MRI",
  "medico_nombre_firma": "Dr. Carlos Vargas Mejía",
  "medico_rethus_firma": "RM-2019-04521"
}
tipo_registro must be either "nota_aclaracion" or "nota_evolucion". All other clinical fields are optional on notes but follow the same shape as the main record.The same endpoint is also reachable via PUT /historias/:id for backward compatibility.

Prescribed Medications

The medicamentos_recetados column is a jsonb field that stores prescriptions as a plain text object: { "texto": "..." }. The value sent by the client may be a plain string or an object with a texto key — the server normalizes both forms before persisting.
{ "texto": "Amitriptilina 10mg, 1 tableta oral cada noche × 30 días. Ibuprofeno 400mg cada 8h SOS." }
When the record is returned to the frontend, the server deserializes this back to the plain string stored in texto for display and PDF rendering.
For structured per-medication rows with dosing fields, use the recetas array in the POST /historias request body instead. Each entry is stored in the separate recetas_medicas table with columns: medicamento, dosis, frecuencia, duracion, via_administracion, and indicaciones.

Retrieving Clinical Records

Returns the historia_principal for a given appointment, along with its linked aclaraciones (clarification/evolution notes), recetas, and examenes arrays.
GET /historias/cita/:id_cita
When no record has been created yet, returns { historia: null, aclaraciones: [], recetas: [], examenes: [] } (not a 404).

Clinical Documents

External clinical documents — such as laboratory results, imaging reports, or referral letters — can be registered and associated with a clinical record.
POST /historias/documentos
Content-Type: application/json

{
  "id_historia": 15,
  "id_paciente": 8,
  "tipo_documento": "formula_medica",
  "nombre_archivo": "formula_amitriptilina.pdf",
  "url_pdf": "https://storage.melika.app/docs/formula-42.pdf",
  "descripcion": "Fórmula médica post-consulta neurología"
}
Required fields: id_paciente, tipo_documento, url_pdf.Allowed tipo_documento values depend on the caller’s role:
RoleAllowed types
medicoformula_medica, orden_examen, historia_clinica
pacientedocumento_externo
Doctors may only register documents for patients with whom they have at least one shared appointment.

PDF Export and In-Browser Viewer

MELIKA provides full PDF generation and in-browser viewing of clinical records, entirely client-side.

PDF Generation

The PlantillaHistoriaPDF.jsx component uses @react-pdf/renderer to compile all clinical record fields — including the medication text, CIE-10 code, and clarification notes — into a downloadable PDF. Three templates are available: Historia Clínica, Fórmula Médica, and Orden de Exámenes.

In-Browser Viewer

The VisorPDFModal.jsx component renders the generated PDF directly in a modal overlay, allowing patients to review the document without leaving the application or downloading the file.
PDF generation happens entirely in the browser via @react-pdf/renderer — no server-side rendering pipeline is required. The resulting file can be downloaded directly from the viewer modal.

Access Control

Clinical records enforce strict role-based access. Authorization is checked at the controller level before any database write.
RolePermissions
medico (treating doctor)Create record, add clarification/evolution notes, register documents, manage appointment state
medico (other doctor)Read records only if they have at least one shared appointment with the patient
pacienteRead their own records and documents; hide patient-uploaded documents from their view
Only the treating doctor (the medico linked to the original cita) can create a clinical record for that appointment. Other doctors can view but cannot author records they did not originate.

Build docs developers (and LLMs) love