-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlaboratorio.html
More file actions
841 lines (697 loc) · 22.1 KB
/
laboratorio.html
File metadata and controls
841 lines (697 loc) · 22.1 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
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<title>Módulo Laboratorio</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
:root{
--bg:#f4f7fb;
--card:#ffffff;
--border:#d6e3f3;
--label:#475569;
--title:#1f4e72;
--btn:#009688;
--btn2:#64748b;
--radius:14px;
--shadow:0 10px 30px rgba(16,24,40,.08);
--font: Inter, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
}
*{ box-sizing:border-box; }
body{
margin:0;
padding:24px;
font-family:var(--font);
background:var(--bg);
color:#0f172a;
}
h1{
margin:0 0 16px;
color:var(--title);
font-size:28px;
font-weight:900;
text-align:center;
}
.card{
max-width:900px;
margin:auto;
background:var(--card);
border:1px solid var(--border);
border-radius:var(--radius);
box-shadow:var(--shadow);
padding:22px;
margin-bottom:24px;
}
.grid{
display:grid;
gap:16px;
}
.g-2{ grid-template-columns:1fr 1fr; }
.g-3{ grid-template-columns:repeat(3,1fr); }
@media(max-width:800px){
.g-2,.g-3{ grid-template-columns:1fr; }
}
label{
font-size:13px;
font-weight:600;
color:var(--label);
display:block;
margin-bottom:6px;
}
input, select{
width:100%;
padding:12px;
border-radius:12px;
border:1.5px solid var(--border);
font-size:15px;
outline:none;
}
input:focus, select:focus{
border-color:#94a3b8;
}
canvas{
width:100%;
height:140px;
border:1.5px dashed var(--border);
border-radius:12px;
background:#fff;
cursor:crosshair;
}
.firma-box{
border:1px solid var(--border);
border-radius:12px;
padding:12px;
background:#f8fafc;
margin-top:16px;
}
.firma-actions{
display:flex;
justify-content:flex-end;
gap:10px;
margin-top:8px;
}
button{
border:none;
border-radius:12px;
padding:10px 14px;
font-weight:700;
cursor:pointer;
font-family:var(--font);
}
.btn-main{ background:var(--btn); color:#fff; }
.btn-clear{ background:var(--btn2); color:#fff; }
.btn-danger{
background:#ef4444;
color:#fff;
}
.btn-ghost{
background:#e2e8f0;
color:#0f172a;
}
.footer-actions{
display:flex;
gap:12px;
margin-top:20px;
align-items:center;
justify-content:flex-end;
}
table{
width:100%;
border-collapse:collapse;
margin-top:12px;
}
th,td{
padding:10px;
border-bottom:1px solid var(--border);
font-size:13px;
text-align:left;
vertical-align:top;
}
th{
background:#f4f7fb;
}
.mini-btn{
padding:6px 10px;
border-radius:10px;
font-size:12px;
font-weight:800;
}
.row-actions{
display:flex;
gap:8px;
flex-wrap:wrap;
}
.hint{
font-size:12px;
color:#64748b;
margin-top:6px;
}
.locked{
opacity:.85;
cursor:not-allowed !important;
}
</style>
</head>
<body>
<h1>Laboratorio</h1>
<!-- ================= FORMULARIO ================= -->
<div class="card">
<form id="formLaboratorio">
<!-- FECHAS + ESTADO -->
<div class="grid g-3">
<div>
<label>Fecha de envío</label>
<input type="date" id="fecha_envio" required>
</div>
<div>
<label>Fecha de entrega</label>
<input type="date" id="fecha_entrega">
</div>
<div>
<label>Estado</label>
<select id="estado" required>
<option>Pendiente de enviar</option>
<option>Enviado</option>
<option>En laboratorio</option>
<option>Entregado</option>
</select>
</div>
</div>
<!-- TRABAJO + COSTO -->
<div class="grid g-2" style="margin-top:16px">
<div>
<label>Nombre del trabajo</label>
<input id="nombre_trabajo" required>
</div>
<div>
<label>Costo (COP)</label>
<input id="costo" type="number" min="0" required>
</div>
</div>
<!-- PROVEEDOR + TEL -->
<div class="grid g-2" style="margin-top:16px">
<div>
<label>Proveedor</label>
<select id="proveedor" required></select>
</div>
<div>
<label>Teléfono proveedor</label>
<input id="telefono_proveedor" readonly>
</div>
</div>
<!-- PACIENTE -->
<div class="grid g-2" style="margin-top:16px">
<div>
<label>Nombre del paciente</label>
<input id="nombre_paciente" required>
</div>
<div>
<label>Cédula del paciente</label>
<input id="cedula_paciente" required>
</div>
</div>
<!-- FIRMA RECOGE -->
<div class="firma-box">
<label>Firma de quien recoge</label>
<canvas id="firmaRecoge"></canvas>
<input id="nombre_recoge" placeholder="Nombre de quien recoge">
<div class="firma-actions">
<button type="button" class="btn-clear" id="clearRecoge">Limpiar</button>
</div>
<div class="hint" id="hintRecoge"></div>
</div>
<!-- FIRMA ENTREGA -->
<div class="firma-box">
<label>Firma de quien recibe la entrega</label>
<canvas id="firmaEntrega"></canvas>
<input id="nombre_entrega" placeholder="Nombre de quien recibe la entrega">
<div class="firma-actions">
<button type="button" class="btn-clear" id="clearEntrega">Limpiar</button>
</div>
<div class="hint" id="hintEntrega"></div>
</div>
<!-- ACCIONES FORM -->
<div class="footer-actions">
<button type="button" class="btn-ghost" id="btnCancelarEdicion" style="display:none">Cancelar edición</button>
<button class="btn-main" type="submit" id="btnGuardar">Guardar</button>
</div>
</form>
</div>
<!-- ================= LISTADO ================= -->
<div class="card">
<h2 style="margin:0 0 12px">Registros</h2>
<div class="grid g-3">
<select id="fEstado">
<option value="">Todos los estados</option>
<option>Pendiente de enviar</option>
<option>Enviado</option>
<option>En laboratorio</option>
<option>Entregado</option>
</select>
<input id="fPaciente" placeholder="Paciente">
<input id="fCedula" placeholder="Cédula">
<select id="fProveedor"></select>
</div>
<table>
<thead>
<tr>
<th>Fecha</th>
<th>Paciente</th>
<th>Cédula</th>
<th>Proveedor</th>
<th>Estado</th>
<th>Costo</th>
<th>Acciones</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
<script type="module">
import { createClient } from "https://cdn.jsdelivr.net/npm/@supabase/supabase-js/+esm";
const supabase = createClient(
"https://dmcfrmpqlkrqbpjhrfyo.supabase.co",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRtY2ZybXBxbGtycWJwamhyZnlvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjI5MzU0MDIsImV4cCI6MjA3ODUxMTQwMn0.YY_6t_lCTs5mK-a_eEdBFa6l9_NBM3B4YDtWOXayCBE"
// si quieres usar otra key: "TU_ANON_KEY"
);
// ============== UTIL ==============
const $ = (id) => document.getElementById(id);
// =========================================
// LEER CÉDULA DESDE LA URL (?cedula=)
// EJ: laboratorio.html?cedula=1029999017
// =========================================
function getQueryParam(param){
const params = new URLSearchParams(window.location.search);
return params.get(param);
}
const cedulaFromUrl = getQueryParam("cedula");
if (cedulaFromUrl) {
$("cedula_paciente").value = cedulaFromUrl;
// opcional: bloquear edición de la cédula
$("cedula_paciente").readOnly = true;
// buscar automáticamente el paciente
setTimeout(() => {
buscarPacientePorCedula(cedulaFromUrl);
}, 300);
}
// aplicar filtro automático en registros
$("fCedula").value = cedulaFromUrl;
// esperar a que carguen los registros y filtrar
setTimeout(() => {
cargarRegistros();
}, 500);
// =========================================
// AUTOCOMPLETAR PACIENTE DESDE HISTORIAS CLINICAS
// TABLA: "HISTORIAS CLINICAS"
// CÉDULA: "Numero de Identificacion"
// NOMBRE: "Nombre y apellido"
// =========================================
let cedulaTimeout = null;
$("cedula_paciente").addEventListener("input", () => {
clearTimeout(cedulaTimeout);
const cedula = $("cedula_paciente").value.trim();
// limpiar nombre mientras escribe
$("nombre_paciente").value = "";
if (cedula.length < 5) return;
cedulaTimeout = setTimeout(() => {
buscarPacientePorCedula(cedula);
}, 400);
});
async function buscarPacientePorCedula(cedula) {
const { data, error } = await supabase
.from("HISTORIAS CLINICAS")
.select(`"Nombre y apellido"`)
.eq(`"Numero de Identificacion"`, cedula)
.maybeSingle(); // mejor que single() para que no reviente si no encuentra
if (error) {
console.error("Error buscando historia clínica:", error);
return;
}
if (!data) {
// No encontró → deja vacío
return;
}
// ✅ Autocompletar nombre
$("nombre_paciente").value = data["Nombre y apellido"] || "";
}
// Estado de edición
let editId = null;
let editRowSnapshot = null; // guardamos el registro original para no sobreescribir firmas
// Fecha por defecto
$("fecha_envio").value = new Date().toISOString().split("T")[0];
// =========================================
// CANVAS: firma con bloqueo real + resize
// =========================================
function initFirma(canvas){
const ctx = canvas.getContext("2d");
let habilitado = true;
let drawing = false;
// sincronizar tamaño real para evitar desfase
function resize(){
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
}
resize();
window.addEventListener("resize", resize);
function getPos(e){
const rect = canvas.getBoundingClientRect();
return {
x: (e.touches ? e.touches[0].clientX : e.clientX) - rect.left,
y: (e.touches ? e.touches[0].clientY : e.clientY) - rect.top
};
}
function start(e){
if(!habilitado) return;
drawing = true;
const p = getPos(e);
ctx.beginPath();
ctx.moveTo(p.x, p.y);
e.preventDefault();
}
function move(e){
if(!drawing || !habilitado) return;
const p = getPos(e);
ctx.lineTo(p.x, p.y);
ctx.strokeStyle = "#0f172a";
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.stroke();
e.preventDefault();
}
function end(){
drawing = false;
}
canvas.addEventListener("mousedown", start);
canvas.addEventListener("mousemove", move);
canvas.addEventListener("mouseup", end);
canvas.addEventListener("mouseleave", end);
canvas.addEventListener("touchstart", start, {passive:false});
canvas.addEventListener("touchmove", move, {passive:false});
canvas.addEventListener("touchend", end);
return {
clear(){
ctx.clearRect(0,0,canvas.width,canvas.height);
},
lock(){
habilitado = false;
canvas.classList.add("locked");
canvas.style.cursor = "not-allowed";
},
unlock(){
habilitado = true;
canvas.classList.remove("locked");
canvas.style.cursor = "crosshair";
},
drawBase64(base64){
if(!base64) return;
const img = new Image();
img.onload = () => {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
img.src = base64;
},
toBase64(){
return canvas.toDataURL("image/png");
},
isBlank(){
// Compara con un canvas vacío del mismo tamaño
const tmp = document.createElement("canvas");
tmp.width = canvas.width;
tmp.height = canvas.height;
return tmp.toDataURL("image/png") === canvas.toDataURL("image/png");
}
};
}
const firmaRecogeCtrl = initFirma($("firmaRecoge"));
const firmaEntregaCtrl = initFirma($("firmaEntrega"));
$("clearRecoge").onclick = () => firmaRecogeCtrl.clear();
$("clearEntrega").onclick = () => firmaEntregaCtrl.clear();
// =========================================
// PROVEEDORES: dropdown + teléfono + filtro
// =========================================
async function cargarProveedores(){
const { data, error } = await supabase
.from("proveedores")
.select("id,nombre,telefono,activo")
.eq("activo", true)
.order("nombre");
if(error){
console.error("Error proveedores:", error);
alert("Error cargando proveedores. Revisa consola.");
return;
}
$("proveedor").innerHTML = "<option value=''>Seleccione...</option>";
$("fProveedor").innerHTML = "<option value=''>Todos los proveedores</option>";
data.forEach(p=>{
const o = document.createElement("option");
o.value = p.id;
o.textContent = p.nombre;
o.dataset.tel = p.telefono || "";
$("proveedor").appendChild(o);
const of = o.cloneNode(true);
$("fProveedor").appendChild(of);
});
$("proveedor").onchange = () => {
const opt = $("proveedor").selectedOptions[0];
$("telefono_proveedor").value = opt?.dataset.tel || "";
};
}
// =========================================
// LISTADO: cargar registros + filtros
// =========================================
async function cargarRegistros(){
let q = supabase
.from("laboratorios")
.select("id,fecha_envio,nombre_paciente,cedula_paciente,proveedor,estado,costo,proveedor_id")
.order("created_at", {ascending:false});
if($("fEstado").value) q = q.eq("estado", $("fEstado").value);
if($("fPaciente").value) q = q.ilike("nombre_paciente", "%"+$("fPaciente").value+"%");
if($("fCedula").value) q = q.ilike("cedula_paciente", "%"+$("fCedula").value+"%");
if($("fProveedor").value) q = q.eq("proveedor_id", $("fProveedor").value);
const { data, error } = await q;
if(error){
console.error("Error registros:", error);
alert("Error cargando registros. Revisa consola.");
return;
}
$("tbody").innerHTML = "";
data.forEach(r=>{
$("tbody").innerHTML += `
<tr>
<td>${r.fecha_envio || ""}</td>
<td>${r.nombre_paciente || ""}</td>
<td>${r.cedula_paciente || ""}</td>
<td>${r.proveedor || ""}</td>
<td>${r.estado || ""}</td>
<td>$ ${Number(r.costo || 0).toLocaleString("es-CO")}</td>
<td>
<div class="row-actions">
<button class="mini-btn btn-ghost" onclick="editar('${r.id}')">✏️ Editar</button>
<button class="mini-btn btn-danger" onclick="eliminar('${r.id}')">🗑️ Eliminar</button>
</div>
</td>
</tr>
`;
});
}
// =========================================
// MODO EDICIÓN: cargar registro completo
// =========================================
function resetLocksYHints(){
$("hintRecoge").textContent = "";
$("hintEntrega").textContent = "";
// habilitar firma por defecto
firmaRecogeCtrl.unlock();
firmaEntregaCtrl.unlock();
// habilitar botones limpiar
$("clearRecoge").disabled = false;
$("clearEntrega").disabled = false;
// limpiar data flags
$("firmaRecoge").dataset.locked = "";
$("firmaEntrega").dataset.locked = "";
}
function entrarModoEdicion(){
$("btnGuardar").textContent = "Actualizar";
$("btnCancelarEdicion").style.display = "inline-flex";
}
function salirModoEdicion(){
editId = null;
editRowSnapshot = null;
$("btnGuardar").textContent = "Guardar";
$("btnCancelarEdicion").style.display = "none";
// reset form
$("formLaboratorio").reset();
$("fecha_envio").value = new Date().toISOString().split("T")[0];
$("telefono_proveedor").value = "";
// limpiar canvas
firmaRecogeCtrl.clear();
firmaEntregaCtrl.clear();
// habilitar firmas
resetLocksYHints();
}
$("btnCancelarEdicion").onclick = () => {
salirModoEdicion();
};
window.editar = async (id) => {
const { data, error } = await supabase
.from("laboratorios")
.select("*")
.eq("id", id)
.single();
if(error){
console.error("Error editar:", error);
alert("No se pudo cargar el registro. Revisa consola.");
return;
}
editId = id;
editRowSnapshot = data; // guardamos original para no sobreescribir firmas
entrarModoEdicion();
// cargar campos
$("fecha_envio").value = data.fecha_envio || new Date().toISOString().split("T")[0];
$("fecha_entrega").value = data.fecha_entrega || "";
$("estado").value = data.estado || "Pendiente de enviar";
$("nombre_trabajo").value = data.nombre_trabajo || "";
$("nombre_paciente").value = data.nombre_paciente || "";
$("cedula_paciente").value = data.cedula_paciente || "";
$("costo").value = data.costo || 0;
$("nombre_recoge").value = data.nombre_recoge || "";
$("nombre_entrega").value = data.nombre_entrega || "";
// proveedor select + teléfono
$("proveedor").value = data.proveedor_id || "";
const opt = $("proveedor").selectedOptions[0];
$("telefono_proveedor").value = opt?.dataset.tel || "";
// limpiar canvas primero
firmaRecogeCtrl.clear();
firmaEntregaCtrl.clear();
// reset locks/hints
resetLocksYHints();
// ✅ cargar firmas guardadas y bloquear SI YA EXISTEN (inmutables)
if(data.firma_recoge){
firmaRecogeCtrl.drawBase64(data.firma_recoge);
firmaRecogeCtrl.lock();
$("clearRecoge").disabled = true;
$("firmaRecoge").dataset.locked = "true";
$("hintRecoge").textContent = "Firma ya guardada. No se puede modificar.";
}
if(data.firma_entrega){
firmaEntregaCtrl.drawBase64(data.firma_entrega);
firmaEntregaCtrl.lock();
$("clearEntrega").disabled = true;
$("firmaEntrega").dataset.locked = "true";
$("hintEntrega").textContent = "Firma ya guardada. No se puede modificar.";
}
};
// =========================================
// ELIMINAR
// =========================================
window.eliminar = async (id) => {
if(!confirm("¿Eliminar este registro? Esta acción no se puede deshacer.")) return;
const { error } = await supabase
.from("laboratorios")
.delete()
.eq("id", id);
if(error){
console.error("Error eliminar:", error);
alert("No se pudo eliminar. Revisa consola.");
return;
}
// si estabas editando el mismo, salimos
if(editId === id) salirModoEdicion();
await cargarRegistros();
};
// =========================================
// SUBMIT: INSERT / UPDATE sin sobreescribir firmas
// =========================================
$("formLaboratorio").onsubmit = async (e) => {
e.preventDefault();
// validar proveedor
if(!$("proveedor").value){
alert("Debe seleccionar un proveedor.");
return;
}
const proveedorSelect = $("proveedor");
const proveedorNombre = proveedorSelect.selectedOptions[0]?.textContent || "";
// payload base (sin firmas todavía)
const payload = {
fecha_envio: $("fecha_envio").value,
fecha_entrega: $("fecha_entrega").value || null,
estado: $("estado").value,
nombre_trabajo: $("nombre_trabajo").value,
proveedor_id: proveedorSelect.value,
proveedor: proveedorNombre,
nombre_paciente: $("nombre_paciente").value,
cedula_paciente: $("cedula_paciente").value,
costo: Number($("costo").value),
nombre_recoge: $("nombre_recoge").value,
nombre_entrega: $("nombre_entrega").value
};
// firmas actuales (lo que está en el canvas)
const firmaRecogeActual = firmaRecogeCtrl.isBlank() ? null : firmaRecogeCtrl.toBase64();
const firmaEntregaActual = firmaEntregaCtrl.isBlank() ? null : firmaEntregaCtrl.toBase64();
if(editId){
// ===== UPDATE =====
// IMPORTANTÍSIMO: NO sobreescribir firmas si ya existen en el registro original
// Solo se permite guardar firma si antes NO existía.
const firmaRecogeExistia = !!editRowSnapshot?.firma_recoge;
const firmaEntregaExistia = !!editRowSnapshot?.firma_entrega;
if(!firmaRecogeExistia && firmaRecogeActual){
payload.firma_recoge = firmaRecogeActual;
}
if(!firmaEntregaExistia && firmaEntregaActual){
payload.firma_entrega = firmaEntregaActual;
}
const { error } = await supabase
.from("laboratorios")
.update(payload)
.eq("id", editId);
if(error){
console.error("Error update:", error);
alert(error.message || "Error actualizando.");
return;
}
// refrescar
await cargarRegistros();
// mantenerte en modo edición pero recargando registro para bloquear si ya guardó firmas
await window.editar(editId);
alert("Registro actualizado correctamente.");
return;
}
// ===== INSERT =====
// En creación, sí se guardan firmas si existen (puede que entrega esté vacía al inicio)
payload.firma_recoge = firmaRecogeActual;
payload.firma_entrega = firmaEntregaActual;
const { error } = await supabase
.from("laboratorios")
.insert([payload]);
if(error){
console.error("Error insert:", error);
alert(error.message || "Error guardando.");
return;
}
// limpiar form
$("formLaboratorio").reset();
$("fecha_envio").value = new Date().toISOString().split("T")[0];
$("telefono_proveedor").value = "";
firmaRecogeCtrl.clear();
firmaEntregaCtrl.clear();
resetLocksYHints();
await cargarRegistros();
alert("Registro guardado correctamente.");
};
// =========================================
// FILTROS
// =========================================
["fEstado","fPaciente","fCedula","fProveedor"].forEach(id=>{
$(id).addEventListener("input", cargarRegistros);
$(id).addEventListener("change", cargarRegistros);
});
// =========================================
// INIT
// =========================================
await cargarProveedores();
await cargarRegistros();
</script>
</body>
</html>