-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagendamientos.html
More file actions
1608 lines (1350 loc) · 49.6 KB
/
agendamientos.html
File metadata and controls
1608 lines (1350 loc) · 49.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Agendamiento Avanzado - Clínica Odontológica</title>
<!-- ✅ FullCalendar -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.css">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.15/index.global.min.js"></script>
<!-- 🔐 GUARD / PERMISOS POR MODULO (SUPABASE) + APP -->
<script type="module">
import { createClient } from "https://cdn.jsdelivr.net/npm/@supabase/supabase-js/+esm";
// ==============================
// ✅ CONFIG SUPABASE (MISMA CONFIG QUE YA TENÍAS)
// ==============================
const supabase = createClient(
"https://dmcfrmpqlkrqbpjhrfyo.supabase.co",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRtY2ZybXBxbGtycWJwamhyZnlvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjI5MzU0MDIsImV4cCI6MjA3ODUxMTQwMn0.YY_6t_lCTs5mK-a_eEdBFa6l9_NBM3B4YDtWOXayCBE"
);
// Hacerlo global para que el resto del JS lo use
window.supabase = supabase;
// ==============================
// ✅ URLs DE TU APP (MISMAS QUE YA TENÍAS)
// ==============================
window.APP_URLS = {
LOGIN: "https://cacg1022.github.io/ODONTOLOGIA/login.html",
HOME: "https://cacg1022.github.io/ODONTOLOGIA/index.html",
};
// ==============================
// ✅ CAMBIA ESTO EN CADA MODULO
// (debe coincidir EXACTO con modulos_permisos.modulo)
// ==============================
const MODULO = "agendamientos";
// Ejemplos:
// const MODULO = "facturacion";
// const MODULO = "historia_clinica";
// const MODULO = "plan_tratamiento";
// const MODULO = "reportes";
async function verificarSesion() {
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
window.location.href = window.APP_URLS.LOGIN;
return null;
}
return session;
}
async function validarPermisoModulo() {
const session = await verificarSesion();
if (!session) return { ok:false };
// 1) Leer rol desde profiles
const { data: perfil, error: ePerfil } = await supabase
.from("profiles")
.select("role")
.eq("id", session.user.id)
.single();
if (ePerfil || !perfil?.role) {
alert("No se pudo obtener tu rol.");
window.location.href = window.APP_URLS.HOME;
return { ok:false };
}
const rol = String(perfil.role).toLowerCase().trim(); // admin/doctor/auxiliar/paciente
// 2) Leer permisos del módulo
const { data: permiso, error: ePerm } = await supabase
.from("modulos_permisos")
.select("admin, doctor, auxiliar, paciente, modulo")
.eq("modulo", MODULO)
.maybeSingle();
if (ePerm) {
console.error("❌ Error leyendo modulos_permisos:", ePerm);
alert("Error leyendo permisos del módulo: " + (ePerm.message || ePerm));
window.location.href = window.APP_URLS.HOME;
return { ok:false };
}
if (!permiso) {
console.warn("⚠️ No existe fila en modulos_permisos para modulo =", MODULO);
alert("Módulo no configurado en permisos.");
window.location.href = window.APP_URLS.HOME;
return { ok:false };
}
// 3) Validar permiso
if (!permiso[rol]) {
alert("⛔ No tienes permiso para acceder a este módulo.");
window.location.href = window.APP_URLS.HOME;
return { ok:false };
}
console.log("✅ Acceso permitido a:", MODULO, "Rol:", rol);
return { ok:true, session, rol };
}
// ✅ Si se cierra sesión, sacarlo
supabase.auth.onAuthStateChange((_event, session) => {
if (!session) window.location.href = window.APP_URLS.LOGIN;
});
// =========================================
// ✅ AQUI EMPIEZA TU CODIGO DE AGENDA (SIN OMITIR)
// (MISMAS CONFIGS, SOLO QUITAMOS EL DOBLE createClient)
// =========================================
const LOGIN_URL = window.APP_URLS.LOGIN;
const HOME_URL = window.APP_URLS.HOME;
// ✅ Tablas en español
const TABLA_CITAS = "citas";
const TABLA_PROFESIONALES = "profesionales";
// ✅ HISTORIAS CLÍNICAS (AJUSTABLE SI TU TABLA/CAMPOS SE LLAMAN DISTINTO)
const TABLA_HISTORIAS = "HISTORIAS CLINICAS";
const HIST_COL_DOCUMENTO = "Numero de Identificacion";
const HIST_COL_NOMBRE = "Nombre y apellido";
const HIST_COL_TELEFONO = "paciente_cel";
const HIST_COL_CORREO = "paciente_email";
// ✅ Lista de especialidades del procedimiento
const ESPECIALIDADES = [
"Cita de Valoracion",
"Odontologia General",
"Rehabilitacion Oral",
"Endodoncia",
"Periodoncia",
"Ortodoncia",
"Cirugia",
"Odontopediatría"
];
// =========================
// Helpers UI
// =========================
const $ = (id) => document.getElementById(id);
function toast(msg, type="info"){
const el = $("toast");
if(!el) return alert(msg);
el.textContent = msg;
el.className = "toast show " + type;
clearTimeout(window.__toastT);
window.__toastT = setTimeout(()=> el.className = "toast", 2600);
}
function setLoading(isLoading){
const b = $("loading");
if(!b) return;
b.style.display = isLoading ? "flex" : "none";
}
function toLocalInputValue(dateObj){
const pad = (n)=> String(n).padStart(2,"0");
const y = dateObj.getFullYear();
const m = pad(dateObj.getMonth()+1);
const d = pad(dateObj.getDate());
const hh = pad(dateObj.getHours());
const mm = pad(dateObj.getMinutes());
return `${y}-${m}-${d}T${hh}:${mm}`;
}
// ✅ Mantener para cálculos/título (usa UTC)
function toISOFromLocalInput(val){
const d = new Date(val);
if (isNaN(d.getTime())) return null;
return d.toISOString();
}
// ✅ NUEVO: guardar en DB como hora local (Colombia) sin zona
function toDbLocalTimestamp(val){
// "2026-01-07T16:00" -> "2026-01-07 16:00:00"
if (!val) return null;
return String(val).replace("T"," ") + ":00";
}
// ✅ NUEVO: Date -> "YYYY-MM-DD HH:mm:ss" en hora local
function toDbFromDate(dateObj){
if (!dateObj || !(dateObj instanceof Date) || isNaN(dateObj.getTime())) return null;
const pad = (n)=> String(n).padStart(2,"0");
const y = dateObj.getFullYear();
const m = pad(dateObj.getMonth()+1);
const d = pad(dateObj.getDate());
const hh = pad(dateObj.getHours());
const mm = pad(dateObj.getMinutes());
const ss = pad(dateObj.getSeconds());
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
}
// ✅ NUEVO: DB "YYYY-MM-DD HH:mm:ss" -> input datetime-local "YYYY-MM-DDTHH:mm"
function dbTimestampToDatetimeLocal(ts){
if (!ts) return "";
const s = String(ts);
// acepta "YYYY-MM-DD HH:mm:ss" o "YYYY-MM-DDTHH:mm:ss"
return s.replace(" ", "T").slice(0,16);
}
function normalizeText(t){ return (t || "").trim(); }
function colorPorEstado(estado){
const s = String(estado || "").toLowerCase();
if (s === "confirmada") return "#2563eb";
if (s === "atendida") return "#16a34a";
if (s === "cancelada") return "#ef4444";
return "#f59e0b"; // programada
}
function escapeHtml(str){
return String(str || "")
.replaceAll("&","&")
.replaceAll("<","<")
.replaceAll(">",">")
.replaceAll('"',""")
.replaceAll("'","'");
}
function pad2(n){ return String(n).padStart(2,"0"); }
function formatHoraLocal(dateObj){
return `${pad2(dateObj.getHours())}:${pad2(dateObj.getMinutes())}`;
}
function duracionMinutos(startISO, endISO){
const s = new Date(startISO);
const e = new Date(endISO);
const ms = e - s;
return Math.max(0, Math.round(ms / 60000));
}
function formatoDuracion(mins){
if (mins < 60) return `${mins} min`;
const h = Math.floor(mins/60);
const m = mins % 60;
return m === 0 ? `${h} h` : `${h} h ${m} min`;
}
// =========================
// n8n Webhook
// =========================
async function enviarCitaAN8N(payload){
try{
await fetch("https://ftth-n8n2.pzveh5.easypanel.host/webhook/a331764c-dc97-4e11-887c-18338dccb839", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
});
} catch(e){
console.warn("No se pudo enviar a n8n:", e);
}
}
// =========================
// Auth + Roles (TU LOGICA ORIGINAL)
// =========================
async function cargarRolDesdeProfiles(userId){
try {
const { data, error } = await supabase
.from("profiles")
.select("role")
.eq("id", userId)
.single();
if (error) return null;
return data?.role || null;
} catch {
return null;
}
}
async function verificarSesionYPermisos(){
const { data: { session } } = await supabase.auth.getSession();
if (!session){
window.location.href = LOGIN_URL;
return { ok:false };
}
$("user-email").textContent = session.user?.email || "Usuario autenticado";
const role = await cargarRolDesdeProfiles(session.user.id);
$("user-role").textContent = role ? `Rol: ${role}` : "Rol: (sin rol)";
const r = String(role || "").toLowerCase().trim();
const allowed = (r === "admin" || r === "auxiliar"|| r === "doctor");
if (!allowed){
$("blocked").style.display = "block";
$("app").style.display = "none";
return { ok:false, session, role };
}
$("blocked").style.display = "none";
$("app").style.display = "grid";
return { ok:true, session, role };
}
supabase.auth.onAuthStateChange((_event, session) => {
if (!session) window.location.href = LOGIN_URL;
});
window.cerrarSesion = async () => {
try { await supabase.auth.signOut(); } catch(e) {}
try { localStorage.removeItem("usuario_logueado"); } catch(e) {}
window.location.href = LOGIN_URL;
};
// =========================
// Profesionales (cargar select)
// =========================
let profesionalesCache = [];
async function cargarProfesionales(){
const { data, error } = await supabase
.from(TABLA_PROFESIONALES)
.select("id, nombre, activo, profesion, especialidad")
.order("nombre", { ascending: true });
if (error) throw new Error(error.message);
profesionalesCache = (data || []).filter(p => p.activo === true);
const sel = $("profesional_id");
sel.innerHTML = `<option value="">-- Selecciona --</option>` +
profesionalesCache.map(p => `<option value="${p.id}">${escapeHtml(p.nombre)}</option>`).join("");
const filt = $("filterProfessional");
filt.innerHTML = `<option value="">Todos</option>` +
profesionalesCache.map(p => `<option value="${p.id}">${escapeHtml(p.nombre)}</option>`).join("");
}
function getNombreProfesionalPorId(id){
return profesionalesCache.find(p => p.id === id)?.nombre || "";
}
// =========================
// Especialidades (cargar select)
// =========================
function cargarEspecialidades(){
const sel = $("especialidad");
sel.innerHTML =
`<option value="">-- Selecciona --</option>` +
ESPECIALIDADES.map(e => `<option value="${escapeHtml(e)}">${escapeHtml(e)}</option>`).join("");
const filt = $("filterEspecialidad");
filt.innerHTML =
`<option value="todos">Todas</option>` +
ESPECIALIDADES.map(e => `<option value="${escapeHtml(e)}">${escapeHtml(e)}</option>`).join("");
}
// =========================
// Autocompletar paciente desde HISTORIAS CLÍNICAS
// =========================
let __lookupTimer = null;
async function buscarPacienteEnHistorias(documento){
const docTxt = normalizeText(documento);
if (!docTxt) return { found: false };
const docNum = Number(docTxt);
if (!Number.isFinite(docNum)) return { found: false };
const selectCols = `"${HIST_COL_NOMBRE}",${HIST_COL_TELEFONO},${HIST_COL_CORREO}`;
const { data, error } = await supabase
.from(TABLA_HISTORIAS)
.select(selectCols)
.eq(HIST_COL_DOCUMENTO, docNum)
.maybeSingle();
if (error){
console.error("Error HISTORIAS:", error);
toast(`Error consultando historias: ${error.message}`, "error");
return { found: false, error };
}
if (!data) return { found: false };
return {
found: true,
nombre: data[HIST_COL_NOMBRE] ?? "",
telefono: data[HIST_COL_TELEFONO] ?? "",
correo: data[HIST_COL_CORREO] ?? ""
};
}
async function autocompletarPacientePorDocumento({ showToast = false } = {}){
const doc = normalizeText($("documento_paciente").value);
if (!doc) return;
const last = $("documento_paciente").dataset.lastLookup || "";
if (last === doc) return;
$("documento_paciente").dataset.lastLookup = doc;
try{
setLoading(true);
const res = await buscarPacienteEnHistorias(doc);
if (res.found){
if (!normalizeText($("nombre_paciente").value)) $("nombre_paciente").value = res.nombre || "";
if (!normalizeText($("telefono_paciente").value)) $("telefono_paciente").value = res.telefono || "";
if (!normalizeText($("correo_paciente").value)) $("correo_paciente").value = res.correo || "";
$("documento_paciente").dataset.patientFound = "true";
if (showToast) toast("Paciente encontrado: datos autocompletados.", "ok");
} else {
$("documento_paciente").dataset.patientFound = "false";
if (showToast) toast("Paciente no encontrado. Diligencia los datos manualmente.", "warn");
}
actualizarPreviewTitulo();
} finally {
setLoading(false);
}
}
function autocompletarPacienteDebounced(){
clearTimeout(__lookupTimer);
__lookupTimer = setTimeout(() => autocompletarPacientePorDocumento({ showToast: false }), 450);
}
// =========================
// Título automático
// =========================
function construirTituloAutomatico({ inicioISO, finISO, nombrePaciente, cedulaPaciente, especialidad }){
const s = new Date(inicioISO);
const e = new Date(finISO);
const rango = `${formatHoraLocal(s)} - ${formatHoraLocal(e)}`;
const mins = duracionMinutos(inicioISO, finISO);
const dur = formatoDuracion(mins);
const np = normalizeText(nombrePaciente) || "Paciente";
const cc = normalizeText(cedulaPaciente) || "Sin cédula";
const esp = normalizeText(especialidad) || "Sin especialidad";
return `${rango}, ${dur}\n${np}, ${cc}\n${esp}`;
}
// =========================
// CRUD Supabase (citas)
// =========================
function rowToEvent(row){
// ✅ Como ahora inicio/fin son timestamp sin tz, los convertimos a Date desde partes (más seguro)
const start = new Date(dbTimestampToDatetimeLocal(row.inicio));
const end = new Date(dbTimestampToDatetimeLocal(row.fin));
const estado = row.estado || "programada";
const titulo = normalizeText(row.titulo)
? row.titulo
: construirTituloAutomatico({
inicioISO: toISOFromLocalInput(dbTimestampToDatetimeLocal(row.inicio)),
finISO: toISOFromLocalInput(dbTimestampToDatetimeLocal(row.fin)),
nombrePaciente: row.nombre_paciente,
cedulaPaciente: row.documento_paciente,
especialidad: row.especialidad
});
return {
id: row.id,
title: titulo,
start: dbTimestampToDatetimeLocal(row.inicio),
end: dbTimestampToDatetimeLocal(row.fin),
backgroundColor: colorPorEstado(estado),
borderColor: colorPorEstado(estado),
extendedProps: {
nombre_paciente: row.nombre_paciente || "",
documento_paciente: row.documento_paciente || "",
telefono_paciente: row.telefono_paciente || "",
correo_paciente: row.correo_paciente || "", // ✅ ahora sí
profesional_id: row.profesional_id || "",
nombre_profesional: row.nombre_profesional || "",
especialidad: row.especialidad || "",
estado: estado,
notas: row.notas || "",
inicio_local: toLocalInputValue(start),
fin_local: toLocalInputValue(end),
}
};
}
async function fetchCitas(rangeStartISO, rangeEndISO, profesionalIdFiltro, estadoFiltro, especialidadFiltro){
// ✅ rangeStartISO/rangeEndISO vienen en ISO UTC por FullCalendar.
// Convertimos a hora local para comparar con timestamp sin tz en DB.
const startLocal = toDbFromDate(new Date(rangeStartISO));
const endLocal = toDbFromDate(new Date(rangeEndISO));
let q = supabase
.from(TABLA_CITAS)
.select("*")
.gte("inicio", startLocal)
.lt("inicio", endLocal)
.order("inicio", { ascending: true });
if (profesionalIdFiltro) q = q.eq("profesional_id", profesionalIdFiltro);
if (estadoFiltro && estadoFiltro !== "todos") q = q.eq("estado", estadoFiltro);
if (especialidadFiltro && especialidadFiltro !== "todos") q = q.eq("especialidad", especialidadFiltro);
const { data, error } = await q;
if (error) throw new Error(error.message);
return data || [];
}
async function getCitaById(id){
const { data, error } = await supabase
.from(TABLA_CITAS)
.select("*")
.eq("id", id)
.single();
if (error) throw new Error(error.message);
return data;
}
async function crearCita(row){
const { data, error } = await supabase
.from(TABLA_CITAS)
.insert(row)
.select("*")
.single();
if (error) throw new Error(error.message);
return data;
}
async function actualizarCita(id, row){
const { data, error } = await supabase
.from(TABLA_CITAS)
.update(row)
.eq("id", id)
.select("*")
.single();
if (error) throw new Error(error.message);
return data;
}
async function eliminarCita(id){
const { error } = await supabase
.from(TABLA_CITAS)
.delete()
.eq("id", id);
if (error) throw new Error(error.message);
return true;
}
// =========================
// Modal
// =========================
function openModal(mode, payload){
$("modal").classList.add("open");
$("modal").setAttribute("aria-hidden","false");
$("modalTitle").textContent = mode === "edit" ? "Editar cita" : "Nueva cita";
$("citaId").value = payload?.id || "";
$("titulo").value = payload?.titulo || "";
$("documento_paciente").value = payload?.documento_paciente || "";
$("nombre_paciente").value = payload?.nombre_paciente || "";
$("telefono_paciente").value = payload?.telefono_paciente || "";
$("correo_paciente").value = payload?.correo_paciente || "";
$("profesional_id").value = payload?.profesional_id || "";
$("especialidad").value = payload?.especialidad || "";
$("estado").value = payload?.estado || "programada";
$("notas").value = payload?.notas || "";
$("inicio").value = payload?.inicio_local || "";
$("fin").value = payload?.fin_local || "";
$("documento_paciente").dataset.lastLookup = "";
$("documento_paciente").dataset.patientFound = "";
if (!normalizeText($("titulo").value) && payload?.inicio_local && payload?.fin_local){
const inicioISO = toISOFromLocalInput(payload.inicio_local);
const finISO = toISOFromLocalInput(payload.fin_local);
if (inicioISO && finISO){
$("titulo").value = construirTituloAutomatico({
inicioISO,
finISO,
nombrePaciente: $("nombre_paciente").value,
cedulaPaciente: $("documento_paciente").value,
especialidad: $("especialidad").value
});
}
}
$("titulo_preview").textContent = $("titulo").value || "";
$("btnDelete").style.display = mode === "edit" ? "inline-flex" : "none";
$("btnSave").textContent = mode === "edit" ? "Guardar cambios" : "Crear cita";
// En móvil: al abrir, mandamos scroll del cuerpo arriba
const body = $("modalBody");
if (body) body.scrollTop = 0;
if (mode !== "edit" && normalizeText($("documento_paciente").value)){
autocompletarPacientePorDocumento({ showToast: false });
} else {
actualizarPreviewTitulo();
}
// 🔔 Notificar paciente (por defecto SI)
$("notificar_paciente").checked =
payload?.notificar_paciente !== false;
}
function closeModal(){
$("modal").classList.remove("open");
$("modal").setAttribute("aria-hidden","true");
}
function actualizarPreviewTitulo(){
const inicioLocal = $("inicio").value;
const finLocal = $("fin").value;
if (!inicioLocal || !finLocal) return;
const inicioISO = toISOFromLocalInput(inicioLocal);
const finISO = toISOFromLocalInput(finLocal);
if (!inicioISO || !finISO) return;
const titulo = construirTituloAutomatico({
inicioISO,
finISO,
nombrePaciente: $("nombre_paciente").value,
cedulaPaciente: $("documento_paciente").value,
especialidad: $("especialidad").value
});
$("titulo").value = titulo;
$("titulo_preview").textContent = titulo;
}
// =========================
// FullCalendar
// =========================
let calendar;
let currentSession = null;
function getFilters(){
return {
profesional_id: $("filterProfessional").value || "",
estado: $("filterStatus").value || "todos",
especialidad: $("filterEspecialidad").value || "todos"
};
}
async function reloadCalendarEvents(){
if (!calendar) return;
setLoading(true);
try{
const view = calendar.view;
const rangeStart = view.activeStart.toISOString();
const rangeEnd = view.activeEnd.toISOString();
const { profesional_id, estado, especialidad } = getFilters();
const rows = await fetchCitas(rangeStart, rangeEnd, profesional_id, estado, especialidad);
const events = rows.map(rowToEvent);
calendar.removeAllEvents();
events.forEach(e => calendar.addEvent(e));
$("rangeLabel").textContent = view.title || new Date().toLocaleDateString("es-CO");
} catch(e){
console.error(e);
toast("Error cargando agenda: " + e.message, "error");
} finally {
setLoading(false);
}
}
async function initCalendar(){
calendar = new FullCalendar.Calendar($("calendar"), {
locale: "es",
timeZone: "local",
initialView: "timeGridWeek",
nowIndicator: true,
selectable: true,
editable: true,
eventResizableFromStart: true,
dayMaxEvents: true,
allDaySlot: false,
slotMinTime: "07:00:00",
slotMaxTime: "20:00:00",
slotDuration: "00:15:00",
headerToolbar: false,
select: (info) => {
openModal("create", {
inicio_local: toLocalInputValue(info.start),
fin_local: toLocalInputValue(info.end),
estado: "programada"
});
},
dateClick: (info) => {
const start = info.date;
const end = new Date(start.getTime() + 30*60*1000);
openModal("create", {
inicio_local: toLocalInputValue(start),
fin_local: toLocalInputValue(end),
estado: "programada"
});
},
// ✅ al hacer click, consultamos la cita REAL en Supabase por id
eventClick: async (info) => {
try{
setLoading(true);
const ev = info.event;
const row = await getCitaById(ev.id);
openModal("edit", {
id: row.id,
titulo: row.titulo,
nombre_paciente: row.nombre_paciente,
documento_paciente: row.documento_paciente,
telefono_paciente: row.telefono_paciente,
correo_paciente: row.correo_paciente,
profesional_id: row.profesional_id,
especialidad: row.especialidad,
estado: row.estado,
notas: row.notas,
// ✅ timestamp sin tz -> input datetime-local directo
inicio_local: dbTimestampToDatetimeLocal(row.inicio),
fin_local: dbTimestampToDatetimeLocal(row.fin),
notificar_paciente: row.notificar_paciente,
});
} catch(e){
console.error(e);
toast("No se pudo abrir la cita: " + e.message, "error");
} finally {
setLoading(false);
}
},
eventDrop: async (info) => {
try{
setLoading(true);
const id = info.event.id;
// ✅ Guardar en DB como hora local (no ISO UTC)
const inicioDB = toDbFromDate(info.event.start);
const finDB = toDbFromDate(info.event.end);
// Para título seguimos usando ISO (solo visual)
const inicioISO = info.event.start.toISOString();
const finISO = info.event.end.toISOString();
const nuevoTitulo = construirTituloAutomatico({
inicioISO,
finISO,
nombrePaciente: info.event.extendedProps.nombre_paciente,
cedulaPaciente: info.event.extendedProps.documento_paciente,
especialidad: info.event.extendedProps.especialidad
});
const row = { inicio: inicioDB, fin: finDB, titulo: nuevoTitulo };
await actualizarCita(id, row);
info.event.setProp("title", nuevoTitulo);
info.event.setExtendedProp("inicio_local", toLocalInputValue(info.event.start));
info.event.setExtendedProp("fin_local", toLocalInputValue(info.event.end));
toast("Cita reprogramada.", "ok");
} catch(e){
console.error(e);
info.revert();
toast("Error al mover: " + e.message, "error");
} finally {
setLoading(false);
}
},
eventResize: async (info) => {
try{
setLoading(true);
const id = info.event.id;
// ✅ Guardar en DB como hora local (no ISO UTC)
const inicioDB = toDbFromDate(info.event.start);
const finDB = toDbFromDate(info.event.end);
// Para título seguimos usando ISO (solo visual)
const inicioISO = info.event.start.toISOString();
const finISO = info.event.end.toISOString();
const nuevoTitulo = construirTituloAutomatico({
inicioISO,
finISO,
nombrePaciente: info.event.extendedProps.nombre_paciente,
cedulaPaciente: info.event.extendedProps.documento_paciente,
especialidad: info.event.extendedProps.especialidad
});
const row = { inicio: inicioDB, fin: finDB, titulo: nuevoTitulo };
await actualizarCita(id, row);
info.event.setProp("title", nuevoTitulo);
info.event.setExtendedProp("inicio_local", toLocalInputValue(info.event.start));
info.event.setExtendedProp("fin_local", toLocalInputValue(info.event.end));
toast("Duración actualizada.", "ok");
} catch(e){
console.error(e);
info.revert();
toast("Error al redimensionar: " + e.message, "error");
} finally {
setLoading(false);
}
},
datesSet: async () => {
await reloadCalendarEvents();
}
});
calendar.render();
await reloadCalendarEvents();
}
// =========================
// UI
// =========================
function wireButtons(){
$("btnDay").addEventListener("click", ()=> calendar.changeView("timeGridDay"));
$("btnWeek").addEventListener("click", ()=> calendar.changeView("timeGridWeek"));
$("btnMonth").addEventListener("click", ()=> calendar.changeView("dayGridMonth"));
$("btnToday").addEventListener("click", ()=> calendar.today());
$("btnPrev").addEventListener("click", ()=> calendar.prev());
$("btnNext").addEventListener("click", ()=> calendar.next());
$("btnHome").addEventListener("click", ()=> window.location.href = HOME_URL);
$("filterProfessional").addEventListener("change", ()=> reloadCalendarEvents());
$("filterStatus").addEventListener("change", ()=> reloadCalendarEvents());
$("filterEspecialidad").addEventListener("change", ()=> reloadCalendarEvents());
$("btnNew").addEventListener("click", () => {
const start = new Date();
start.setSeconds(0,0);
const m = start.getMinutes();
const rounded = Math.ceil(m/15)*15;
start.setMinutes(rounded);
const end = new Date(start.getTime() + 30*60*1000);
openModal("create", {
inicio_local: toLocalInputValue(start),
fin_local: toLocalInputValue(end),
estado: "programada"
});
});
$("btnClose").addEventListener("click", closeModal);
$("modalBackdrop").addEventListener("click", closeModal);
window.addEventListener("keydown", (e)=> { if (e.key === "Escape") closeModal(); });
$("btnCancel").addEventListener("click", closeModal);
$("btnSave").addEventListener("click", onSave);
$("btnDelete").addEventListener("click", onDelete);
["nombre_paciente","documento_paciente","especialidad","inicio","fin"].forEach(id=>{
$(id).addEventListener("input", actualizarPreviewTitulo);
$(id).addEventListener("change", actualizarPreviewTitulo);
});
$("documento_paciente").addEventListener("input", autocompletarPacienteDebounced);
$("documento_paciente").addEventListener("blur", () => autocompletarPacientePorDocumento({ showToast: true }));
["nombre_paciente","telefono_paciente","correo_paciente"].forEach(id=>{
$(id).addEventListener("input", actualizarPreviewTitulo);
$(id).addEventListener("change", actualizarPreviewTitulo);
});
}
async function onSave(){
try{
setLoading(true);
const id = $("citaId").value.trim();
const profesionalId = $("profesional_id").value;
const especialidad = $("especialidad").value;
const inicioLocal = $("inicio").value;
const finLocal = $("fin").value;
if (!profesionalId){ toast("Selecciona un profesional.", "warn"); return; }
if (!especialidad){ toast("Selecciona la especialidad del procedimiento.", "warn"); return; }
if (!inicioLocal || !finLocal){ toast("Selecciona inicio y fin.", "warn"); return; }
// ✅ Para cálculos/título seguimos usando ISO (UTC)
const inicioISO = toISOFromLocalInput(inicioLocal);
const finISO = toISOFromLocalInput(finLocal);
if (!inicioISO || !finISO){ toast("Fecha/hora inválida.", "warn"); return; }
// ✅ Validación de rango usando valores del input (local)
const inicioD = new Date(inicioLocal);
const finD = new Date(finLocal);
if (finD <= inicioD){ toast("La hora final debe ser mayor que la inicial.", "warn"); return; }
const tituloAuto = construirTituloAutomatico({
inicioISO,
finISO,
nombrePaciente: $("nombre_paciente").value,
cedulaPaciente: $("documento_paciente").value,
especialidad: especialidad
});
$("titulo").value = tituloAuto;
$("titulo_preview").textContent = tituloAuto;
// ✅ Guardar en DB como hora local Colombia (timestamp sin tz)
const inicioDB = toDbLocalTimestamp(inicioLocal);
const finDB = toDbLocalTimestamp(finLocal);
const notificarPaciente = $("notificar_paciente").checked;
const row = {
usuario_id: currentSession.user.id,
profesional_id: profesionalId,
nombre_paciente: normalizeText($("nombre_paciente").value),
documento_paciente: normalizeText($("documento_paciente").value),
telefono_paciente: normalizeText($("telefono_paciente").value),
correo_paciente: normalizeText($("correo_paciente").value),
especialidad: normalizeText(especialidad),
titulo: tituloAuto,
estado: $("estado").value || "programada",
notas: normalizeText($("notas").value),
inicio: inicioDB,
fin: finDB,
nombre_profesional: getNombreProfesionalPorId(profesionalId),
usuario_email: currentSession.user.email,
// 🔔 NUEVO
notificar_paciente: notificarPaciente
};
let citaResult = null;
if (id){
citaResult = await actualizarCita(id, row);
toast("Cita actualizada.", "ok");
} else {
citaResult = await crearCita(row);
toast("Cita creada.", "ok");
}
// 🔔 Enviar a n8n (crear o actualizar)
enviarCitaAN8N({
accion: id ? "actualizada" : "creada",
notificar_paciente: notificarPaciente,
cita: citaResult,
usuario: {
id: currentSession.user.id,
email: currentSession.user.email
},
fecha_envio: new Date().toISOString()
});
closeModal();
await reloadCalendarEvents();
} catch(e){
console.error(e);
toast("Error guardando: " + e.message, "error");
} finally {
setLoading(false);
}
}
async function onDelete(){
const id = $("citaId").value.trim();
if (!id) return;
const ok = confirm("¿Eliminar esta cita definitivamente?");
if (!ok) return;
try{
setLoading(true);
await eliminarCita(id);
closeModal();
toast("Cita eliminada.", "ok");
await reloadCalendarEvents();
} catch(e){
console.error(e);
toast("Error eliminando: " + e.message, "error");