-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformulasmedicas.html
More file actions
1405 lines (1210 loc) · 43.8 KB
/
formulasmedicas.html
File metadata and controls
1405 lines (1210 loc) · 43.8 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>Fórmula Médica - Clínica Dra. Leidi Silva</title>
<!-- Fuente bonita (opcional) -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
:root{
--bg:#f5f7fb;
--card:#ffffff;
--text:#0f172a;
--muted:#64748b;
--line: rgba(15, 23, 42, .12);
--brand:#2563eb;
--brand2:#1d4ed8;
--ok:#16a34a;
--danger:#dc2626;
--shadow: 0 18px 40px rgba(15,23,42,.10);
--radius: 18px;
--font: "Inter", ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
}
*{ box-sizing:border-box; }
body{
margin:0;
font-family: var(--font);
color: var(--text);
background:
radial-gradient(900px 500px at 25% 15%, rgba(37, 99, 235, .08), transparent 55%),
radial-gradient(700px 420px at 85% 75%, rgba(2, 132, 199, .07), transparent 60%),
linear-gradient(180deg, #ffffff, var(--bg));
padding: 22px 14px;
}
.wrap{
width:min(1100px, 100%);
margin: 0 auto;
display:flex;
flex-direction:column;
gap: 14px;
}
.top{
display:flex;
align-items:flex-start;
justify-content:space-between;
gap: 12px;
padding: 16px 18px;
border-radius: var(--radius);
background: linear-gradient(180deg, #fff, #fbfcff);
border: 1px solid var(--line);
box-shadow: var(--shadow);
}
.brand{
display:flex;
gap: 12px;
align-items:center;
min-width: 260px;
}
.brand img{
width: 64px;
height: 64px;
object-fit: contain;
filter: drop-shadow(0 10px 18px rgba(15,23,42,.18));
}
.brand h1{
margin:0;
font-size: 16px;
line-height: 1.15;
letter-spacing: -0.01em;
}
.brand p{
margin:6px 0 0;
color: var(--muted);
font-size: 12.5px;
line-height: 1.2;
}
.meta{
display:flex;
gap: 10px;
align-items:center;
justify-content:flex-end;
flex-wrap: wrap;
}
.chip{
border: 1px solid var(--line);
background:#fff;
border-radius: 999px;
padding: 8px 12px;
box-shadow: 0 8px 18px rgba(15,23,42,.06);
display:flex;
flex-direction:column;
gap: 4px;
font-size: 12px;
color: var(--muted);
white-space: nowrap;
}
.chip b{ color: var(--text); }
.btn{
border: 1px solid var(--line);
background:#fff;
color: var(--text);
padding: 10px 12px;
border-radius: 12px;
font-weight: 800;
cursor: pointer;
box-shadow: 0 10px 18px rgba(15,23,42,.06);
}
.btn:hover{ filter: brightness(.98); transform: translateY(-1px); }
.btn.primary{
background: var(--brand);
border-color: var(--brand);
color:#fff;
}
.btn.primary:hover{ background: var(--brand2); border-color: var(--brand2); }
.btn.ok{
background: var(--ok);
border-color: var(--ok);
color:#fff;
}
.btn.danger{
background: #fff;
border-color: rgba(220,38,38,.30);
color: var(--danger);
}
.grid{
display:grid;
grid-template-columns: repeat(12, 1fr);
gap: 12px;
}
.card{
background: var(--card);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 16px;
}
.title{
margin:0 0 10px;
font-size: 14px;
color: var(--muted);
font-weight: 800;
letter-spacing: .2px;
text-transform: uppercase;
}
.ctrl{ display:flex; flex-direction:column; gap: 7px; }
.ctrl label{
font-size: 12px;
color: var(--muted);
font-weight: 800;
letter-spacing: .2px;
}
input, textarea, select{
width:100%;
border: 1px solid rgba(15,23,42,.18);
border-radius: 12px;
padding: 12px;
font-size: 14px;
outline: none;
background:#fff;
font-family: var(--font);
color: var(--text);
}
textarea{ min-height: 90px; resize: vertical; }
.mono{
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
font-size: 12px;
color: var(--muted);
white-space: pre-wrap;
}
.row-actions{
display:flex;
gap: 10px;
flex-wrap: wrap;
align-items:center;
justify-content:flex-end;
}
table{
width:100%;
border-collapse: collapse;
overflow:hidden;
border-radius: 14px;
border: 1px solid rgba(15,23,42,.10);
}
th, td{
border-bottom: 1px solid rgba(15,23,42,.10);
padding: 10px;
vertical-align: top;
text-align:left;
font-size: 13px;
}
thead th{
background:#f8fafc;
color: var(--muted);
font-size: 12px;
font-weight: 900;
}
td input, td textarea{
padding: 10px;
border-radius: 10px;
font-size: 13px;
}
.t-actions{ width: 130px; white-space: nowrap; }
.hint{
font-size: 12px;
color: var(--muted);
}
.sig-wrap{
display:grid;
grid-template-columns: 1fr;
gap: 10px;
}
canvas{
width: 100%;
height: 150px;
border-radius: 14px;
border: 1px solid rgba(15,23,42,.18);
background: #fff;
touch-action: none;
}
.status{
min-height: 18px;
font-size: 12px;
color: var(--muted);
font-weight: 700;
}
/* Área lista para imprimir */
#printArea{
display:none;
}
@media (max-width: 900px){
.brand{ min-width: unset; }
}
/* ======== PRINT ======== */
@media print{
/* Ocultar botones Imprimir y Cerrar en la impresión */
#modalFormula button{ display:none !important; }
body{ background:#fff; padding:0; }
/* Cuando se imprime desde el modal, ocultar el printArea original para evitar una página extra */
body.printing-modal .print-original{ display:none !important; }
body.printing-modal #modalPrintContainer #printArea{ display:block !important; }
.wrap{ width:100%; margin:0; }
.top, .no-print{ display:none !important; }
#printArea{ display:block; padding: 18px; font-family: var(--font); }
.p-head{
display:flex; align-items:center; justify-content:space-between; gap: 14px;
border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 10px;
}
.p-head img{ width: 90px; height:auto; }
.p-title{ font-weight: 900; font-size: 16px; margin:0; }
.p-sub{ color:#555; margin: 4px 0 0; font-size: 12px; }
.p-box{ border:1px solid #ddd; border-radius: 10px; padding: 10px; margin: 10px 0; }
.p-row{ display:flex; gap: 10px; flex-wrap:wrap; font-size: 12px; }
.p-row b{ min-width: 140px; display:inline-block; }
.p-table{ width:100%; border-collapse: collapse; font-size: 12px; }
.p-table th, .p-table td{ border:1px solid #ddd; padding: 8px; }
.p-table th{ background:#f4f4f4; }
.p-sig{
margin-top: 14px;
display:flex; justify-content:flex-end;
}
.p-sig img{ width: 240px; height:auto; border-bottom: 1px solid #222; padding-bottom: 6px; }
.p-sig .lbl{ text-align:center; font-size: 12px; margin-top: 6px; }
}
/* Alinear nombre del profesional a la izquierda (solo debajo de la firma) */
#pFirmaWrap #pProfesional{ display:block; width:100%; text-align:left; }
/* Alinear texto 'Firma del profesional' a la izquierda */
#pFirmaWrap .lbl{ text-align:left; }
</style>
<script type="module">
import { createClient } from "https://cdn.jsdelivr.net/npm/@supabase/supabase-js/+esm";
// ✅ Supabase (igual que tus páginas)
const supabase = createClient(
"https://dmcfrmpqlkrqbpjhrfyo.supabase.co",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRtY2ZybXBxbGtycWJwamhyZnlvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjI5MzU0MDIsImV4cCI6MjA3ODUxMTQwMn0.YY_6t_lCTs5mK-a_eEdBFa6l9_NBM3B4YDtWOXayCBE"
);
const LOGIN_URL = "https://cacg1022.github.io/ODONTOLOGIA/login.html";
const INDEX_URL = "https://cacg1022.github.io/ODONTOLOGIA/index.html";
const LOGO_URL = "https://static.wixstatic.com/media/63e6ec_3973b230e8aa49869f3127b467fb3e6e~mv2.png/v1/fill/w_426,h_426,al_c,q_85,usm_0.66_1.00_0.01,enc_auto/LOGO%20LEIDI%20SILVA%202%20(1).png";
// ✅ Acceso recomendado (ajusta si quieres permitir auxiliar)
const ALLOWED_ROLES = ["admin","doctor"];
// ✅ Candidatos para tabla de historias clínicas (como tu reporte)
const TABLE_CANDIDATES = [
"HISTORIAS CLINICAS",
];
let HIST_TABLE = null;
// Columnas usadas desde tu historia clínica (según tu HTML actual)
const COL_CEDULA = "Numero de Identificacion";
const COL_NOMBRE = "Nombre y apellido";
const COL_EDAD = "Edad";
const COL_TIPO_ID = "Tipo identificacion";
const COL_LUGAR_EXP= "Lugar exp";
const COL_NAC = "Fecha de nacimiento";
// y de tu historia clínica HTML:
// paciente_tel, paciente_cel, paciente_email, paciente_direccion, paciente_ciudad
// OJO: estas no necesariamente existen en la tabla de supabase; por eso las leemos si están.
const OPTIONAL_COLS = [
"paciente_tel",
"paciente_cel",
"paciente_email",
"paciente_direccion",
"ciudad_de_residencia",
"EPS_Paciente",
"paciente_ciudad" // por si lo usas en otra versión
];
const state = {
session: null,
role: null,
userEmail: "",
firmaDataUrl: "",
meds: []
};
const $ = (id) => document.getElementById(id);
function toast(msg, type="ok"){
const el = $("status");
if (!el) return;
el.style.color = (type==="err") ? "#b91c1c" : (type==="warn" ? "#92400e" : "#64748b");
el.textContent = msg || "";
}
async function verificarSesion(){
const { data: { session } } = await supabase.auth.getSession();
if (!session){
window.location.href = LOGIN_URL;
return null;
}
state.session = session;
state.userEmail = session.user?.email || "";
return session;
}
supabase.auth.onAuthStateChange((_event, session) => {
if (!session) window.location.href = LOGIN_URL;
});
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 validarAcceso(){
const role = (state.role || "user").toString().trim().toLowerCase();
if (!ALLOWED_ROLES.includes(role)){
alert("🚫 Acceso restringido: Solo Admin o Doctor.");
window.location.href = INDEX_URL;
return false;
}
return true;
}
async function detectarTablaHistorias(){
for (const t of TABLE_CANDIDATES){
const { error } = await supabase
.from(t)
.select(`"${COL_CEDULA}"`, { head: true, count: "exact" })
.limit(1);
if (!error) return t;
}
return null;
}
function setHeader(){
$("logoTop").src = LOGO_URL;
$("user-email").textContent = state.userEmail || "Usuario";
$("user-role").textContent = state.role ? `Rol: ${state.role}` : "Rol: (sin rol)";
}
function nowISO(){
const d = new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth()+1).padStart(2,"0");
const dd = String(d.getDate()).padStart(2,"0");
const hh = String(d.getHours()).padStart(2,"0");
const mi = String(d.getMinutes()).padStart(2,"0");
const ss = String(d.getSeconds()).padStart(2,"0");
return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`;
}
function tickClock(){
const s = nowISO();
$("fechaHora").textContent = s;
$("fm_fecha_hora").value = s;
}
function normalizeTipoId(v){
if (Array.isArray(v)) return v.join(", ");
return String(v || "");
}
function setPacienteFromRow(row){
// Campos del formulario (principales)
$("paciente_nombre").value = row?.[COL_NOMBRE] ?? "";
$("paciente_cedula").value = row?.[COL_CEDULA] ?? "";
$("paciente_edad").value = row?.[COL_EDAD] ?? "";
$("paciente_tipoid").value = normalizeTipoId(row?.[COL_TIPO_ID] ?? "");
$("paciente_lugarexp").value = row?.[COL_LUGAR_EXP] ?? "";
$("paciente_nacimiento").value = row?.[COL_NAC] ?? "";
// ✅ Opcionales (tus columnas reales)
$("paciente_correo").value = row?.paciente_email ?? "";
$("paciente_celular").value = (row?.paciente_cel ?? "")?.toString();
$("paciente_telefono").value = (row?.paciente_tel ?? "")?.toString();
$("paciente_direccion").value = row?.paciente_direccion ?? "";
$("paciente_ciudad").value = row?.ciudad_de_residencia ?? "";
$("paciente_eps").value = row?.EPS_Paciente ?? "";
}
async function buscarPaciente(){
toast("");
const cedulaRaw = ($("buscar_cedula").value || "").trim();
if (!cedulaRaw){
toast("Escribe una cédula para buscar.", "warn");
return;
}
if (!HIST_TABLE){
toast("No se detectó la tabla de historias clínicas.", "err");
return;
}
// Intento: cédula numérica
const cedulaNum = Number(cedulaRaw);
const isNum = !Number.isNaN(cedulaNum);
// SELECT: columnas “seguras” + opcionales (si existen, supabase no falla si no están? OJO: si no existe columna, sí falla)
// Para evitar error por columnas que no existan, pedimos solo las que sabemos de tu tabla por el reporte, y luego “*” no es buena idea.
// Entonces: pedimos las básicas y luego intentamos un segundo select con opcionales si quieres.
let q = supabase.from(HIST_TABLE).select(`
"${COL_CEDULA}",
"${COL_NOMBRE}",
"${COL_EDAD}",
"${COL_TIPO_ID}",
"${COL_LUGAR_EXP}",
"${COL_NAC}",
paciente_email,
paciente_cel,
paciente_tel,
paciente_direccion,
ciudad_de_residencia,
"EPS_Paciente"
`).limit(1);
q = isNum ? q.eq(COL_CEDULA, cedulaNum) : q.eq(COL_CEDULA, cedulaRaw);
const { data, error } = await q;
if (error){
console.error(error);
toast("Error buscando paciente: " + (error.message || ""), "err");
return;
}
if (!data || !data.length){
toast("No encontré historia clínica con esa cédula. Puedes llenar los datos manualmente.", "warn");
// set cedula al menos
$("paciente_cedula").value = cedulaRaw;
return;
}
const row = data[0];
// Intento extra: leer columnas opcionales sin romper si fallan
let extras = {};
try{
const { data: d2 } = await supabase
.from(HIST_TABLE)
.select(OPTIONAL_COLS.map(c => `"${c}"`).join(","))
.limit(1)
.eq(COL_CEDULA, isNum ? cedulaNum : cedulaRaw);
if (d2 && d2[0]) extras = d2[0];
}catch(e){ /* si falla, no pasa nada */ }
setPacienteFromRow({ ...row, ...extras });
toast("Paciente cargado desde historia clínica ✅", "ok");
cargarFormulasDelPaciente(row[COL_CEDULA]);
}
function addMedRow(prefill = {}){
const meds = state.meds;
meds.push({
medicamento: prefill.medicamento || "",
concentracion: prefill.concentracion || "",
forma: prefill.forma || "",
dosis: prefill.dosis || "",
frecuencia: prefill.frecuencia || "",
duracion: prefill.duracion || "",
cantidad: prefill.cantidad || "",
indicaciones: prefill.indicaciones || ""
});
renderMeds();
}
function removeMedRow(i){
state.meds.splice(i, 1);
renderMeds();
}
function renderMeds(){
const tb = $("tbMeds");
tb.innerHTML = "";
if (!state.meds.length){
tb.innerHTML = `<tr><td colspan="9" class="mono">Sin medicamentos. Agrega al menos uno si aplica.</td></tr>`;
return;
}
state.meds.forEach((m, i) => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td><input data-k="medicamento" value="${escapeHtmlAttr(m.medicamento)}" placeholder="Ej: Amoxicilina"></td>
<td><input data-k="concentracion" value="${escapeHtmlAttr(m.concentracion)}" placeholder="Ej: 500 mg"></td>
<td><input data-k="forma" value="${escapeHtmlAttr(m.forma)}" placeholder="Ej: cápsulas / jarabe"></td>
<td><input data-k="dosis" value="${escapeHtmlAttr(m.dosis)}" placeholder="Ej: 1 cápsula"></td>
<td><input data-k="frecuencia" value="${escapeHtmlAttr(m.frecuencia)}" placeholder="Ej: cada 8 horas"></td>
<td><input data-k="duracion" value="${escapeHtmlAttr(m.duracion)}" placeholder="Ej: 7 días"></td>
<td><input data-k="cantidad" value="${escapeHtmlAttr(m.cantidad)}" placeholder="Ej: 21"></td>
<td><textarea data-k="indicaciones" placeholder="Indicaciones adicionales...">${escapeHtml(m.indicaciones)}</textarea></td>
<td class="t-actions">
<button type="button" class="btn danger" data-del="1">Eliminar</button>
</td>
`;
tr.querySelectorAll("input,textarea").forEach(el=>{
el.addEventListener("input", ()=>{
const k = el.getAttribute("data-k");
state.meds[i][k] = el.value;
});
});
tr.querySelector('[data-del="1"]').addEventListener("click", ()=> removeMedRow(i));
tb.appendChild(tr);
});
}
function escapeHtml(s){
return String(s ?? "")
.replaceAll("&","&")
.replaceAll("<","<")
.replaceAll(">",">")
.replaceAll('"',""")
.replaceAll("'","'");
}
function escapeHtmlAttr(s){
return escapeHtml(s).replaceAll("\n"," ");
}
// ===== Firma (canvas) =====
function initFirma(){
const canvas = $("firma");
const ctx = canvas.getContext("2d");
function resizeCanvas(){
// Mantener nitidez
const rect = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.max(1, Math.floor(rect.width * dpr));
canvas.height = Math.max(1, Math.floor(rect.height * dpr));
ctx.setTransform(dpr,0,0,dpr,0,0);
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.strokeStyle = "#0f172a";
}
resizeCanvas();
window.addEventListener("resize", resizeCanvas);
let drawing = false;
let last = null;
function posFromEvent(e){
const rect = canvas.getBoundingClientRect();
const p = (e.touches && e.touches[0]) ? e.touches[0] : e;
return { x: p.clientX - rect.left, y: p.clientY - rect.top };
}
function start(e){
e.preventDefault();
drawing = true;
last = posFromEvent(e);
}
function move(e){
if (!drawing) return;
e.preventDefault();
const p = posFromEvent(e);
ctx.beginPath();
ctx.moveTo(last.x, last.y);
ctx.lineTo(p.x, p.y);
ctx.stroke();
last = p;
}
function end(){
drawing = false;
last = null;
// Guardar snapshot base64
state.firmaDataUrl = canvas.toDataURL("image/png");
$("firmaPreview").src = state.firmaDataUrl;
$("firmaPreview").style.display = state.firmaDataUrl ? "block" : "none";
}
canvas.addEventListener("mousedown", start);
canvas.addEventListener("mousemove", move);
window.addEventListener("mouseup", end);
canvas.addEventListener("touchstart", start, { passive:false });
canvas.addEventListener("touchmove", move, { passive:false });
window.addEventListener("touchend", end);
$("btnLimpiarFirma").addEventListener("click", ()=>{
// limpiar
ctx.clearRect(0,0,canvas.width,canvas.height);
state.firmaDataUrl = "";
$("firmaPreview").src = "";
$("firmaPreview").style.display = "none";
});
}
function buildPayload(){
const paciente = {
nombre: ($("paciente_nombre").value || "").trim(),
cedula: ($("paciente_cedula").value || "").trim(),
tipo_id: ($("paciente_tipoid").value || "").trim(),
lugar_exp: ($("paciente_lugarexp").value || "").trim(),
nacimiento: ($("paciente_nacimiento").value || "").trim(),
edad: ($("paciente_edad").value || "").trim(),
correo: ($("paciente_correo").value || "").trim(),
celular: ($("paciente_celular").value || "").trim(),
telefono: ($("paciente_telefono").value || "").trim(),
direccion: ($("paciente_direccion").value || "").trim(),
ciudad: ($("paciente_ciudad").value || "").trim(),
eps: ($("paciente_eps").value || "").trim(),
};
const receta = {
fecha_hora: ($("fm_fecha_hora").value || "").trim(),
diagnostico: ($("diagnostico").value || "").trim(),
alergias: ($("alergias").value || "").trim(),
observaciones: ($("observaciones").value || "").trim(),
medicamentos: state.meds
.map(m => ({
medicamento: (m.medicamento||"").trim(),
concentracion: (m.concentracion||"").trim(),
forma: (m.forma||"").trim(),
dosis: (m.dosis||"").trim(),
frecuencia: (m.frecuencia||"").trim(),
duracion: (m.duracion||"").trim(),
cantidad: (m.cantidad||"").trim(),
indicaciones: (m.indicaciones||"").trim()
}))
.filter(x => Object.values(x).some(v => String(v||"").trim().length))
};
return { paciente, receta };
}
async function guardarFormula(){
toast("");
const { paciente, receta } = buildPayload();
if (!paciente.cedula){
toast("La cédula del paciente es obligatoria.", "err");
return;
}
if (!paciente.nombre){
toast("El nombre del paciente es obligatorio.", "err");
return;
}
if (!receta.fecha_hora){
toast("No se pudo obtener fecha/hora.", "err");
return;
}
if (!state.firmaDataUrl){
const ok = confirm("No hay firma en el canvas. ¿Deseas guardar SIN firma?");
if (!ok) return;
}
const payload = {
paciente_cedula: paciente.cedula,
paciente_nombre: paciente.nombre,
paciente_correo: paciente.correo || null,
paciente_celular: paciente.celular || null,
paciente_telefono: paciente.telefono || null,
paciente_tipo_id: paciente.tipo_id || null,
paciente_lugar_exp: paciente.lugar_exp || null,
paciente_fecha_nacimiento: paciente.nacimiento || null,
paciente_edad: paciente.edad ? Number(paciente.edad) : null,
paciente_direccion: paciente.direccion || null,
paciente_ciudad: paciente.ciudad || null,
paciente_eps: paciente.eps || null,
fecha_hora: receta.fecha_hora, // texto legible
diagnostico: receta.diagnostico || null,
alergias: receta.alergias || null,
observaciones: receta.observaciones || null,
medicamentos: receta.medicamentos || [],
firma_png: state.firmaDataUrl || null,
profesional_id: state.session?.user?.id || null,
profesional_email: state.userEmail || null,
profesional_role: state.role || null
};
$("btnGuardar").disabled = true;
try{
const { data, error } = await supabase
.from("formulas_medicas")
.insert([payload])
.select("id")
.single();
if (error){
console.error(error);
toast("Error guardando: " + (error.message || ""), "err");
return;
}
$("formula_id").value = data?.id || "";
toast("Fórmula guardada ✅ (ID: " + (data?.id || "") + ")", "ok");
// Preparar impresión
buildPrintArea();
} finally{
$("btnGuardar").disabled = false;
}
}
function buildPrintArea(){
const { paciente, receta } = buildPayload();
$("pLogo").src = LOGO_URL;
$("pFechaHora").textContent = receta.fecha_hora || "";
$("pPaciente").textContent = `${paciente.nombre || ""}`;
$("pCedula").textContent = `${paciente.tipo_id ? paciente.tipo_id + " " : ""}${paciente.cedula || ""}`;
$("pContacto").textContent =
`${paciente.celular ? "Cel: " + paciente.celular : ""}${(paciente.celular && paciente.correo) ? " | " : ""}${paciente.correo ? "Email: " + paciente.correo : ""}`;
$("pDiagnostico").textContent = receta.diagnostico || "—";
$("pAlergias").textContent = receta.alergias || "—";
$("pObserv").textContent = receta.observaciones || "—";
const tb = $("pMeds");
tb.innerHTML = "";
const meds = (receta.medicamentos || []);
if (!meds.length){
tb.innerHTML = `<tr><td colspan="7">—</td></tr>`;
} else {
meds.forEach(m=>{
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${escapeHtml(m.medicamento || "")}</td>
<td>${escapeHtml(m.concentracion || "")}</td>
<td>${escapeHtml(m.forma || "")}</td>
<td>${escapeHtml(m.dosis || "")}</td>
<td>${escapeHtml(m.frecuencia || "")}</td>
<td>${escapeHtml(m.duracion || "")}</td>
<td>${escapeHtml(m.indicaciones || "")}</td>
`;
tb.appendChild(tr);
});
}
if (state.firmaDataUrl){
$("pFirma").src = state.firmaDataUrl;
$("pFirmaWrap").style.display = "block";
} else {
$("pFirmaWrap").style.display = "none";
}
$("pProfesional").textContent = `${state.userEmail || ""} (${state.role || ""})`;
}
function imprimir(){
buildPrintArea();
window.print();
}
window.imprimirModalFormula = function(){
// Imprime SOLO la vista del modal (evita 2 páginas por duplicación de #printArea)
document.body.classList.add('printing-modal');
window.print();
// Al cerrar el cuadro de impresión, limpiamos la clase
setTimeout(()=>document.body.classList.remove('printing-modal'), 800);
}
async function init(){
// logo y reloj
$("logoTop").src = LOGO_URL;
tickClock();
setInterval(tickClock, 1000);
// sesión
const session = await verificarSesion();
if (!session) return;
// rol
state.role = (await cargarRolDesdeProfiles(session.user.id)) || "user";
setHeader();
// acceso
const ok = await validarAcceso();
if (!ok) return;
// detectar tabla historias
HIST_TABLE = await detectarTablaHistorias();
$("tablaDetectada").textContent = HIST_TABLE ? `Tabla historias: ${HIST_TABLE}` : "No se detectó tabla de historias clínicas.";
// ===============================
// 🔹 AUTOCARGA DESDE URL (?cedula=)
// ===============================
const params = new URLSearchParams(window.location.search);
const cedulaURL = params.get("cedula");
if (cedulaURL) {
const input = document.getElementById("buscar_cedula");
if (input) {
input.value = cedulaURL;
await buscarPaciente();
}
}
// init meds
state.meds = [];
renderMeds();
// firma
initFirma();
// eventos
$("btnBuscar").addEventListener("click", buscarPaciente);
$("btnAddMed").addEventListener("click", ()=> addMedRow());
$("btnGuardar").addEventListener("click", guardarFormula);
$("btnImprimir").addEventListener("click", imprimir);
$("btnInicio").addEventListener("click", ()=> window.location.href = INDEX_URL);
$("btnLogout").addEventListener("click", async ()=>{
try{ await supabase.auth.signOut(); }catch(e){}
window.location.href = LOGIN_URL;
});
// Enter en búsqueda
$("buscar_cedula").addEventListener("keydown", (e)=>{
if (e.key === "Enter"){ e.preventDefault(); buscarPaciente(); }
});
// firma preview invisible al inicio
$("firmaPreview").style.display = "none";
}
async function cargarFormulasDelPaciente(cedula){
const tbody = $("tbFormulasPaciente");
tbody.innerHTML = `<tr><td colspan="4" class="mono">Cargando...</td></tr>`;
const { data, error } = await supabase
.from("formulas_medicas")
.select("*")
.eq("paciente_cedula", cedula)
.order("created_at", { ascending: false });
if (error){
console.error(error);
tbody.innerHTML = `<tr><td colspan="4">Error cargando fórmulas</td></tr>`;
return;
}
// ✅ Buscar nombre del profesional desde tabla "profesionales" usando el correo
const emails = [...new Set((data || []).map(f => f.profesional_email).filter(Boolean))];
const profMap = {};
if (emails.length){
const { data: profs, error: errProf } = await supabase
.from("profesionales")
.select("correo,nombre")
.in("correo", emails);
if (errProf){
console.warn("No se pudo cargar profesionales:", errProf);
} else {
(profs || []).forEach(p => { if (p && p.correo) profMap[p.correo] = p.nombre; });
}
}
if (!data.length){
tbody.innerHTML = `<tr><td colspan="4" class="mono">No hay fórmulas registradas</td></tr>`;
return;
}
tbody.innerHTML = "";
data.forEach(f => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${f.fecha_hora || ""}</td>
<td>${f.diagnostico || "—"}</td>
<td>${escapeHtml(profMap[f.profesional_email] || f.profesional_email || "")}</td>
<td>
<button class="btn primary" onclick="verFormula('${f.id}')">Ver</button>
</td>
`;
tbody.appendChild(tr);
});
}
async function verFormula(id){
const { data, error } = await supabase
.from("formulas_medicas")
.select("*")
.eq("id", id)
.single();
if (error){
alert("Error cargando fórmula");
return;
}
// ✅ Renderizar el área de impresión dentro del modal
const modalContainer = $("modalPrintContainer");
modalContainer.innerHTML = $("printArea").outerHTML;
// 🔧 FORZAR VISIBILIDAD (printArea viene con display:none)
const pa = modalContainer.querySelector("#printArea");
if (pa){
pa.style.display = "block";
}
// ✅ IMPORTANTE: siempre escribir dentro del printArea del MODAL (no en el hidden del documento)
const $m = (sel) => pa ? pa.querySelector(sel) : null;
const elLogo = $m("#pLogo");
if (elLogo) elLogo.src = LOGO_URL;
const elFechaHora = $m("#pFechaHora");
if (elFechaHora) elFechaHora.textContent = data.fecha_hora || "";
const elPaciente = $m("#pPaciente");
if (elPaciente) elPaciente.textContent = data.paciente_nombre || "";
const elCedula = $m("#pCedula");
if (elCedula) elCedula.textContent = data.paciente_cedula || "";