-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrips.html
More file actions
919 lines (778 loc) · 30.8 KB
/
rips.html
File metadata and controls
919 lines (778 loc) · 30.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
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>RIPS por Evolución</title>
<!-- Supabase JS v2 (UMD) -->
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2.45.4/dist/umd/supabase.min.js"></script>
<style>
:root{
--bg:#f3f5f7; --card:#fff; --text:#1f2a37; --muted:#6b7280; --line:#e5e7eb;
--brand:#1f6aa5; --brand2:#114a75; --ok:#16a34a; --bad:#dc2626; --warn:#f59e0b;
--radius:12px; --shadow:0 10px 30px rgba(0,0,0,.06);
}
*{box-sizing:border-box}
body{margin:0;padding:20px;background:var(--bg);font-family:Arial;color:var(--text);}
.container{max-width:1400px;margin:0 auto;background:var(--card);border-radius:var(--radius);padding:18px;box-shadow:var(--shadow);border:1px solid var(--line);}
.topbar{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:12px;}
h1{margin:0;font-size:18px}
.meta{display:flex;gap:10px;align-items:center;flex-wrap:wrap;color:var(--muted);font-size:13px;font-weight:700;}
.btn{padding:9px 12px;border:1px solid var(--line);border-radius:10px;cursor:pointer;font-weight:800;background:#fff;}
.btn:hover{filter:brightness(.98)}
.btn-primary{background:var(--brand);color:#fff;border-color:var(--brand);}
.btn-primary:hover{background:var(--brand2);border-color:var(--brand2);}
.btn-export{background:var(--ok);color:#fff;border-color:var(--ok);}
.btn-export:hover{filter:brightness(.95)}
.btn:disabled{opacity:.6;cursor:not-allowed}
.table-wrap{overflow:auto; max-height:72vh; border:1px solid var(--line); border-radius:12px;}
table{width:100%;border-collapse:collapse; min-width:1250px;}
th,td{padding:10px;border-bottom:1px solid var(--line);font-size:13px;vertical-align:middle;}
th{background:#fafafa;text-align:left;font-size:12px;color:var(--muted);position:sticky;top:0; z-index:2;}
.pill{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;font-size:12px;font-weight:900;border:1px solid var(--line);background:#fff;white-space:nowrap;}
.pill.warn{color:var(--warn);border-color:rgba(245,158,11,.25)}
.pill.ok{color:var(--ok);border-color:rgba(22,163,74,.25)}
.pill.bad{color:var(--bad);border-color:rgba(220,38,38,.25)}
.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono",monospace;font-size:12px}
.row-actions{display:flex;gap:8px;flex-wrap:wrap}
.empty{color:var(--muted);text-align:center;padding:18px}
.filters{display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;margin:10px 0 14px;}
.ctrl{display:flex;flex-direction:column;gap:6px;min-width:220px;}
.ctrl label{font-size:12px;color:var(--muted);font-weight:800;}
input, select{border:1px solid var(--line);border-radius:10px;padding:10px 12px;outline:none;background:#fff;font-size:14px;}
#toast{
position:fixed;right:16px;bottom:16px;padding:10px 12px;border-radius:12px;border:1px solid var(--line);
background:#fff;box-shadow:var(--shadow);font-weight:900;opacity:0;transform:translateY(8px);
transition:opacity .15s ease,transform .15s ease;pointer-events:none;max-width:520px;white-space:pre-wrap;z-index:99;
}
#toast.show{opacity:1;transform:translateY(0)}
#toast[data-type="ok"]{border-color:#b7e4c7}
#toast[data-type="err"]{border-color:#f2c6c6}
#toast[data-type="warn"]{border-color:#ffe7b3}
</style>
</head>
<body>
<div class="container">
<div class="topbar">
<h1>RIPS por Evolución</h1>
<div class="meta">
<span id="count">—</span>
<button class="btn" id="btn-reload" type="button">🔄 Recargar</button>
</div>
</div>
<div class="filters">
<div class="ctrl">
<label for="f-text">Buscar (paciente / doc / factura / cufe / id evolución)</label>
<input id="f-text" type="text" placeholder="Ej: 1022, 34ab..., FEV-001, CUFE..." />
</div>
<div class="ctrl" style="min-width:180px;">
<label for="f-fact">Factura</label>
<select id="f-fact">
<option value="all">Todas</option>
<option value="with">Con factura</option>
<option value="without">Sin factura</option>
</select>
</div>
<div class="ctrl" style="min-width:180px;">
<label for="f-cufe">CUFE</label>
<select id="f-cufe">
<option value="all">Todos</option>
<option value="with">Con CUFE</option>
<option value="without">Sin CUFE</option>
</select>
</div>
<div class="ctrl" style="min-width:200px;">
<label for="f-rips">RIPS Generado</label>
<select id="f-rips">
<option value="all">Todos</option>
<option value="with">Con RIPS (en tabla rips_generados)</option>
<option value="without">Sin RIPS</option>
</select>
</div>
<div class="ctrl" style="min-width:200px;">
<label for="f-procs">Procedimientos</label>
<select id="f-procs">
<option value="all">Todos</option>
<option value="with">Con procedimientos</option>
<option value="without">Sin procedimientos</option>
</select>
</div>
<div class="ctrl" style="min-width:150px;">
<label> </label>
<button class="btn" id="btn-clear" type="button">🧹 Limpiar</button>
</div>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th style="width:160px;">Evolución</th>
<th style="width:140px;">Fecha/Hora</th>
<th>Paciente</th>
<th style="width:160px;">Profesional</th>
<th style="width:110px;"># Procs</th>
<th style="width:160px;">Factura</th>
<th style="width:200px;">CUFE</th>
<th style="width:170px;">Estado</th>
<th style="width:340px;">Acción</th>
</tr>
</thead>
<tbody id="tbody">
<tr><td colspan="9" class="empty">Cargando...</td></tr>
</tbody>
</table>
</div>
</div>
<div id="toast"></div>
<script>
// =======================
// CONFIG
// =======================
const SUPABASE_URL = "https://dmcfrmpqlkrqbpjhrfyo.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRtY2ZybXBxbGtycWJwamhyZnlvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjI5MzU0MDIsImV4cCI6MjA3ODUxMTQwMn0.YY_6t_lCTs5mK-a_eEdBFa6l9_NBM3B4YDtWOXayCBE";
// Webhook n8n
const WEBHOOK_URL = "https://ftth-n8n2.pzveh5.easypanel.host/webhook/bb200fb9-3acf-4995-9c42-af837e328432";
const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
const $ = (id)=>document.getElementById(id);
function toast(msg, type="ok"){
const el = $("toast");
el.textContent = msg;
el.dataset.type = type;
el.classList.add("show");
clearTimeout(window.__toastT);
window.__toastT = setTimeout(()=> el.classList.remove("show"), 2600);
}
function esc(s){
return String(s ?? "")
.replaceAll("&","&")
.replaceAll("<","<")
.replaceAll(">",">")
.replaceAll('"',""")
.replaceAll("'","'");
}
function ymd(d){
const s = String(d || "");
return s ? s.slice(0,10) : "";
}
function hhmm(t){
const s = String(t || "");
return s ? s.slice(0,5) : "";
}
function trimStr(v){ return String(v ?? "").trim(); }
function asNum(v){
const n = Number(v);
return Number.isFinite(n) ? n : null;
}
function firstNonEmpty(...vals){
for (const v of vals){
const s = String(v ?? "").trim();
if (s) return s;
}
return "";
}
// Estado en memoria
let __rows = [];
// =======================
// CARGAR EVOLUCIONES + RELACIONES
// =======================
async function cargarEvoluciones(){
const tbody = $("tbody");
tbody.innerHTML = `<tr><td colspan="9" class="empty">Cargando...</td></tr>`;
$("count").textContent = "—";
try{
// 1) evoluciones recientes
const evoRes = await sb
.from("EVOLUCIONES")
.select("*")
.order("created_at", { ascending:false })
.limit(500);
if (evoRes.error) throw evoRes.error;
const evos = evoRes.data || [];
if (!evos.length){
__rows = [];
render();
return;
}
// 2) ids de evolución
const evoIds = evos.map(e => String(e["id-evolucion"] || "")).filter(Boolean);
// 3) procedimientos (conteo por evolución)
let procCounts = new Map();
if (evoIds.length){
// Traemos id_evolucion (y contamos en memoria)
const procRes = await sb
.from("evolucion_procedimientos")
.select("id_evolucion")
.in("id_evolucion", evoIds)
.limit(10000);
if (procRes.error) throw procRes.error;
(procRes.data || []).forEach(p => {
const k = String(p.id_evolucion || "");
if (!k) return;
procCounts.set(k, (procCounts.get(k) || 0) + 1);
});
}
// 4) cargar facturas relacionadas por evolucion_id
const facByEvoRes = evoIds.length
? await sb
.from("facturas")
.select("id, numero_factura, cufe, fechafacturaelectronica, evolucion_id, paciente_cedula, paciente_nombre, fecha, valor_total, tipoNota, numNota")
.in("evolucion_id", evoIds)
: { data: [], error: null };
if (facByEvoRes.error) throw facByEvoRes.error;
// 5) cargar facturas relacionadas por numero_factura (si EVOLUCIONES.factura trae el número)
const evoFacturaNums = evos
.map(e => String(e.factura || "").trim())
.filter(Boolean);
let facByNumRes = { data: [], error: null };
if (evoFacturaNums.length){
facByNumRes = await sb
.from("facturas")
.select("id, numero_factura, cufe, fechafacturaelectronica, evolucion_id, paciente_cedula, paciente_nombre, fecha, valor_total, tipoNota, numNota")
.in("numero_factura", Array.from(new Set(evoFacturaNums)));
if (facByNumRes.error) throw facByNumRes.error;
}
const allFacturas = [...(facByEvoRes.data || []), ...(facByNumRes.data || [])];
// 6) indexar facturas
const facByEvo = new Map();
const facByNum = new Map();
allFacturas.forEach(f => {
if (f?.evolucion_id) facByEvo.set(String(f.evolucion_id), f);
if (f?.numero_factura) facByNum.set(String(f.numero_factura), f);
});
// 7) cargar pacientes (HISTORIAS CLINICAS)
const cedulas = Array.from(new Set(
evos
.map(e => e.paciente_numdoc)
.filter(v => v !== null && v !== undefined)
.map(v => Number(v))
.filter(v => !Number.isNaN(v))
));
let pacientes = [];
if (cedulas.length){
const pacRes = await sb
.from("HISTORIAS CLINICAS")
.select('"Numero de Identificacion", "Nombre y apellido", "Tipo identificacion", "Fecha de nacimiento", sexo, tipo_paciente, pais_residencia, paciente_ciudad, zonaresidencial, incapacidad, pais_origen')
.in('Numero de Identificacion', cedulas)
.limit(2000);
if (pacRes.error) throw pacRes.error;
pacientes = pacRes.data || [];
}
const pacByDoc = new Map();
pacientes.forEach(p => pacByDoc.set(String(p["Numero de Identificacion"]), p));
// 8) diagnosticos por evolución
let diagRows = [];
if (evoIds.length){
const diagRes = await sb
.from("historia_diagnosticos")
.select("id_evolucion, codigo_cie10, tipo")
.in("id_evolucion", evoIds)
.limit(5000);
if (diagRes.error) throw diagRes.error;
diagRows = diagRes.data || [];
}
const diagByEvo = new Map();
diagRows.forEach(d => {
const k = String(d.id_evolucion || "");
if (!k) return;
if (!diagByEvo.has(k)) diagByEvo.set(k, []);
diagByEvo.get(k).push(d);
});
// 9) rips_generados (solo aplica si hay factura)
const facturaIds = Array.from(new Set(allFacturas.map(f => String(f.id)).filter(Boolean)));
let ripsSet = new Set();
if (facturaIds.length){
const ripsRes = await sb
.from("rips_generados")
.select("factura_id")
.in("factura_id", facturaIds);
if (ripsRes.error) throw ripsRes.error;
ripsSet = new Set((ripsRes.data || []).map(r => String(r.factura_id)));
}
// 10) construir filas
__rows = evos.map(e => {
const evoId = String(e["id-evolucion"] || "");
const doc = String(e.paciente_numdoc ?? "");
const p = pacByDoc.get(doc) || null;
const f1 = facByEvo.get(evoId) || null;
const f2 = (e.factura ? facByNum.get(String(e.factura).trim()) : null) || null;
const fac = f1 || f2;
const hasFactura = !!fac;
const hasCufe = !!(fac && String(fac.cufe || "").trim());
const hasRips = !!(fac && ripsSet.has(String(fac.id)));
const nombre = p?.["Nombre y apellido"] || fac?.paciente_nombre || "";
const numFactura = fac?.numero_factura || (String(e.factura || "").trim() || "");
const diags = diagByEvo.get(evoId) || [];
const diagPrincipal = (diags.find(d => String(d.tipo||"").toLowerCase() === "principal") || diags[0] || null)?.codigo_cie10 || null;
const procCount = procCounts.get(evoId) || 0;
return {
evo: e,
evoId,
doc,
paciente: p,
paciente_nombre: nombre,
profesional: e.evo_profesional || "",
fecha_hora: `${ymd(e.evo_fecha || e.created_at)} ${hhmm(e.evo_hora)}`.trim(),
factura: fac,
numFactura,
cufe: fac?.cufe || "",
hasFactura,
hasCufe,
hasRips,
diagPrincipal,
procCount,
};
});
render();
} catch (err){
console.error(err);
$("tbody").innerHTML = `<tr><td colspan="9" class="empty">❌ Error cargando datos: ${esc(err?.message || err)}</td></tr>`;
toast("❌ Error cargando evoluciones (mira consola)", "err");
}
}
// =======================
// RENDER + FILTROS
// =======================
function applyFilters(rows){
const q = String($("f-text").value || "").trim().toLowerCase();
const fact = $("f-fact").value;
const cufe = $("f-cufe").value;
const rips = $("f-rips").value;
const procs = $("f-procs").value;
return rows.filter(r => {
if (fact === "with" && !r.hasFactura) return false;
if (fact === "without" && r.hasFactura) return false;
if (cufe === "with" && !r.hasCufe) return false;
if (cufe === "without" && r.hasCufe) return false;
if (rips === "with" && !r.hasRips) return false;
if (rips === "without" && r.hasRips) return false;
if (procs === "with" && !(r.procCount > 0)) return false;
if (procs === "without" && (r.procCount > 0)) return false;
if (q){
const hay = [
r.evoId,
r.doc,
r.paciente_nombre,
r.numFactura,
r.cufe,
r.profesional,
].join(" ").toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
});
}
function render(){
const tbody = $("tbody");
const rows = applyFilters(__rows);
$("count").textContent = `Evoluciones: ${rows.length} / ${__rows.length}`;
if (!rows.length){
tbody.innerHTML = `<tr><td colspan="9" class="empty">No hay resultados con los filtros actuales.</td></tr>`;
return;
}
tbody.innerHTML = "";
rows.forEach(r => {
const tr = document.createElement("tr");
const pFactura = r.hasFactura
? `<span class="pill ok">Con factura</span>`
: `<span class="pill warn">Sin factura</span>`;
const pCufe = r.hasFactura
? (r.hasCufe ? `<span class="pill ok">CUFE</span>` : `<span class="pill warn">Sin CUFE</span>`)
: `<span class="pill bad">No aplica</span>`;
const pRips = r.hasFactura
? (r.hasRips ? `<span class="pill ok">RIPS generado</span>` : `<span class="pill warn">RIPS pendiente</span>`)
: `<span class="pill warn">Sin factura</span>`;
const pProcs = (r.procCount > 0)
? `<span class="pill ok">Procs OK</span>`
: `<span class="pill bad">Sin procs</span>`;
tr.innerHTML = `
<td class="mono">${esc(r.evoId)}</td>
<td class="mono">${esc(r.fecha_hora)}</td>
<td>
<div style="font-weight:900;">${esc(r.paciente_nombre || "")}</div>
<div class="mono" style="color:var(--muted);">Doc: ${esc(r.doc || "")}</div>
</td>
<td>${esc(r.profesional || "")}</td>
<td class="mono">${esc(String(r.procCount))}</td>
<td class="mono">${esc(r.numFactura || "—")}</td>
<td class="mono">${esc(String(r.cufe || "").slice(0, 22))}${r.cufe && String(r.cufe).length>22 ? "…" : ""}</td>
<td>
<div style="display:flex; gap:6px; flex-wrap:wrap;">
${pFactura}
${pCufe}
${pRips}
${pProcs}
</div>
</td>
<td>
<div class="row-actions">
<button class="btn btn-primary" type="button" data-gen="${esc(r.evoId)}">Enviar a n8n</button>
<button class="btn btn-export" type="button" data-exp="${esc(r.evoId)}">Exportar JSON</button>
</div>
</td>
`;
tbody.appendChild(tr);
});
tbody.querySelectorAll("[data-gen]").forEach(btn=>{
btn.addEventListener("click", ()=> enviarAN8N(btn.getAttribute("data-gen"), btn));
});
tbody.querySelectorAll("[data-exp]").forEach(btn=>{
btn.addEventListener("click", ()=> exportarJSON(btn.getAttribute("data-exp"), btn));
});
}
// =======================
// ARMAR PAYLOAD (por evolución)
// - Incluye evolución + factura (si existe) + procedimientos (evolucion_procedimientos) + paciente + diagnosticos
// =======================
async function construirPayloadPorEvolucion(evoId){
// 1) emisor activo
const emRes = await sb.from("emisor_dian").select("*").eq("activo", true).limit(1).maybeSingle();
if (emRes.error) throw emRes.error;
// 2) evolución
const evoRes = await sb.from("EVOLUCIONES").select("*").eq("id-evolucion", evoId).maybeSingle();
if (evoRes.error) throw evoRes.error;
if (!evoRes.data) throw new Error("No se encontró la evolución con id: " + evoId);
const evo = evoRes.data;
// 3) factura (por evolucion_id) o por numero_factura
let fac = null;
const fac1 = await sb
.from("facturas")
.select("*")
.eq("evolucion_id", evoId)
.order("created_at", { ascending:false })
.limit(1)
.maybeSingle();
if (fac1.error) throw fac1.error;
fac = fac1.data || null;
if (!fac && evo.factura){
const fac2 = await sb
.from("facturas")
.select("*")
.eq("numero_factura", String(evo.factura).trim())
.order("created_at", { ascending:false })
.limit(1)
.maybeSingle();
if (fac2.error) throw fac2.error;
fac = fac2.data || null;
}
// 4) procedimientos de la evolución (FUENTE PRINCIPAL)
const procRes = await sb
.from("evolucion_procedimientos")
.select("*")
.eq("id_evolucion", evoId)
.order("orden", { ascending:true })
.limit(5000);
if (procRes.error) throw procRes.error;
const procedimientos = procRes.data || [];
// 4.1) detalle de factura
let factura_detalle = [];
if (fac?.id) {
const detRes = await sb
.from("factura_detalle")
.select("*")
.eq("factura_id", fac.id)
.limit(5000);
if (detRes.error) throw detRes.error;
factura_detalle = detRes.data || [];
}
// 5) paciente
const doc = String(evo.paciente_numdoc ?? "");
let paciente = null;
if (doc){
const pacRes = await sb
.from("HISTORIAS CLINICAS")
.select('*')
.eq('Numero de Identificacion', Number(doc))
.maybeSingle();
if (pacRes.error) throw pacRes.error;
paciente = pacRes.data || null;
}
// 6) diagnósticos por evolución
const diagRes = await sb
.from("historia_diagnosticos")
.select("*")
.eq("id_evolucion", evoId)
.limit(5000);
if (diagRes.error) throw diagRes.error;
const diagnosticos = diagRes.data || [];
return {
meta: {
generated_at: new Date().toISOString(),
source: "html_rips_por_evolucion",
webhook: WEBHOOK_URL,
},
emisor: emRes.data || null,
evolucion: evo,
factura: fac,
procedimientos,
factura_detalle,
paciente,
diagnosticos,
};
}
// =======================
// EXPORTAR JSON RIPS
// - Construye servicios desde evolucion_procedimientos
// =======================
function guessConceptoRecaudo(hasFactura){
// Si es RIPS sin factura (RS), normalmente no hay recaudo; dejamos "05" como en ejemplo.
return hasFactura ? "02" : "05";
}
function normalizeMunicipio(v){
return String(v ?? "").trim();
}
// =======================
// CLASIFICAR CONSULTA O PROCEDIMIENTO
// usando tabla procedimientos_precios
// =======================
async function detectarConsultasDesdeBD(procs){
const cupsList = procs
.map(p => trimStr(p.codigo_cups || p.codservicio))
.filter(Boolean);
if(!cupsList.length) return {};
const res = await sb
.from("procedimientos_precios")
.select("codigo_cups, especialidad")
.in("codigo_cups", Array.from(new Set(cupsList)));
if(res.error) throw res.error;
const mapa = {};
(res.data || []).forEach(r=>{
mapa[r.codigo_cups] = r.especialidad;
});
return mapa;
}
async function exportarJSON(evoId, btn){
const oldText = btn?.textContent;
try{
if(btn){ btn.disabled = true; btn.textContent = "Exportando..."; }
const payload = await construirPayloadPorEvolucion(evoId);
const evo = payload.evolucion;
const fac = payload.factura;
const paciente = payload.paciente;
const emisor = payload.emisor;
const diagnosticos = payload.diagnosticos || [];
const procs = payload.procedimientos || [];
const detalleFactura = payload.factura_detalle || [];
// =======================
// OBTENER PROFESIONAL
// =======================
const nombreProfesional = trimStr(evo.evo_profesional);
let profesional = null;
if (nombreProfesional) {
const profRes = await sb
.from("profesionales")
.select("tipo_identificacion, cedula")
.ilike("nombre", nombreProfesional)
.limit(1)
.maybeSingle();
if (profRes.error) throw profRes.error;
profesional = profRes.data || null;
}
if (!profesional) {
throw new Error("No se encontró el profesional en la tabla profesionales: " + nombreProfesional);
}
if (!paciente){
alert("⚠ No se encontró el paciente para esta evolución. (Revisa EVOLUCIONES.paciente_numdoc)");
return;
}
if (!procs.length){
alert("⚠ Esta evolución NO tiene procedimientos en evolucion_procedimientos. No se puede generar RIPS.");
return;
}
// Diagnóstico principal
const diagPrincipal = (diagnosticos.find(d => String(d.tipo||"").toLowerCase() === "principal") || diagnosticos[0] || null)?.codigo_cie10 || null;
// Fecha/hora atención
const fechaAtencion = (evo?.evo_fecha)
? `${String(evo.evo_fecha).slice(0,10)} ${String(evo.evo_hora||"00:00").slice(0,5)}`
: (fac?.fecha ? `${String(fac.fecha).slice(0,10)} 00:00` : `${String(evo.created_at||"").slice(0,10)} 00:00`);
// Si no hay factura: RS
const tipoNota = fac ? (fac.tipoNota || null) : "RS";
const numNota = fac ? (fac.numNota || null) : String(evoId);
// codPrestador: intenta varios campos del emisor
const codPrestador = trimStr(emisor?.codPrestador);
const tipoDocProfesional = trimStr(profesional.tipo_identificacion);
const numDocProfesional = trimStr(profesional.cedula);
const usuario = {
tipoDocumentoIdentificacion: trimStr(paciente["Tipo identificacion"] || paciente.tipo_documento),
numDocumentoIdentificacion: String(paciente["Numero de Identificacion"] ?? paciente.num_documento ?? ""),
tipoUsuario: trimStr(paciente.tipo_paciente),
fechaNacimiento: trimStr(paciente["Fecha de nacimiento"]),
codSexo: trimStr(paciente.sexo),
codPaisResidencia: trimStr(paciente.pais_residencia),
codMunicipioResidencia: normalizeMunicipio(paciente.paciente_ciudad),
codZonaTerritorialResidencia: trimStr(paciente.zonaresidencial),
incapacidad: trimStr(paciente.incapacidad),
codPaisOrigen: trimStr(paciente.pais_origen),
consecutivo: 1,
servicios: {}
};
// Construir listas
const consultas = [];
const procedimientos = [];
// consultar especialidad de cada CUPS
const mapaEspecialidades = await detectarConsultasDesdeBD(procs);
let cCons = 1;
let cProc = 1;
procs.forEach((p) => {
const codigo = trimStr(p.codigo_cups);
if (!codigo) {
throw new Error(`El procedimiento no tiene codigo_cups en evolucion_procedimientos. codservicio=${trimStr(p.codservicio)}`);
}
if (!codigo) return;
const especialidad = mapaEspecialidades[codigo] || "";
const isConsulta = especialidad === "Consulta y valoraciones";
const codServicio = asNum(p.codservicio);
const viaIngreso = trimStr(p.via_ingreso);
const modalidad = trimStr(p.modalidad_atencion);
const grupo = trimStr(p.grupo_servicio);
if (!viaIngreso) {
throw new Error(`El procedimiento ${codigo} no tiene via_ingreso`);
}
if (!modalidad) {
throw new Error(`El procedimiento ${codigo} no tiene modalidad_atencion`);
}
if (!grupo) {
throw new Error(`El procedimiento ${codigo} no tiene grupo_servicio`);
}
if (codServicio === null) {
throw new Error(`El procedimiento ${codigo} no tiene codservicio en la tabla evolucion_procedimientos`);
}
const finalidad = trimStr(p.finalidadtecnologiasalud);
const causa = trimStr(p.causamotivoatencion);
const dxP = trimStr(p.diagnostico_principal) || (diagPrincipal || null);
const tipoDx = trimStr(p.tipo_diagnostico);
const codComplicacion = trimStr(p.codcomplicacion) || null;
const dxRel1 = trimStr(p.diagnosticos_secundario_1) || null;
const dxRel2 = trimStr(p.diagnosticos_secundario_2) || null;
const dxRel3 = trimStr(p.diagnosticos_secundario_3) || null;
const detalleItem = detalleFactura.find(d => String(d.codigo_cups || "").trim() === codigo);
const vr = Number(detalleItem?.valor_total || 0);
if (isConsulta){
consultas.push({
codPrestador,
fechaInicioAtencion: fechaAtencion,
numAutorizacion: null,
codConsulta: codigo,
modalidadGrupoServicioTecSal: modalidad,
grupoServicios: grupo,
codServicio: codServicio,
finalidadTecnologiaSalud: finalidad,
causaMotivoAtencion: causa,
codDiagnosticoPrincipal: dxP,
codDiagnosticoRelacionado1: dxRel1,
codDiagnosticoRelacionado2: dxRel2,
codDiagnosticoRelacionado3: dxRel3,
tipoDiagnosticoPrincipal: tipoDx,
tipoDocumentoIdentificacion: tipoDocProfesional,
numDocumentoIdentificacion: numDocProfesional,
vrServicio: vr,
conceptoRecaudo: trimStr(fac?.conceptorecaudo),
valorPagoModerador: 0,
numFEVPagoModerador: null,
consecutivo: cCons++
});
} else {
procedimientos.push({
codPrestador,
fechaInicioAtencion: fechaAtencion,
idMIPRES: null,
numAutorizacion: null,
codProcedimiento: codigo,
viaIngresoServicioSalud: viaIngreso,
modalidadGrupoServicioTecSal: modalidad,
grupoServicios: grupo,
codServicio: codServicio,
finalidadTecnologiaSalud: finalidad,
tipoDocumentoIdentificacion: tipoDocProfesional,
numDocumentoIdentificacion: numDocProfesional,
codDiagnosticoPrincipal: dxP,
codDiagnosticoRelacionado: dxRel1,
codComplicacion: codComplicacion,
vrServicio: vr,
conceptoRecaudo: trimStr(fac?.conceptorecaudo),
valorPagoModerador: 0,
numFEVPagoModerador: null,
consecutivo: cProc++
});
}
});
if (consultas.length) usuario.servicios.consultas = consultas;
if (procedimientos.length) usuario.servicios.procedimientos = procedimientos;
const rips = {
numDocumentoIdObligado: trimStr(emisor?.nit) || null,
numFactura: fac ? (trimStr(fac.numero_factura) || null) : null,
tipoNota,
numNota,
usuarios: [usuario]
};
const blob = new Blob([JSON.stringify(rips, null, 2)], { type:"application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `RIPS_EVO_${String(evoId).slice(0,16)}${fac?.numero_factura ? "_FAC_"+fac.numero_factura : ""}.json`;
a.click();
URL.revokeObjectURL(url);
toast("✅ JSON exportado", "ok");
} catch(e){
console.error(e);
toast("❌ Error exportando (mira consola)", "err");
alert("Error exportando: " + (e?.message || e));
} finally{
if(btn){ btn.disabled = false; btn.textContent = oldText || "Exportar JSON"; }
}
}
// =======================
// ENVIAR A N8N
// =======================
async function enviarAN8N(evoId, btn){
if (!confirm("¿Enviar esta evolución a n8n para generar/validar el RIPS?")) return;
const oldText = btn?.textContent;
try{
if (btn){ btn.disabled = true; btn.textContent = "Enviando…"; }
toast("Enviando a n8n…", "warn");
const payload = await construirPayloadPorEvolucion(evoId);
const res = await fetch(WEBHOOK_URL, {
method:"POST",
headers:{ "Content-Type":"application/json" },
body: JSON.stringify(payload)
});
if (!res.ok){
const t = await res.text().catch(()=> "");
throw new Error(`Webhook respondió ${res.status}. ${t}`.trim());
}
toast("✅ Enviado a n8n", "ok");
alert("✅ Evolución enviada a n8n.");
await cargarEvoluciones();
} catch(e){
console.error(e);
toast("❌ Error enviando a n8n", "err");
alert("❌ Error enviando a n8n:\n" + (e?.message || e));
} finally{
if (btn){ btn.disabled = false; btn.textContent = oldText || "Enviar a n8n"; }
}
}
// =======================
// UI Events
// =======================
function wireFilters(){
const rer = ()=> render();
["f-text","f-fact","f-cufe","f-rips","f-procs"].forEach(id => {
const el = $(id);
if (!el) return;
el.addEventListener("input", rer);
el.addEventListener("change", rer);
});
$("btn-clear").addEventListener("click", ()=>{
$("f-text").value = "";
$("f-fact").value = "all";
$("f-cufe").value = "all";
$("f-rips").value = "all";
$("f-procs").value = "all";
render();
});
}
// init
$("btn-reload").addEventListener("click", cargarEvoluciones);
window.addEventListener("DOMContentLoaded", ()=>{ wireFilters(); cargarEvoluciones(); });
</script>
</body>
</html>