-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreporte_costos_profesionales.html
More file actions
587 lines (497 loc) · 16.3 KB
/
Copy pathreporte_costos_profesionales.html
File metadata and controls
587 lines (497 loc) · 16.3 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
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Reporte de Facturación por Profesional</title>
<!-- Tipografía -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<!-- Excel -->
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<style>
:root{
--bg:#f4f6f8;
--card:#ffffff;
--text:#1f2937;
--muted:#6b7280;
--brand:#1f6aa5;
--brand2:#114a75;
--line:#e5e7eb;
--radius:14px;
--shadow:0 10px 25px rgba(0,0,0,.08);
--green:#16a34a;
--red:#dc2626;
}
*{box-sizing:border-box}
body{
margin:0;
font-family:'Inter',system-ui,Arial,sans-serif;
background:var(--bg);
color:var(--text);
padding:24px;
}
h1{font-size:20px;margin:0}
.muted{color:var(--muted);font-size:13px}
.container{max-width:1400px;margin:0 auto}
.topbar{
display:flex;
justify-content:space-between;
align-items:center;
margin-bottom:16px;
}
.userbox{
font-size:13px;
background:#fff;
border:1px solid var(--line);
border-radius:12px;
padding:10px 12px;
box-shadow:var(--shadow);
line-height:1.35;
min-width:260px;
text-align:left;
}
.card{
background:var(--card);
border-radius:var(--radius);
box-shadow:var(--shadow);
border:1px solid var(--line);
margin-bottom:18px;
}
.card-header{
padding:16px 20px;
border-bottom:1px solid var(--line);
display:flex;
justify-content:space-between;
align-items:center;
gap:12px;
flex-wrap:wrap;
}
.actions{display:flex;gap:10px;flex-wrap:wrap}
.filters{
display:grid;
grid-template-columns:repeat(6,1fr);
gap:12px;
padding:16px 20px;
}
label{
font-size:12px;
color:var(--muted);
font-weight:600;
margin-bottom:4px;
display:block;
}
input{
width:100%;
padding:10px 12px;
border-radius:10px;
border:1px solid var(--line);
font-size:14px;
background:#fff;
outline:none;
}
.btn{
padding:10px 14px;
border-radius:10px;
border:1px solid var(--brand);
background:var(--brand);
color:#fff;
font-weight:700;
cursor:pointer;
}
.btn.secondary{
background:#fff;
color:var(--brand);
}
.btn:hover{background:var(--brand2);color:#fff}
table{
width:100%;
border-collapse:collapse;
font-size:13px;
}
thead th{
background:#f9fafb;
color:var(--muted);
font-weight:700;
padding:12px 14px;
border-bottom:1px solid var(--line);
position:sticky;
top:0;
z-index:1;
text-align:left;
}
tbody td{
padding:10px 14px;
border-bottom:1px solid var(--line);
vertical-align:top;
}
tbody tr:hover{background:#f8fafc}
.right{text-align:right}
.mono{font-family:ui-monospace,monospace}
.summary{
display:flex;
gap:16px;
flex-wrap:wrap;
padding:16px 20px;
border-top:1px solid var(--line);
background:#fbfcfd;
}
.box{
border:1px solid var(--line);
border-radius:12px;
padding:12px 14px;
min-width:220px;
background:#fff;
font-size:13px;
display:flex;
justify-content:space-between;
align-items:center;
gap:10px;
}
.hidden{display:none}
@media(max-width:1100px){
.filters{grid-template-columns:repeat(3,1fr)}
}
@media(max-width:700px){
.filters{grid-template-columns:1fr}
.userbox{min-width:auto}
}
</style>
</head>
<body>
<div class="container">
<div class="topbar">
<div></div>
<div class="userbox" id="userBox">Cargando usuario…</div>
</div>
<div class="card hidden" id="app">
<div class="card-header">
<div>
<h1>Reporte de Facturación por Profesional</h1>
<div class="muted">Detalle completo desde <b>factura_detalle_ext</b></div>
</div>
<div class="actions">
<button class="btn secondary" id="btn-excel">📊 Exportar Excel</button>
<button class="btn" id="btn-buscar">🔎 Buscar</button>
</div>
</div>
<div class="filters">
<!-- PROFESIONAL -->
<div>
<label>Profesional</label>
<input id="f_profesional" list="dl_profesionales" placeholder="Buscar profesional…">
<datalist id="dl_profesionales"></datalist>
</div>
<div>
<label>N° Factura</label>
<input id="f_factura" placeholder="FAC-2026...">
</div>
<div>
<label>Cédula</label>
<input id="f_cedula" placeholder="Solo números">
</div>
<!-- PACIENTE -->
<div>
<label>Paciente</label>
<input id="f_paciente" list="dl_pacientes" placeholder="Buscar paciente…">
<datalist id="dl_pacientes"></datalist>
</div>
<div>
<label>Desde</label>
<input type="date" id="f_desde">
</div>
<div>
<label>Hasta</label>
<input type="date" id="f_hasta">
</div>
<!-- PROCEDIMIENTO (para no perderlo) -->
<div style="grid-column:1 / span 3;">
<label>Procedimiento</label>
<input id="f_procedimiento" placeholder="Texto libre">
</div>
</div>
<div style="overflow:auto;max-height:60vh">
<table>
<thead>
<tr>
<th>Fecha</th>
<th>Profesional</th>
<th>N° Factura</th>
<th>Cédula</th>
<th>Paciente</th>
<th>Procedimiento</th>
<th class="right">Cantidad</th>
<th class="right">Costo Unitario</th>
<th class="right">Costo Total</th>
<th class="right">Valor Total</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
<div class="summary">
<div class="box"><span>Registros</span><b id="s_count">0</b></div>
<div class="box"><span>Total facturado</span><b>$ <span id="s_total">0</span></b></div>
<div class="box"><span>Total costo</span><b>$ <span id="s_costo">0</span></b></div>
<div class="box"><span>Margen de ganancia</span><b id="s_margen">$ 0</b></div>
</div>
</div>
<div id="noAccess" class="card hidden" style="padding:24px;text-align:center">
⛔ Acceso denegado. Este módulo es solo para administradores.
</div>
</div>
<script type="module">
import { createClient } from "https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/+esm";
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 $ = (id) => document.getElementById(id);
const money = (n) => Number(n||0).toLocaleString("es-CO");
const fmtFecha = (v) => {
if (!v) return "—";
// si viene timestamp: 2026-02-04T...
const s = String(v);
return s.split("T")[0];
};
function getModuloActual(){
const file = (location.pathname.split("/").pop() || "").toLowerCase().trim();
return file.replace(".html", "") || "reporte_costos_profesionales";
}
function getModuloCandidates(mod){
const base = String(mod || "").toLowerCase().trim();
const withHtml = base.endsWith(".html") ? base : base + ".html";
const undersc = base.replaceAll("-", "_");
const underscHtml = undersc.endsWith(".html") ? undersc : undersc + ".html";
return Array.from(new Set([base, withHtml, undersc, underscHtml].filter(Boolean)));
}
async function verificarSesion(){
const { data: { session }, error } = await supabase.auth.getSession();
if (error) console.error("getSession error:", error);
if (!session){
window.location.href = LOGIN_URL;
return null;
}
return session;
}
async function cargarRolDesdeProfiles(userId){
try{
const { data, error } = await supabase
.from("profiles")
.select("role")
.eq("id", userId)
.single();
if (error){
console.warn("No se pudo leer profiles.role:", error.message);
return null;
}
return data?.role || null;
}catch(e){
console.warn("Error leyendo role:", e);
return null;
}
}
async function validarPermisoModuloAdmin(){
// 1) sesión
const session = await verificarSesion();
if (!session) return { ok:false };
// 2) rol real
const roleRaw = await cargarRolDesdeProfiles(session.user.id);
const roleNorm = String(roleRaw || "").toLowerCase().trim();
const roleFinal = roleNorm || "user";
// pintar usuario/rol SIEMPRE
$("userBox").innerHTML = `👤 ${session.user?.email || "Usuario"}<br>🛡️ Rol: <b>${roleFinal}</b>`;
// 3) bloqueo por rol: SOLO admin
if (roleFinal !== "admin"){
return { ok:false, session, rol: roleFinal };
}
// 4) (recomendado) validar modulos_permisos (admin=true)
// Si no tienes fila para este módulo, igual te dejará entrar si eres admin
const MODULO = getModuloActual();
const candidates = getModuloCandidates(MODULO);
try{
const { data, error } = await supabase
.from("modulos_permisos")
.select("admin, modulo")
.in("modulo", candidates)
.limit(1);
if (error){
console.warn("No se pudo leer modulos_permisos:", error.message);
return { ok:true, session, rol: roleFinal }; // admin pasa aunque no lea permisos
}
const permiso = data?.[0] || null;
if (permiso && permiso.admin !== true){
// existe fila pero admin no está permitido
return { ok:false, session, rol: roleFinal };
}
// si no existe fila, no bloqueamos (porque ya es admin)
return { ok:true, session, rol: roleFinal };
}catch(e){
console.warn("Error validando modulos_permisos:", e);
return { ok:true, session, rol: roleFinal };
}
}
/* ===== APP ===== */
let currentRows = [];
async function cargarListas(){
// PROFESIONALES
const { data: profs, error: e1 } = await supabase
.from("factura_detalle_ext")
.select("profesional")
.not("profesional","is",null);
if (e1) console.warn("Error cargando profesionales:", e1.message);
const profesionales = Array.from(new Set((profs||[])
.map(x => (x?.profesional || "").trim())
.filter(Boolean)
)).sort((a,b)=>a.localeCompare(b));
$("dl_profesionales").innerHTML = profesionales.map(p => `<option value="${p}"></option>`).join("");
// PACIENTES
const { data: pacs, error: e2 } = await supabase
.from("factura_detalle_ext")
.select("paciente_nombre")
.not("paciente_nombre","is",null);
if (e2) console.warn("Error cargando pacientes:", e2.message);
const pacientes = Array.from(new Set((pacs||[])
.map(x => (x?.paciente_nombre || "").trim())
.filter(Boolean)
)).sort((a,b)=>a.localeCompare(b));
$("dl_pacientes").innerHTML = pacientes.map(p => `<option value="${p}"></option>`).join("");
}
async function cargarReporte(){
let q = supabase.from("factura_detalle_ext").select("*");
const prof = ($("f_profesional").value || "").trim();
const fac = ($("f_factura").value || "").trim();
const ced = ($("f_cedula").value || "").trim();
const pac = ($("f_paciente").value || "").trim();
const des = ($("f_desde").value || "").trim();
const has = ($("f_hasta").value || "").trim();
const proc = ($("f_procedimiento").value || "").trim();
if (prof) q = q.ilike("profesional", `%${prof}%`);
if (fac) q = q.ilike("numero_factura", `%${fac}%`);
if (ced) q = q.ilike("paciente_cedula", `%${ced}%`);
if (pac) q = q.ilike("paciente_nombre", `%${pac}%`);
if (proc) q = q.ilike("descripcion", `%${proc}%`);
// fecha_factura viene de tu vista (alias)
if (des) q = q.gte("fecha_factura", des);
if (has) q = q.lte("fecha_factura", has);
// orden recomendado
q = q.order("fecha_factura", { ascending: false });
const { data, error } = await q;
if (error){
alert("Error cargando reporte: " + error.message);
console.error(error);
return;
}
currentRows = data || [];
render();
}
function render(){
let total = 0;
let costo = 0;
let costoTotal = 0;
const tbody = $("tbody");
tbody.innerHTML = "";
for (const r of currentRows){
const vTotal = Number(r.valor_total || 0);
const vCosto = Number(r.costo || 0);
const vCostoTotal = Number(r.costo_total || 0);
total += vTotal;
costo += vCosto;
costoTotal += vCostoTotal;
const tr = document.createElement("tr");
tr.innerHTML = `
<td class="mono">${fmtFecha(r.fecha_factura)}</td>
<td>${r.profesional || "—"}</td>
<td class="mono">${r.numero_factura || "—"}</td>
<td class="mono">${r.paciente_cedula || "—"}</td>
<td>${r.paciente_nombre || "—"}</td>
<td>${r.descripcion || "—"}</td>
<td class="right mono">${r.cantidad ?? 0}</td>
<td class="right mono">$ ${money(vCosto)}</td>
<td class="right mono">$ ${money(vCostoTotal)}</td>
<td class="right mono">$ ${money(vTotal)}</td>
`;
tbody.appendChild(tr);
}
$("s_count").textContent = currentRows.length;
$("s_total").textContent = money(total);
$("s_costo").textContent = money(costoTotal);
const margen = total - costoTotal;
$("s_margen").textContent = "$ " + money(margen);
$("s_margen").style.color = margen >= 0 ? "var(--green)" : "var(--red)";
}
function exportarExcel(){
if (!currentRows || currentRows.length === 0){
alert("No hay datos para exportar.");
return;
}
const data = currentRows.map(r => ({
"Fecha": fmtFecha(r.fecha_factura),
"Profesional": r.profesional || "",
"N° Factura": r.numero_factura || "",
"Cédula": r.paciente_cedula || "",
"Paciente": r.paciente_nombre || "",
"Procedimiento": r.descripcion || "",
"Cantidad": Number(r.cantidad || 0),
"Costo Unitario": Number(r.costo || 0),
"Costo Total": Number(r.costo_total || 0),
"Valor Total": Number(r.valor_total || 0),
}));
const totalFacturado = currentRows.reduce((acc, r) => acc + (Number(r.valor_total) || 0), 0);
const totalCosto = currentRows.reduce((acc, r) => acc + (Number(r.costo) || 0), 0);
const margen = totalFacturado - totalCosto;
const ws = XLSX.utils.json_to_sheet(data);
const ws2 = XLSX.utils.aoa_to_sheet([
["Reporte de Facturación por Profesional"],
["Generado:", new Date().toLocaleString("es-CO")],
["Registros:", currentRows.length],
["Total facturado:", totalFacturado],
["Total costo:", totalCosto],
["Margen:", margen],
[],
["Filtros"],
["Profesional:", ($("f_profesional").value || "")],
["N° Factura:", ($("f_factura").value || "")],
["Cédula:", ($("f_cedula").value || "")],
["Paciente:", ($("f_paciente").value || "")],
["Procedimiento:", ($("f_procedimiento").value || "")],
["Desde:", ($("f_desde").value || "")],
["Hasta:", ($("f_hasta").value || "")]
]);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Reporte");
XLSX.utils.book_append_sheet(wb, ws2, "Filtros");
const desde = ($("f_desde").value || "NA");
const hasta = ($("f_hasta").value || "NA");
XLSX.writeFile(wb, `reporte_facturacion_${desde}_a_${hasta}.xlsx`);
}
async function init(){
try{
// Guard: solo admin (desde profiles) + (opcional) modulos_permisos
const guard = await validarPermisoModuloAdmin();
if (!guard.ok){
$("noAccess").classList.remove("hidden");
return;
}
$("app").classList.remove("hidden");
// eventos
$("btn-buscar").addEventListener("click", cargarReporte);
$("btn-excel").addEventListener("click", exportarExcel);
// cargar listas + reporte
await cargarListas();
await cargarReporte();
}catch(err){
console.error(err);
$("userBox").innerHTML = `⚠️ Error cargando usuario/rol.<br><small>Revisa consola (F12) → ${err?.message || err}</small>`;
$("noAccess").classList.remove("hidden");
}
}
// si se cierra sesión, sacar al login
supabase.auth.onAuthStateChange((_event, session) => {
if (!session) window.location.href = LOGIN_URL;
});
window.addEventListener("DOMContentLoaded", init);
</script>
</body>
</html>