Skip to main content
The Appointment Service provides comprehensive methods to manage medical appointments, including creation, retrieval, updates, status transitions, and availability checks.

Methods

getAll

Retrieve all appointments with patient and status information.
appointments.getAll(): Promise<Appointment[]>
Returns: Array of appointments ordered by date and time (ascending).
appointments
array
Each appointment includes:
id
string
Appointment UUID
fecha_cita
string
Appointment date (YYYY-MM-DD)
hora_cita
string
Appointment time (HH:MM)
estado
number
Status ID
estado_nombre
string
Status name (e.g., ‘Programada’, ‘Completada’)
patients
object
Patient information (id, Nombre, Paterno, Materno)
motivo
string
Appointment reason
urgente
boolean
Whether the appointment is urgent
consultorio
number
Office/room number
Example:
import { api } from '../lib/api';

// From Calendar.tsx
const appointments = await api.appointments.getAll();
console.log(`Total appointments: ${appointments.length}`);
Cache: Results are cached for 20 minutes.

getById

Retrieve a single appointment by ID.
appointments.getById(id: string): Promise<Appointment | null>
id
string
required
The appointment’s unique identifier (UUID)
Example:
import { api } from '../lib/api';

// From CitasPage.tsx
const fetchedAppointment = await api.appointments.getById(appointmentId);
if (fetchedAppointment) {
  console.log(`Appointment: ${fetchedAppointment.motivo}`);
}

getByPatientId

Retrieve all appointments for a specific patient.
appointments.getByPatientId(patientId: string): Promise<Appointment[]>
patientId
string
required
The patient’s unique identifier (UUID)
Example:
import { api } from '../lib/api';

// From Layout.tsx
const patientAppointments = await api.appointments.getByPatientId(selectedPatient.id);
const upcoming = patientAppointments.filter(apt => apt.estado === 1);
Cache: Results are cached with key patient_${patientId}.

getByDateRange

Retrieve appointments within a date range.
appointments.getByDateRange(
  startDate: string,
  endDate: string
): Promise<Appointment[]>
startDate
string
required
Start date in YYYY-MM-DD format
endDate
string
required
End date in YYYY-MM-DD format
Example:
const appointments = await api.appointments.getByDateRange(
  '2024-01-01',
  '2024-01-31'
);
Returns: Appointments ordered by date descending, including full patient details.

getByDateAndConsultorio

Retrieve appointments for a specific date and office.
appointments.getByDateAndConsultorio(
  fecha: string,
  consultorio: number
): Promise<Appointment[]>
fecha
string
required
Date in YYYY-MM-DD format
consultorio
number
required
Office/room number
Example:
const dayAppointments = await api.appointments.getByDateAndConsultorio(
  '2024-03-15',
  1
);
Cache: Results are cached with key date_consultorio_${fecha}_${consultorio}.

createSecure

Create a new appointment using the secure RPC function.
appointments.createSecure(dto: AppointmentDTO): Promise<Appointment>
dto
object
required
Appointment data transfer object
dto.id_paciente
string
required
Patient UUID
dto.fecha_cita
string
required
Appointment date (YYYY-MM-DD)
dto.hora_cita
string
required
Appointment time (HH:MM)
dto.motivo
string
required
Reason for appointment
dto.consultorio
number
required
Office/room number
dto.duracion_minutos
number
required
Duration in minutes
dto.tipo_consulta
string
required
Consultation type
dto.tiempo_evolucion
number
Evolution time (numeric value)
dto.unidad_tiempo
'horas' | 'dias' | 'semanas' | 'meses'
Time unit for evolution
dto.sintomas_asociados
string[]
Associated symptoms array
dto.urgente
boolean
Whether appointment is urgent
dto.notas
string
Additional notes
Example:
import { api } from '../lib/api';

// From CitasPage.tsx
const createPayload = {
  id_paciente: selectedPatient.id,
  fecha_cita: '2024-03-20',
  hora_cita: '10:00',
  motivo: 'Consulta general',
  consultorio: 1,
  duracion_minutos: 30,
  tipo_consulta: 'Primera vez',
  urgente: false
};

const result = await api.appointments.createSecure(createPayload);
Note: This method uses the agendar_cita RPC function which automatically retrieves user_id and idbu from the authenticated session. Cache invalidation: Clears 'all', patient_${id_paciente}, and date_consultorio_${fecha}_${consultorio} caches.

update

