@phenyxhealth/sdk
v1.1.0
Published
SDK oficial para PhenyxHealth - Sistema integral de gestión de radioterapia. Incluye gestión de pacientes, recursos humanos, equipos médicos y configuración global.
Readme
PhenyxHealth SDK
SDK oficial para interactuar con las instancias de PhenyxHealth, un sistema integral de gestión de radioterapia.
Instalación
npm install @phenyxhealth/sdkInicio Rápido
import { PhenyxSDK } from "@phenyxhealth/sdk";
const api = new PhenyxSDK();
// Autenticación
await api.login({
apiHost: "https://your-phenyx-instance.com",
user: "your-username",
password: "your-password",
});
// Obtener pacientes
const patients = await api.getPatients();
console.log(patients);Características
- ✅ Autenticación y manejo de sesiones
- ✅ Gestión de pacientes y datos clínicos
- ✅ Control de recursos humanos (médicos, físicos)
- ✅ Gestión de equipos (LINACs)
- ✅ Configuración global del sistema
- ✅ Utilidades para fechas y colores
- ✅ Validaciones automáticas
- ✅ Soporte completo para TypeScript
API Reference
Autenticación
login(credentials)
Autentica con una instancia de PhenyxHealth y prepara el SDK para uso.
await api.login({
apiHost: "https://instance.phenyxheath.com",
user: "username",
password: "password",
});Parámetros:
apiHost(string): URL de la instancia de PhenyxHealthuser(string): Nombre de usuariopassword(string): Contraseña
Returns: Promise que resuelve cuando la autenticación es exitosa.
Gestión de Pacientes
getPatients()
Obtiene la lista de todos los pacientes.
const patients = await api.getPatients();Returns: Array de objetos de pacientes.
getPatient(id)
Obtiene los datos clínicos de un paciente específico.
const patient = await api.getPatient("patient-id");Parámetros:
id(string): ID del paciente
Returns: Objeto con datos clínicos del paciente.
createPatient(data)
Crea un nuevo paciente.
const patientId = await api.createPatient({
name: "Juan Pérez",
birthDate: "1980-01-15",
// ... otros campos
});Parámetros:
data(object): Datos del paciente a crear
Returns: ID del paciente creado.
deletePatient(id)
Elimina un paciente.
await api.deletePatient("patient-id");Recursos Humanos
getHumanResources()
Obtiene la lista de recursos humanos (médicos, físicos médicos).
const doctors = await api.getHumanResources();createHumanResource(data)
Crea un nuevo recurso humano.
await api.createHumanResource({
name: "Dr. García",
typeId: "radiation-oncologist-type-id",
agenda: [],
});Gestión de Equipos
getResources()
Obtiene todos los recursos (equipos) disponibles.
const resources = await api.getResources();createResource(data)
Crea un nuevo recurso.
await api.createResource({
name: "LINAC-01",
typeId: "linac-type-id",
});Configuración Global
getGlobalInfo(globalType)
Obtiene información global de un tipo específico.
const treatmentTypes = api.getGlobalInfo(api.globalTypes.treatmentType);updateGlobalInfo(globalTypeId, data)
Actualiza información global.
await api.updateGlobalInfo("global-type-id", updatedData);Estados y Flujo de Trabajo
createPatientStateChanges(params)
Crea cambios de estado para pacientes en el flujo de trabajo.
await api.createPatientStateChanges({
formDataId: "form-id",
date: "2024-02-14",
humanResourceId: "doctor-id",
nextStateCode: "COMPLETED",
});Tipos Globales Disponibles
El SDK incluye constantes para todos los tipos globales del sistema:
api.globalTypes = {
humanResources: { type: "Global", name: "Human Resources Types" },
sendingDepartment: { type: "Global", name: "Sending Department" },
treatmentType: { type: "Global", name: "Treatment Type" },
treatmentGoal: { type: "Global", name: "Treatment Goal" },
// ... muchos más
};Estados del Sistema
api.allStatus = {
NOTSTARTED: "NOT_STARTED",
COMPLETED: "COMPLETED",
INPROGRESS: "IN_PROGRESS",
// ... todos los estados disponibles
};Utilidades
Fechas
import { today, formatDate, formatDateString } from "@phenyxhealth/sdk";
const currentDate = today(); // '2024-02-14'
const formatted = formatDate(new Date()); // '2024-02-14'
const converted = formatDateString("14/02/2024"); // '2024-02-14'Colores
import { getContrastingColor } from "@phenyxhealth/sdk";
const color = getContrastingColor(); // '244, 67, 54' (formato RGB)Obtener IDs de Elementos Globales
// Obtener ID de departamento emisor
const deptId = api.getSendingDepartmentIdByName("Oncología");
// Obtener ID de código CEI9
const cei9Id = api.getCei9IdByName("C78.9");
// Obtener ID de código CIE10
const cie10Id = api.getCie10IdByName("C78.9");Funciones de Validación
Validar Médicos
import { beSureDoctorExists } from "@phenyxhealth/sdk";
await beSureDoctorExists(api, [
{ name: "Dr. García", hrGroup: "RadOnc" },
{ name: "Dr. Pérez", hrGroup: "MedPhys" },
]);Validar LINACs
import { beSureLinacsExists } from "@phenyxhealth/sdk";
await beSureLinacsExists(api, ["LINAC-01", "LINAC-02"]);Validar Configuración Global
import { checkGlobals, beSureGlobalExists } from "@phenyxhealth/sdk";
await checkGlobals(api, api.globalTypes.treatmentType, ["IMRT", "VMAT"]);Configuración y Debug
Habilitar Logs
api.showLogs(true); // Muestra todas las llamadas HTTP en la consolaObtener Token
const token = api.getToken(); // Obtiene el token JWT actualEjemplos Completos
Ejemplo 1: Setup Básico de Clínica
import {
PhenyxSDK,
beSureDoctorExists,
beSureLinacsExists,
checkGlobals,
} from "@phenyxhealth/sdk";
const setupClinic = async () => {
const api = new PhenyxSDK();
// Autenticación
await api.login({
apiHost: "https://clinic.phenyxhealth.com",
user: "admin",
password: "password",
});
// Configurar médicos
await beSureDoctorExists(api, [
{ name: "Dr. García", hrGroup: "RadOnc" },
{ name: "Dr. Martínez", hrGroup: "MedPhys" },
]);
// Configurar LINACs
await beSureLinacsExists(api, ["LINAC-01", "LINAC-02"]);
// Configurar tipos de tratamiento
await checkGlobals(api, api.globalTypes.treatmentType, [
"IMRT",
"VMAT",
"SRS",
]);
console.log("Clínica configurada correctamente");
};
setupClinic();Ejemplo 2: Crear y Procesar Paciente
import { PhenyxSDK, today } from "@phenyxhealth/sdk";
const processPatient = async () => {
const api = new PhenyxSDK();
await api.login({
/* credentials */
});
// Crear paciente
const patientId = await api.createPatient({
name: "Juan Pérez",
birthDate: "1980-01-15",
sendingDepartmentId: api.getSendingDepartmentIdByName("Oncología"),
cei9Id: api.getCei9IdByName("C78.9"),
cie10Id: api.getCie10IdByName("C78.9"),
});
// Cambiar estado del paciente
await api.createPatientStateChanges({
formDataId: patientId,
date: today(),
humanResourceId: api.getDoctorIdByName("Dr. García"),
nextStateCode: "IN_PROGRESS",
});
console.log(`Paciente ${patientId} procesado`);
};Manejo de Errores
El SDK lanza errores descriptivos que puedes capturar:
try {
await api.login({ apiHost: "invalid-host" });
} catch (error) {
console.error("Error de autenticación:", error.message);
}
try {
const department = api.getSendingDepartmentIdByName("No Existe");
} catch (error) {
console.error("Departamento no encontrado:", error.message);
}
try {
const cei9Id = api.getCei9IdByName("C00.0");
const cie10Id = api.getCie10IdByName("C00.0");
} catch (error) {
console.error("Código CEI no encontrado:", error.message);
}TypeScript Support
El SDK incluye definiciones TypeScript completas:
import { PhenyxSDK, PatientData, HumanResourceData } from "@phenyxhealth/sdk";
const api: PhenyxSDK = new PhenyxSDK();
const patient: PatientData = await api.getPatient("id");
const doctors: HumanResourceData[] = await api.getHumanResources();Uso con Claude Code
Si usas Claude Code para desarrollar, este SDK incluye un archivo de referencia completa de la API que puedes cargar automaticamente en tu proyecto.
Agrega la siguiente linea en el CLAUDE.md de tu proyecto:
@node_modules/@phenyxhealth/sdk/.claude/phenyx-sdk.mdEsto le dara a Claude Code el contexto completo de la API del SDK: todos los metodos, interfaces TypeScript, constantes, patrones de uso y notas importantes para que te asista correctamente al escribir codigo con @phenyxhealth/sdk.
Contribución
Las contribuciones son bienvenidas. Please:
- Fork el repositorio
- Crea una rama feature (
git checkout -b feature/nueva-caracteristica) - Commit tus cambios (
git commit -am 'Añadir nueva característica') - Push a la rama (
git push origin feature/nueva-caracteristica) - Crea un Pull Request
Licencia
ISC
Soporte
Para soporte y documentación adicional, contacta al equipo de PhenyxHealth.
Nota: Este SDK requiere una instancia válida de PhenyxHealth y credenciales apropiadas para funcionar.
