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).
Each appointment includes:Appointment date (YYYY-MM-DD)
Status name (e.g., ‘Programada’, ‘Completada’)
Patient information (id, Nombre, Paterno, Materno)
Whether the appointment is urgent
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>
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[]>
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[]>
Start date in YYYY-MM-DD format
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[]>
Date in YYYY-MM-DD format
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>
Appointment data transfer objectAppointment date (YYYY-MM-DD)
Evolution time (numeric value)
dto.unidad_tiempo
'horas' | 'dias' | 'semanas' | 'meses'
Time unit for evolution
Associated symptoms array
Whether appointment is urgent
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>
Partial appointment data to update
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 }>
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 }>
Date in YYYY-MM-DD format
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[]>
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[]>
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[]>
Returns:
Array of history records with status changes, ordered by most recent first.
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