Update an existing appointment.
appointments.update(
  id: string,
  dto: Partial<AppointmentDTO>,
  newStatusId?: number
): Promise<Appointment>
id
string
required
Appointment UUID
dto
object
required
Partial appointment data to update
newStatusId
number
Optional new status ID (triggers history record)
Example:
import { api } from '../lib/api';

// From CitasPage.tsx
const updatePayload = {
  hora_cita: '11:00',
  notas: 'Patient requested time change'
};

await api.appointments.update(
  editingAppointment.id,
  updatePayload,
  2 // New status: Confirmada
);
History tracking: If newStatusId is provided, a record is inserted into tcCitasHistorial tracking the status change.

changeStatus

Change appointment status and record in history.
appointments.changeStatus(
  appointmentId: string,
  newStatusId: number,
  notas?: string
): Promise<{ success: true }>
appointmentId
string
required
Appointment UUID
newStatusId
number
required
New status ID
notas
string
Optional notes about the status change
Example:
await api.appointments.changeStatus(
  appointmentId,
  4, // Completada
  'Patient attended successfully'
);

checkSlotAvailability

Check if a time slot is available for scheduling.
appointments.checkSlotAvailability(
  fecha: string,
  hora_inicio: string,
  duracion_minutos: number,
  consultorio: number
): Promise<{ available: boolean; reason: string }>
fecha
string
required
Date in YYYY-MM-DD format
hora_inicio
string
required
Start time (HH:MM)
duracion_minutos
number
required
Duration in minutes
consultorio
number
required
Office/room number
Example:
const slot = await api.appointments.checkSlotAvailability(
  '2024-03-20',
  '10:00',
  30,
  1
);

if (slot.available) {
  console.log('Slot is available!');
} else {
  console.log(`Not available: ${slot.reason}`);
}
RPC function: Uses the verificar_slot database function.

getAllowedStatusTransitions

Get allowed status transitions from current status.
appointments.getAllowedStatusTransitions(
  currentStatusId: number
): Promise<number[]>
currentStatusId
number
required
Current appointment status ID
Returns: Array of allowed destination status IDs. Example:
const allowedStatuses = await api.appointments.getAllowedStatusTransitions(1);
// Returns: [2, 6, 11] - Can transition to Confirmada, Cancelada, or Urgencia

getFilteredStatusOptions

Get filtered status options based on current status.
appointments.getFilteredStatusOptions(
  currentStatusId?: number
): Promise<Status[]>
currentStatusId
number
Current status ID (undefined for new appointments)
Returns: Array of status objects that are valid transitions. Example:
// For new appointment
const initialStatuses = await api.appointments.getFilteredStatusOptions();
// Returns: Programada (1) and Urgencia (11)

// For existing appointment
const nextStatuses = await api.appointments.getFilteredStatusOptions(1);
// Returns valid transitions from Programada

getAppointmentHistory

Retrieve change history for an appointment.
appointments.getAppointmentHistory(
  appointmentId: string
): Promise<HistoryRecord[]>
appointmentId
string
required
Appointment UUID
Returns: Array of history records with status changes, ordered by most recent first.
history
array
id
string
History record ID
estado_anterior
number
Previous status ID
estado_nuevo
number
New status ID
estado_anterior_nombre
string
Previous status name
estado_nuevo_nombre
string
New status name
usuario_nombre
string
User who made the change
created_at
string
When the change occurred
notas
string
Notes about the change
Cache: Results are cached for 5 minutes.

Status management

getEstados

Get all appointment statuses.
appointments.getEstados(): Promise<Status[]>
Returns: Array of all available appointment statuses.

getAllStatuses

Alias for getEstados - get all appointment statuses.
appointments.getAllStatuses(): Promise<Status[]>

Type definitions

interface Appointment {
  id: string;
  created_at: string;
  updated_at: string;
  id_paciente: string;
  id_user: string | null;
  fecha_cita: string;
  hora_cita: string;
  motivo: string;
  estado: number;
  estado_nombre: string;
  notas: string | null;
  urgente: boolean;
  consultorio: number;
  tipo_consulta: string;
  tiempo_evolucion: number | null;
  unidad_tiempo: 'horas' | 'dias' | 'semanas' | 'meses' | null;
  sintomas_asociados: string[] | null;
  hora_fin: string;
  duracion_minutos: number | null;
  idBu: string | null;
  patients?: {
    id: string;
    Nombre: string;
    Paterno: string;
    Materno: string;
  };
}

interface Status {
  id: number;
  estado: string;
  descripcion: string;
  usocita: string;
}

Source location

~/workspace/source/src/services/appointmentService.ts

Build docs developers (and LLMs) love