essalud-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +77 -0
- package/README.md +141 -0
- package/dist/essalud/api.d.ts +140 -0
- package/dist/essalud/api.js +136 -0
- package/dist/essalud/cmd-cancelar.d.ts +5 -0
- package/dist/essalud/cmd-cancelar.js +74 -0
- package/dist/essalud/cmd-citas.d.ts +1 -0
- package/dist/essalud/cmd-citas.js +47 -0
- package/dist/essalud/cmd-especialidades.d.ts +1 -0
- package/dist/essalud/cmd-especialidades.js +30 -0
- package/dist/essalud/cmd-fechas.d.ts +1 -0
- package/dist/essalud/cmd-fechas.js +47 -0
- package/dist/essalud/cmd-login.d.ts +7 -0
- package/dist/essalud/cmd-login.js +223 -0
- package/dist/essalud/cmd-perfil.d.ts +1 -0
- package/dist/essalud/cmd-perfil.js +38 -0
- package/dist/essalud/cmd-reservar.d.ts +14 -0
- package/dist/essalud/cmd-reservar.js +147 -0
- package/dist/essalud/cmd-token.d.ts +1 -0
- package/dist/essalud/cmd-token.js +62 -0
- package/dist/essalud/har.d.ts +7 -0
- package/dist/essalud/har.js +76 -0
- package/dist/essalud/index.d.ts +2 -0
- package/dist/essalud/index.js +87 -0
- package/dist/essalud/interactive.d.ts +5 -0
- package/dist/essalud/interactive.js +495 -0
- package/dist/essalud/jwt.d.ts +12 -0
- package/dist/essalud/jwt.js +29 -0
- package/dist/essalud-bin.d.ts +2 -0
- package/dist/essalud-bin.js +24 -0
- package/package.json +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Copyright (c) 2026 Shiara Arauzo
|
|
2
|
+
|
|
3
|
+
Required Notice: Copyright (c) 2026 Shiara Arauzo (https://github.com/shiarauzo/essalud-cli)
|
|
4
|
+
|
|
5
|
+
# PolyForm Noncommercial License 1.0.0
|
|
6
|
+
|
|
7
|
+
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
|
8
|
+
|
|
9
|
+
## Acceptance
|
|
10
|
+
|
|
11
|
+
In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
|
|
12
|
+
|
|
13
|
+
## Copyright License
|
|
14
|
+
|
|
15
|
+
The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
|
|
16
|
+
|
|
17
|
+
## Distribution License
|
|
18
|
+
|
|
19
|
+
The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
|
|
20
|
+
|
|
21
|
+
## Notices
|
|
22
|
+
|
|
23
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
|
|
24
|
+
|
|
25
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
26
|
+
|
|
27
|
+
## Changes and New Works License
|
|
28
|
+
|
|
29
|
+
The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
|
|
30
|
+
|
|
31
|
+
## Patent License
|
|
32
|
+
|
|
33
|
+
The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
|
|
34
|
+
|
|
35
|
+
## Noncommercial Purposes
|
|
36
|
+
|
|
37
|
+
Any noncommercial purpose is a permitted purpose.
|
|
38
|
+
|
|
39
|
+
## Personal Uses
|
|
40
|
+
|
|
41
|
+
Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
|
|
42
|
+
|
|
43
|
+
## Noncommercial Organizations
|
|
44
|
+
|
|
45
|
+
Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
|
|
46
|
+
|
|
47
|
+
## Fair Use
|
|
48
|
+
|
|
49
|
+
You may have "fair use" rights for the software under the law. These terms do not limit them.
|
|
50
|
+
|
|
51
|
+
## No Other Rights
|
|
52
|
+
|
|
53
|
+
These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
|
|
54
|
+
|
|
55
|
+
## Patent Defense
|
|
56
|
+
|
|
57
|
+
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
58
|
+
|
|
59
|
+
## Violations
|
|
60
|
+
|
|
61
|
+
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
|
|
62
|
+
|
|
63
|
+
## No Liability
|
|
64
|
+
|
|
65
|
+
***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
|
|
66
|
+
|
|
67
|
+
## Definitions
|
|
68
|
+
|
|
69
|
+
The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
|
|
70
|
+
|
|
71
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
72
|
+
|
|
73
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
74
|
+
|
|
75
|
+
**Your licenses** are all the licenses granted to you for the software under these terms.
|
|
76
|
+
|
|
77
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# essalud-cli
|
|
2
|
+
|
|
3
|
+
CLI **no oficial** para reservar y cancelar citas de EsSalud desde la terminal.
|
|
4
|
+
|
|
5
|
+
> ⚠️ **Disclaimer.** Proyecto independiente, **no afiliado a EsSalud**. Usa la API
|
|
6
|
+
> pública de su portal de citas mediante ingeniería inversa, así que puede dejar de
|
|
7
|
+
> funcionar si EsSalud cambia su backend. Usalo bajo tu responsabilidad.
|
|
8
|
+
> **Tu token y tus datos nunca salen de tu máquina** (se guardan localmente con permisos `600`).
|
|
9
|
+
|
|
10
|
+
## Requisitos
|
|
11
|
+
|
|
12
|
+
- Node >= 20
|
|
13
|
+
- Un navegador de Playwright (para el login asistido). Se instala una sola vez:
|
|
14
|
+
```bash
|
|
15
|
+
npx playwright install chromium
|
|
16
|
+
```
|
|
17
|
+
Si no lo instalas, el login asistido te avisa; igual puedes iniciar sesión con `--token` o `--from-har`.
|
|
18
|
+
|
|
19
|
+
## Instalación
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install -g essalud-cli
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Después, en cualquier carpeta:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
essalud # modo interactivo (menú navegable)
|
|
29
|
+
essalud login # inicia sesión: abre un navegador aislado y captura el token
|
|
30
|
+
essalud perfil # subcomando one-shot
|
|
31
|
+
essalud citas
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Login
|
|
35
|
+
|
|
36
|
+
`essalud login` **abre un navegador nuevo y aislado** (perfil limpio, no toca tu Chrome):
|
|
37
|
+
|
|
38
|
+
1. Ingresas tu DNI y clave en el navegador.
|
|
39
|
+
2. Completas el captcha de Cloudflare Turnstile.
|
|
40
|
+
3. Esperas a ver tu panel (lista de citas).
|
|
41
|
+
|
|
42
|
+
El CLI captura el token automáticamente desde la red, lo valida contra `/perfil` y lo
|
|
43
|
+
guarda. La sesión del navegador es efímera: se descarta al terminar.
|
|
44
|
+
|
|
45
|
+
¿No quieres/puedes usar el navegador asistido? Hay dos caminos manuales:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
# A) pegar el token a mano (Authorization: Bearer <jwt> desde DevTools → Network)
|
|
49
|
+
essalud login --token <jwt>
|
|
50
|
+
|
|
51
|
+
# B) importar desde un HAR exportado de DevTools
|
|
52
|
+
essalud login --from-har ~/Downloads/captura.har
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Modo interactivo
|
|
56
|
+
|
|
57
|
+
Correr `essalud` sin argumentos abre un menú navegable (tipo command palette):
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
┌ essalud · asistente de citas EsSalud
|
|
61
|
+
│
|
|
62
|
+
│ Estado: logueado · expira 21/6/2026, 1:53 a. m.
|
|
63
|
+
│
|
|
64
|
+
◆ ¿Que queres hacer?
|
|
65
|
+
│ ● Login
|
|
66
|
+
│ ○ Mi perfil
|
|
67
|
+
│ ○ Mis citas
|
|
68
|
+
│ ○ Reservar una cita
|
|
69
|
+
│ ○ Cancelar una cita
|
|
70
|
+
│ ○ Salir
|
|
71
|
+
│ ↑/↓ to navigate · Enter: confirm
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
El flujo "Reservar una cita" es guiado: especialidad → actividad → cupo disponible → resumen → confirmación explícita antes del POST real.
|
|
75
|
+
|
|
76
|
+
## Subcomandos one-shot
|
|
77
|
+
|
|
78
|
+
| Comando | Qué hace |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `essalud login` | Login asistido (abre navegador aislado + captura token) |
|
|
81
|
+
| `essalud login --token <jwt>` | Guardar token manualmente |
|
|
82
|
+
| `essalud login --from-har <path>` | Importar token desde HAR de DevTools |
|
|
83
|
+
| `essalud token` | Muestra si hay token y si está vigente |
|
|
84
|
+
| `essalud perfil` | Datos del asegurado (GET /perfil) |
|
|
85
|
+
| `essalud citas` | Citas emitidas (POST /citasEmitidas) |
|
|
86
|
+
| `essalud especialidades <codCentro>` | Lista especialidades del centro |
|
|
87
|
+
| `essalud fechas <codCentro> <codServicioHosp> <codActSubAct>` | Cupos disponibles |
|
|
88
|
+
| `essalud reservar` | Reservar cita (requiere `--confirm` para el POST real) |
|
|
89
|
+
| `essalud cancelar <citActMedNum>` | Cancelar cita (requiere `--confirm`) |
|
|
90
|
+
|
|
91
|
+
## Token
|
|
92
|
+
|
|
93
|
+
El token JWT se guarda en `~/.essalud/token` (chmod `600`).
|
|
94
|
+
Para obtenerlo: `essalud login`, o manualmente con `essalud login --token <jwt>`.
|
|
95
|
+
|
|
96
|
+
**El token nunca sale de tu máquina.**
|
|
97
|
+
|
|
98
|
+
## Desarrollo
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
# Sin build (tsx)
|
|
102
|
+
pnpm install
|
|
103
|
+
pnpm dev <subcomando>
|
|
104
|
+
|
|
105
|
+
# Con build
|
|
106
|
+
pnpm build
|
|
107
|
+
node dist/essalud-bin.js # modo interactivo directo
|
|
108
|
+
node dist/essalud-bin.js <subcomando> # subcomando one-shot
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Estructura
|
|
112
|
+
|
|
113
|
+
```
|
|
114
|
+
src/
|
|
115
|
+
essalud-bin.ts # entry point del comando global `essalud`
|
|
116
|
+
essalud/
|
|
117
|
+
api.ts # cliente HTTP + tipos de dominio
|
|
118
|
+
interactive.ts # modo interactivo (@clack/prompts)
|
|
119
|
+
cmd-token.ts # essalud token
|
|
120
|
+
cmd-perfil.ts # essalud perfil
|
|
121
|
+
cmd-citas.ts # essalud citas
|
|
122
|
+
cmd-login.ts # essalud login (navegador Playwright + --token + --from-har)
|
|
123
|
+
cmd-especialidades.ts # essalud especialidades
|
|
124
|
+
cmd-fechas.ts # essalud fechas
|
|
125
|
+
cmd-reservar.ts # essalud reservar
|
|
126
|
+
cmd-cancelar.ts # essalud cancelar
|
|
127
|
+
index.ts # router de subcomandos essalud
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Notas
|
|
131
|
+
|
|
132
|
+
- Base URL: `https://api.miconsulta.essalud.gob.pe/api`
|
|
133
|
+
- El captcha de Cloudflare (Turnstile) está solo en el login; las llamadas a la API no lo requieren.
|
|
134
|
+
- `essalud reservar` y el flujo interactivo de reserva siempre piden confirmación explícita antes de hacer el POST real a `/generarCita`.
|
|
135
|
+
|
|
136
|
+
## Licencia
|
|
137
|
+
|
|
138
|
+
[PolyForm Noncommercial 1.0.0](./LICENSE). El código está a la vista y puedes usarlo,
|
|
139
|
+
modificarlo y compartirlo **para fines no comerciales** (personal, educativo, ONG).
|
|
140
|
+
Cualquier **uso comercial** requiere permiso de la autora. No es una licencia OSI
|
|
141
|
+
"open source" en sentido estricto, sino *source-available* / no comercial.
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
export declare const BASE_URL = "https://api.miconsulta.essalud.gob.pe/api";
|
|
2
|
+
export declare const TOKEN_PATH: string;
|
|
3
|
+
export declare const PACIENTE_PATH: string;
|
|
4
|
+
export interface PacienteData {
|
|
5
|
+
codCentro: string;
|
|
6
|
+
desCentro: string;
|
|
7
|
+
apePaterno: string;
|
|
8
|
+
apeMaterno: string;
|
|
9
|
+
nombres: string | null;
|
|
10
|
+
email: string | null;
|
|
11
|
+
celular: string | null;
|
|
12
|
+
}
|
|
13
|
+
/** Lee ~/.essalud/paciente.json. Devuelve null si no existe. */
|
|
14
|
+
export declare function getPaciente(): Promise<PacienteData | null>;
|
|
15
|
+
/** Lee el token raw desde ~/.essalud/token */
|
|
16
|
+
export declare function readToken(): Promise<string>;
|
|
17
|
+
/** Envoltorio estándar de respuestas de EsSalud.
|
|
18
|
+
* codError "0" = OK; cualquier otro valor es error con mensaje en desError. */
|
|
19
|
+
export interface EsSaludResponse<T> {
|
|
20
|
+
codError: string;
|
|
21
|
+
desError: string;
|
|
22
|
+
vDataItem: T;
|
|
23
|
+
}
|
|
24
|
+
/** Hace una request autenticada.
|
|
25
|
+
* - Si la respuesta tiene envoltorio {codError, desError, vDataItem}: lo desenvuelve.
|
|
26
|
+
* codError "0" = OK; otro valor lanza error con desError.
|
|
27
|
+
* - Si la respuesta NO tiene envoltorio (p.ej. /perfil): devuelve el JSON directo. */
|
|
28
|
+
export declare function request<T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T>;
|
|
29
|
+
/** Error específico de la API de EsSalud — incluye codError para casos manejables. */
|
|
30
|
+
export declare class EsSaludApiError extends Error {
|
|
31
|
+
readonly codError: string;
|
|
32
|
+
readonly desError: string;
|
|
33
|
+
constructor(codError: string, desError: string);
|
|
34
|
+
}
|
|
35
|
+
export interface PerfilContacto {
|
|
36
|
+
idContacto?: number;
|
|
37
|
+
nroTelefonoFijo?: string | null;
|
|
38
|
+
nroCelular?: string | null;
|
|
39
|
+
email?: string | null;
|
|
40
|
+
[key: string]: unknown;
|
|
41
|
+
}
|
|
42
|
+
export interface Perfil {
|
|
43
|
+
idPersona?: number;
|
|
44
|
+
tipoDocIdent?: string;
|
|
45
|
+
numeroDocIdent?: string;
|
|
46
|
+
fechaNacimiento?: string;
|
|
47
|
+
indPadomi?: boolean;
|
|
48
|
+
indApplyPadomi?: boolean;
|
|
49
|
+
contacto?: PerfilContacto | null;
|
|
50
|
+
nombreAsegurado?: string;
|
|
51
|
+
apellidoPatAsegurado?: string;
|
|
52
|
+
apellidoMatAsegurado?: string;
|
|
53
|
+
[key: string]: unknown;
|
|
54
|
+
}
|
|
55
|
+
export interface CitaEmitida {
|
|
56
|
+
citActMedNum?: string;
|
|
57
|
+
citAutoGenCod?: string;
|
|
58
|
+
citEstCita?: string;
|
|
59
|
+
citFecha?: string;
|
|
60
|
+
citHora?: string;
|
|
61
|
+
citCenAsiDes?: string;
|
|
62
|
+
/** Código del centro de la cita; necesario para cancelarla (POST eliminarCita). */
|
|
63
|
+
citCenAsiCod?: string;
|
|
64
|
+
/** La API marca con `puedeCancelar` si la cita todavía se puede cancelar. */
|
|
65
|
+
puedeCancelar?: boolean;
|
|
66
|
+
/** true si la cita ya fue anulada. */
|
|
67
|
+
citaAnulada?: boolean;
|
|
68
|
+
[key: string]: unknown;
|
|
69
|
+
}
|
|
70
|
+
export interface ActSubAct {
|
|
71
|
+
codActSubAct: string;
|
|
72
|
+
desActHosp?: string;
|
|
73
|
+
desSubActHosp: string;
|
|
74
|
+
}
|
|
75
|
+
export interface ServicioHosp {
|
|
76
|
+
codServicioHosp: string;
|
|
77
|
+
desServicioHosp: string;
|
|
78
|
+
vdataActSubAct: ActSubAct[];
|
|
79
|
+
}
|
|
80
|
+
export interface DataParmSolicitud {
|
|
81
|
+
dataParmServicioHosp: ServicioHosp[];
|
|
82
|
+
[key: string]: unknown;
|
|
83
|
+
}
|
|
84
|
+
export interface CupoSlot {
|
|
85
|
+
hora: string;
|
|
86
|
+
nroCupo: number;
|
|
87
|
+
}
|
|
88
|
+
export interface Cupo {
|
|
89
|
+
apeNomProf: string;
|
|
90
|
+
codProgAsis: string;
|
|
91
|
+
codRel?: string;
|
|
92
|
+
consultorio: string;
|
|
93
|
+
fechaCitaProg: string;
|
|
94
|
+
turnoIni: string;
|
|
95
|
+
turnoFin: string;
|
|
96
|
+
/** Lista de slots individuales con hora y número de cupo */
|
|
97
|
+
vCupoDisp: CupoSlot[];
|
|
98
|
+
codActividad?: string;
|
|
99
|
+
codSubActividad?: string;
|
|
100
|
+
[key: string]: unknown;
|
|
101
|
+
}
|
|
102
|
+
export interface CitaCreada {
|
|
103
|
+
numCitaCreada?: string;
|
|
104
|
+
fechaCita?: string;
|
|
105
|
+
horaCita?: string;
|
|
106
|
+
apeNomProf?: string;
|
|
107
|
+
desServHosp?: string;
|
|
108
|
+
[key: string]: unknown;
|
|
109
|
+
}
|
|
110
|
+
/** GET /perfil — datos del asegurado */
|
|
111
|
+
export declare function getPerfil(): Promise<Perfil>;
|
|
112
|
+
/** POST /citasEmitidas — citas del usuario.
|
|
113
|
+
* Devuelve [] si la API responde "no se encontro cita" (codError "1"). */
|
|
114
|
+
export declare function getCitasEmitidas(): Promise<CitaEmitida[]>;
|
|
115
|
+
/** POST /parametroSolicitud — especialidades disponibles para un centro.
|
|
116
|
+
* codError "1" = sin datos (devuelve DataParmSolicitud vacío). */
|
|
117
|
+
export declare function getParametroSolicitud(codCentro: string): Promise<DataParmSolicitud>;
|
|
118
|
+
export interface ProgramacionPayload {
|
|
119
|
+
codCentro: string;
|
|
120
|
+
codServicioHosp: string;
|
|
121
|
+
codActSubAct: string;
|
|
122
|
+
codTurnoDeseado: string;
|
|
123
|
+
}
|
|
124
|
+
/** POST /programacionDisponible — cupos disponibles.
|
|
125
|
+
* codError "1" = sin programación disponible (no es error, devuelve []). */
|
|
126
|
+
export declare function getProgramacionDisponible(payload: ProgramacionPayload): Promise<Cupo[]>;
|
|
127
|
+
export interface GenerarCitaPayload {
|
|
128
|
+
codProgAsis: string;
|
|
129
|
+
consultorio: string;
|
|
130
|
+
fechaCitaPro: string;
|
|
131
|
+
/** Número de cupo individual (viene de vCupoDisp[].nroCupo) */
|
|
132
|
+
nroCupo: number;
|
|
133
|
+
turnoIni: string;
|
|
134
|
+
turnoFin: string;
|
|
135
|
+
numCelular: string;
|
|
136
|
+
email: string;
|
|
137
|
+
}
|
|
138
|
+
/** POST /generarCita — reserva una cita REAL.
|
|
139
|
+
* ADVERTENCIA: ocupa un cupo real. Solo llamar con confirmación explícita del usuario. */
|
|
140
|
+
export declare function generarCita(payload: GenerarCitaPayload): Promise<CitaCreada[]>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
export const BASE_URL = "https://api.miconsulta.essalud.gob.pe/api";
|
|
5
|
+
export const TOKEN_PATH = join(homedir(), ".essalud", "token");
|
|
6
|
+
export const PACIENTE_PATH = join(homedir(), ".essalud", "paciente.json");
|
|
7
|
+
/** Ubicación antigua del token (antes de renombrar el proyecto a essalud-cli).
|
|
8
|
+
* Solo se usa para dar un mensaje de diagnóstico; no se lee como token válido. */
|
|
9
|
+
const LEGACY_TOKEN_PATH = join(homedir(), ".tramites-pe", "essalud", "token");
|
|
10
|
+
/** Lee ~/.essalud/paciente.json. Devuelve null si no existe. */
|
|
11
|
+
export async function getPaciente() {
|
|
12
|
+
try {
|
|
13
|
+
const raw = await readFile(PACIENTE_PATH, "utf-8");
|
|
14
|
+
return JSON.parse(raw);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Lee el token raw desde ~/.essalud/token */
|
|
21
|
+
export async function readToken() {
|
|
22
|
+
try {
|
|
23
|
+
const raw = await readFile(TOKEN_PATH, "utf-8");
|
|
24
|
+
return raw.trim();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// Diagnóstico: si hay un token en la ubicación antigua, explica el cambio.
|
|
28
|
+
let migracion = "";
|
|
29
|
+
try {
|
|
30
|
+
await readFile(LEGACY_TOKEN_PATH, "utf-8");
|
|
31
|
+
migracion =
|
|
32
|
+
` Tu sesión estaba en una ubicación antigua (${LEGACY_TOKEN_PATH}) que ya no se usa;` +
|
|
33
|
+
` ahora el token vive en ${TOKEN_PATH}.`;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// No había token viejo: mensaje genérico.
|
|
37
|
+
}
|
|
38
|
+
throw new Error(`No hay sesión activa. Corre \`essalud login\` para iniciar sesión.${migracion}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Hace una request autenticada.
|
|
42
|
+
* - Si la respuesta tiene envoltorio {codError, desError, vDataItem}: lo desenvuelve.
|
|
43
|
+
* codError "0" = OK; otro valor lanza error con desError.
|
|
44
|
+
* - Si la respuesta NO tiene envoltorio (p.ej. /perfil): devuelve el JSON directo. */
|
|
45
|
+
export async function request(method, path, body) {
|
|
46
|
+
const token = await readToken();
|
|
47
|
+
const headers = {
|
|
48
|
+
Authorization: `Bearer ${token}`,
|
|
49
|
+
"Content-Type": "application/json",
|
|
50
|
+
Accept: "application/json",
|
|
51
|
+
};
|
|
52
|
+
const res = await fetch(`${BASE_URL}/${path}`, {
|
|
53
|
+
method,
|
|
54
|
+
headers,
|
|
55
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
56
|
+
});
|
|
57
|
+
if (!res.ok) {
|
|
58
|
+
throw new Error(`HTTP ${res.status} ${res.statusText} — ${method} /${path}`);
|
|
59
|
+
}
|
|
60
|
+
const json = (await res.json());
|
|
61
|
+
// Detectar envoltorio: el objeto tiene exactamente las claves del envoltorio
|
|
62
|
+
if ("codError" in json && "desError" in json && "vDataItem" in json) {
|
|
63
|
+
const wrapped = json;
|
|
64
|
+
if (wrapped.codError !== "0") {
|
|
65
|
+
throw new EsSaludApiError(wrapped.codError, wrapped.desError);
|
|
66
|
+
}
|
|
67
|
+
return wrapped.vDataItem;
|
|
68
|
+
}
|
|
69
|
+
// Sin envoltorio: devolver el JSON directo
|
|
70
|
+
return json;
|
|
71
|
+
}
|
|
72
|
+
/** Error específico de la API de EsSalud — incluye codError para casos manejables. */
|
|
73
|
+
export class EsSaludApiError extends Error {
|
|
74
|
+
codError;
|
|
75
|
+
desError;
|
|
76
|
+
constructor(codError, desError) {
|
|
77
|
+
super(`EsSalud [${codError}]: ${desError}`);
|
|
78
|
+
this.codError = codError;
|
|
79
|
+
this.desError = desError;
|
|
80
|
+
this.name = "EsSaludApiError";
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// Endpoints
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
/** GET /perfil — datos del asegurado */
|
|
87
|
+
export async function getPerfil() {
|
|
88
|
+
return request("GET", "perfil");
|
|
89
|
+
}
|
|
90
|
+
/** POST /citasEmitidas — citas del usuario.
|
|
91
|
+
* Devuelve [] si la API responde "no se encontro cita" (codError "1"). */
|
|
92
|
+
export async function getCitasEmitidas() {
|
|
93
|
+
try {
|
|
94
|
+
const result = await request("POST", "citasEmitidas", {});
|
|
95
|
+
return result ?? [];
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
if (err instanceof EsSaludApiError && err.codError === "1") {
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** POST /parametroSolicitud — especialidades disponibles para un centro.
|
|
105
|
+
* codError "1" = sin datos (devuelve DataParmSolicitud vacío). */
|
|
106
|
+
export async function getParametroSolicitud(codCentro) {
|
|
107
|
+
try {
|
|
108
|
+
const result = await request("POST", "parametroSolicitud", { codCentro });
|
|
109
|
+
return result ?? { dataParmServicioHosp: [] };
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
if (err instanceof EsSaludApiError && err.codError === "1") {
|
|
113
|
+
return { dataParmServicioHosp: [] };
|
|
114
|
+
}
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** POST /programacionDisponible — cupos disponibles.
|
|
119
|
+
* codError "1" = sin programación disponible (no es error, devuelve []). */
|
|
120
|
+
export async function getProgramacionDisponible(payload) {
|
|
121
|
+
try {
|
|
122
|
+
const result = await request("POST", "programacionDisponible", payload);
|
|
123
|
+
return Array.isArray(result) ? result : [];
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
if (err instanceof EsSaludApiError && err.codError === "1") {
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
throw err;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** POST /generarCita — reserva una cita REAL.
|
|
133
|
+
* ADVERTENCIA: ocupa un cupo real. Solo llamar con confirmación explícita del usuario. */
|
|
134
|
+
export async function generarCita(payload) {
|
|
135
|
+
return request("POST", "generarCita", payload);
|
|
136
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
import { EsSaludApiError, getCitasEmitidas, request } from "./api.js";
|
|
3
|
+
function confirmarInteractivo(mensaje) {
|
|
4
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
5
|
+
return new Promise((resolve) => {
|
|
6
|
+
rl.question(`${mensaje} [s/N] `, (answer) => {
|
|
7
|
+
rl.close();
|
|
8
|
+
resolve(answer.trim().toLowerCase() === "s");
|
|
9
|
+
});
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
// Busca la cita en citasEmitidas para obtener su codCentro (citCenAsiCod).
|
|
13
|
+
async function buscarCita(citActMedNum) {
|
|
14
|
+
try {
|
|
15
|
+
const citas = await getCitasEmitidas();
|
|
16
|
+
return citas.find((c) => c.citActMedNum === citActMedNum);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// sin citas o error de lectura -> caemos al fallback de --cod-centro
|
|
20
|
+
}
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
export async function cmdCancelar(citActMedNum, opts) {
|
|
24
|
+
console.log(`Cancelar cita: ${citActMedNum}`);
|
|
25
|
+
console.log("─".repeat(50));
|
|
26
|
+
const cita = await buscarCita(citActMedNum);
|
|
27
|
+
const codCentro = opts.codCentro ?? cita?.citCenAsiCod;
|
|
28
|
+
if (!codCentro) {
|
|
29
|
+
console.error("No encontré la cita ni su centro. Pasa el centro con --cod-centro <cod> (es el citCenAsiCod de la cita en `essalud citas`).");
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
// Si la encontramos y la API dice que no se puede cancelar (p. ej. ya anulada), paramos.
|
|
33
|
+
// Nota: acá bloqueamos solo el caso DEFINITIVO (`=== false`) porque el usuario nombró
|
|
34
|
+
// una cita explícita; el menú interactivo, en cambio, solo OFRECE las `=== true`
|
|
35
|
+
// (más conservador, para no listar candidatas dudosas en una operación irreversible).
|
|
36
|
+
if (cita && cita.puedeCancelar === false) {
|
|
37
|
+
const motivo = cita.citaAnulada ? "ya está anulada" : "no se puede cancelar";
|
|
38
|
+
console.error(`Esta cita ${motivo} (estado: ${cita.citEstCita ?? "?"}). No hay nada que cancelar.`);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
}
|
|
41
|
+
if (cita) {
|
|
42
|
+
console.log(`${cita.citEstCita ?? ""} ${cita.citFecha ?? ""} ${cita.citHora ?? ""} · ${cita.citCenAsiDes ?? codCentro}`.trim());
|
|
43
|
+
}
|
|
44
|
+
console.log(`Endpoint: POST /eliminarCita { oriCenAsis:"1", numCitaCreada:"${citActMedNum}", codCentro:"${codCentro}" }`);
|
|
45
|
+
console.log("");
|
|
46
|
+
if (!opts.confirm) {
|
|
47
|
+
console.log("[dry-run] No se canceló nada.");
|
|
48
|
+
console.log("Para cancelar de verdad: agrega --confirm al comando.");
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const ok = await confirmarInteractivo(`Esto CANCELA la cita ${citActMedNum} de verdad. ¿Confirmas?`);
|
|
52
|
+
if (!ok) {
|
|
53
|
+
console.log("Cancelado. No se realizó ninguna operación.");
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const result = await request("POST", "eliminarCita", {
|
|
58
|
+
oriCenAsis: "1",
|
|
59
|
+
numCitaCreada: citActMedNum,
|
|
60
|
+
codCentro,
|
|
61
|
+
});
|
|
62
|
+
console.log("\n✓ Cita cancelada.");
|
|
63
|
+
console.log(JSON.stringify(result, null, 2));
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
if (err instanceof EsSaludApiError) {
|
|
67
|
+
console.error(`Error de API [${err.codError}]: ${err.desError}`);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
console.error(String(err));
|
|
71
|
+
}
|
|
72
|
+
process.exit(1);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function cmdCitas(): Promise<void>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { getCitasEmitidas } from "./api.js";
|
|
2
|
+
function formatCita(c, idx) {
|
|
3
|
+
console.log(`\nCita #${idx + 1}`);
|
|
4
|
+
const campos = [
|
|
5
|
+
["Fecha", c.citFecha ?? ""],
|
|
6
|
+
["Hora", c.citHora ?? ""],
|
|
7
|
+
["Centro", c.citCenAsiDes ?? ""],
|
|
8
|
+
["Estado", c.citEstCita ?? ""],
|
|
9
|
+
["Nro cita", c.citActMedNum ?? ""],
|
|
10
|
+
["Cod autogen", c.citAutoGenCod ?? ""],
|
|
11
|
+
];
|
|
12
|
+
for (const [label, val] of campos) {
|
|
13
|
+
if (val)
|
|
14
|
+
console.log(` ${label.padEnd(12)}: ${val}`);
|
|
15
|
+
}
|
|
16
|
+
// Campos extras que lleguen del API
|
|
17
|
+
const conocidos = new Set([
|
|
18
|
+
"citFecha",
|
|
19
|
+
"citHora",
|
|
20
|
+
"citCenAsiDes",
|
|
21
|
+
"citEstCita",
|
|
22
|
+
"citActMedNum",
|
|
23
|
+
"citAutoGenCod",
|
|
24
|
+
]);
|
|
25
|
+
for (const [k, v] of Object.entries(c)) {
|
|
26
|
+
if (!conocidos.has(k) && v !== null && v !== undefined && v !== "") {
|
|
27
|
+
console.log(` ${k.padEnd(12)}: ${String(v)}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export async function cmdCitas() {
|
|
32
|
+
let citas;
|
|
33
|
+
try {
|
|
34
|
+
citas = await getCitasEmitidas();
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
console.error(String(err));
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
if (citas.length === 0) {
|
|
41
|
+
console.log("No tienes citas registradas.");
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
console.log(`Citas emitidas (${citas.length})`);
|
|
45
|
+
console.log("─".repeat(40));
|
|
46
|
+
citas.forEach(formatCita);
|
|
47
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function cmdEspecialidades(codCentro: string): Promise<void>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { getParametroSolicitud } from "./api.js";
|
|
2
|
+
function formatServicio(s) {
|
|
3
|
+
console.log(`\n [${s.codServicioHosp}] ${s.desServicioHosp}`);
|
|
4
|
+
if (s.vdataActSubAct && s.vdataActSubAct.length > 0) {
|
|
5
|
+
for (const a of s.vdataActSubAct) {
|
|
6
|
+
console.log(` ${a.codActSubAct.padEnd(8)} ${a.desSubActHosp}`);
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export async function cmdEspecialidades(codCentro) {
|
|
11
|
+
let data;
|
|
12
|
+
try {
|
|
13
|
+
data = await getParametroSolicitud(codCentro);
|
|
14
|
+
}
|
|
15
|
+
catch (err) {
|
|
16
|
+
console.error(String(err));
|
|
17
|
+
process.exit(1);
|
|
18
|
+
}
|
|
19
|
+
const servicios = data.dataParmServicioHosp;
|
|
20
|
+
if (!servicios || servicios.length === 0) {
|
|
21
|
+
console.log(`Sin especialidades para el centro "${codCentro}".`);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
console.log(`Especialidades — centro ${codCentro} (${servicios.length})`);
|
|
25
|
+
console.log("─".repeat(50));
|
|
26
|
+
for (const s of servicios) {
|
|
27
|
+
formatServicio(s);
|
|
28
|
+
}
|
|
29
|
+
console.log("");
|
|
30
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function cmdFechas(codCentro: string, codServicioHosp: string, codActSubAct: string): Promise<void>;
|