-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3053 lines (2800 loc) · 132 KB
/
Copy pathapp.js
File metadata and controls
3053 lines (2800 loc) · 132 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
// AhorraLuz — app.js
// Comparador de tarifas de luz via QR de factura
(function () {
'use strict';
// --- Analytics (Umami + PostHog) ---
// Helper único que dispara cada evento custom a Umami y PostHog a la vez,
// para comparar dashboards 1:1. Cada destino va en su propio try/catch: si
// una no está cargada o falla, la otra sigue y nunca rompe el flujo del
// usuario. Ambas solo existen en producción y solo si hay IDs (ver
// index.html); en localhost no se envía nada.
// No mandamos eventos a Vercel: en plan Hobby los custom events no se
// capturan (son de pago) — Vercel se queda solo con pageviews gratis.
function track(name, props) {
var data = props || {};
// Umami Cloud
try {
if (window.umami && typeof window.umami.track === 'function') {
window.umami.track(name, data);
}
} catch (_) {}
// PostHog Cloud EU
try {
if (window.posthog && typeof window.posthog.capture === 'function') {
window.posthog.capture(name, data);
}
} catch (_) {}
}
// --- DOM helpers defensivos ---
// Estos wrappers permiten que el JS siga funcionando aunque el HTML
// cacheado en el navegador del usuario esté desfasado y falte algún
// elemento. En lugar de petar con "Cannot set properties of null",
// se hace log silencioso y se sigue ejecutando.
function $(id) { return document.getElementById(id); }
function setText(id, text) {
const el = $(id);
if (el) el.textContent = text;
else if (typeof console !== 'undefined') console.warn('Missing element #' + id);
}
function setHTML(id, html) {
const el = $(id);
if (el) el.innerHTML = html;
else if (typeof console !== 'undefined') console.warn('Missing element #' + id);
}
function addClass(id, cls) { const el = $(id); if (el) el.classList.add(cls); }
function removeClass(id, cls) { const el = $(id); if (el) el.classList.remove(cls); }
function setDisplay(id, value) { const el = $(id); if (el) el.style.display = value; }
// Defensa: ocultar la card de oferta sospechosa nada más cargar. Si un
// HTML cacheado llegara sin el atributo `hidden`, esto garantiza que no
// se vea vacía con placeholders hasta que processQR decida mostrarla.
(function () { const sc = $('suspect-offer-card'); if (sc) sc.hidden = true; })();
// --- Screens ---
const screens = {
landing: document.getElementById('screen-landing'),
scanner: document.getElementById('screen-scanner'),
loading: document.getElementById('screen-loading'),
result: document.getElementById('screen-result'),
error: document.getElementById('screen-error'),
};
let videoStream = null;
let scannerActive = false;
function showScreen(name) {
Object.values(screens).forEach(s => s.classList.remove('active'));
screens[name].classList.add('active');
}
// --- Theme toggle (dark/light) ---
// Default: respeta prefers-color-scheme del sistema.
// Si el usuario clicka el toggle, override en localStorage y sobreescribe.
function getCurrentTheme() {
const override = (function () {
try { return localStorage.getItem('ahorraluz.theme'); } catch (e) { return null; }
})();
if (override === 'light' || override === 'dark') return override;
// Auto: leer del sistema
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
}
function applyTheme(theme) {
if (theme === 'dark' || theme === 'light') {
document.documentElement.setAttribute('data-theme', theme);
try { localStorage.setItem('ahorraluz.theme', theme); } catch (e) {}
}
}
const themeBtn = $('theme-toggle');
if (themeBtn) {
themeBtn.addEventListener('click', () => {
applyTheme(getCurrentTheme() === 'light' ? 'dark' : 'light');
});
}
// --- Navigation ---
document.getElementById('btn-scan').addEventListener('click', () => {
track('scan_click');
startScanner();
});
// Analytics: trackear click en cualquier CTA de oferta (slide del carrusel
// o el botón principal "Cambiar a X" del footer). Delegación en document
// porque los slides se renderizan dinámicamente.
document.addEventListener('click', e => {
const slideCta = e.target.closest('.slide-cta');
if (slideCta) {
const slide = slideCta.closest('.offers-proposed-slide');
const company = slide ? slide.querySelector('.offers-col-company')?.textContent : null;
track('open_offer', {
company: company || 'desconocida',
source: 'carousel',
rank: slide ? slide.dataset.rank : null,
suspect: slideCta.classList.contains('slide-cta-suspect'),
});
return;
}
const howtoCta = e.target.closest('#howto-cta-link');
if (howtoCta) {
const txt = howtoCta.querySelector('.howto-cta-text')?.textContent || '';
track('open_offer', {
company: txt.replace(/^Cambiar a /, ''),
source: 'howto-cta',
});
}
});
document.getElementById('btn-back').addEventListener('click', stopAndGoHome);
document.getElementById('btn-restart').addEventListener('click', stopAndGoHome);
document.getElementById('btn-retry').addEventListener('click', startScanner);
const btnShare = document.getElementById('btn-share');
if (btnShare) btnShare.addEventListener('click', copyShareLink);
// === Compartir enlace: si la URL trae #r=<lz-comprimido> autoejecutamos el
// análisis con los mismos datos del QR original. Esto permite que un
// usuario comparta sus resultados con otro sin necesidad de escanear.
// OJO: se invoca al final del IIFE (línea ~final) porque depende de
// CNMC_QR_BASE (const) que está más abajo en TDZ. ===
window.addEventListener('hashchange', tryAutoProcessFromHash);
// Debug hook: en localhost exponemos processQR para que el script
// scripts/verify-prepush.js pueda reproducir el flow sin pasar por la cámara.
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1' || location.protocol === 'file:') {
window.__ahorraluzDebug = { processQR, renderCarouselContextNote, encodeShareHash, decodeShareHash };
}
// --- Landing mockup carousel (vistosidad de portada) ---
// Casos reales/representativos que rotan en la card de la landing.
const MOCKUP_CASES = [
{
currentCompany: 'Iberdrola', bestCompany: 'Repsol Estable',
currentAmount: 892, bestAmount: 658, savings: 234, pctDown: 26,
profile: 'Familia 4 personas · Madrid',
tags: [
{ text: '100% verde', icon: '🌿', green: true },
{ text: 'Sin permanencia', icon: '🔓', green: false }
]
},
{
currentCompany: 'Endesa', bestCompany: 'Holaluz',
currentAmount: 1340, bestAmount: 928, savings: 412, pctDown: 31,
profile: 'Vivienda grande · Sevilla',
tags: [
{ text: '100% verde', icon: '🌿', green: true },
{ text: 'Sin permanencia', icon: '🔓', green: false }
]
},
{
currentCompany: 'Naturgy', bestCompany: 'Total Energies',
currentAmount: 645, bestAmount: 458, savings: 187, pctDown: 29,
profile: 'Piso 70m² · Valencia',
tags: [
{ text: 'Precio fijo 12m', icon: '🔒', green: false }
]
},
{
currentCompany: 'Iberdrola', bestCompany: 'Octopus Energy',
currentAmount: 1158, bestAmount: 838, savings: 320, pctDown: 28,
profile: 'Casa + autoconsumo · Barcelona',
tags: [
{ text: 'Compensa excedentes', icon: '☀️', green: true },
{ text: 'Sin permanencia', icon: '🔓', green: false }
]
},
];
let mockupIdx = 0;
let mockupTimer = null;
const MOCKUP_ROTATE_MS = 5000;
const MOCKUP_FADE_MS = 280;
function formatEur(n) {
return n.toLocaleString('es-ES') + ' €';
}
function animateCounter(el, from, to, duration) {
if (!el) return;
const start = performance.now();
function step(now) {
const elapsed = now - start;
const progress = Math.min(elapsed / duration, 1);
const eased = 1 - Math.pow(1 - progress, 3); // ease-out cubic
const value = Math.round(from + (to - from) * eased);
el.textContent = formatEur(value);
if (progress < 1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
function renderMockupCase(c, animate) {
const amountEl = document.getElementById('mockup-amount');
if (!amountEl) return;
document.getElementById('mockup-current-company').textContent = c.currentCompany;
document.getElementById('mockup-current-amount').textContent = formatEur(c.currentAmount);
document.getElementById('mockup-best-company').textContent = c.bestCompany;
document.getElementById('mockup-best-amount').textContent = formatEur(c.bestAmount);
document.getElementById('mockup-bar-label').textContent = `−${c.pctDown}% en tu factura anual`;
document.getElementById('mockup-profile').textContent = c.profile;
// tags
const tagsEl = document.getElementById('mockup-tags');
tagsEl.innerHTML = c.tags.map(t =>
`<span class="mockup-tag ${t.green ? 'mockup-tag-green' : ''}">${t.icon} ${t.text}</span>`
).join('');
// bar fill (use CSS transition)
requestAnimationFrame(() => {
document.getElementById('mockup-bar-fill').style.width = c.pctDown + '%';
});
// amount counter
if (animate) {
animateCounter(amountEl, 0, c.savings, 700);
} else {
amountEl.textContent = formatEur(c.savings);
}
}
function renderMockupDots() {
const dotsEl = document.getElementById('mockup-dots');
if (!dotsEl) return;
dotsEl.innerHTML = MOCKUP_CASES.map((_, i) =>
`<span class="mockup-dot ${i === mockupIdx ? 'active' : ''}"></span>`
).join('');
}
function rotateMockup() {
const card = document.querySelector('.landing-mockup');
if (!card) return;
card.classList.add('mockup-fading');
setTimeout(() => {
mockupIdx = (mockupIdx + 1) % MOCKUP_CASES.length;
renderMockupCase(MOCKUP_CASES[mockupIdx], true);
renderMockupDots();
card.classList.remove('mockup-fading');
}, MOCKUP_FADE_MS);
}
function initMockupCarousel() {
if (!document.querySelector('.landing-mockup')) return;
renderMockupCase(MOCKUP_CASES[0], true);
renderMockupDots();
if (mockupTimer) clearInterval(mockupTimer);
mockupTimer = setInterval(rotateMockup, MOCKUP_ROTATE_MS);
}
// Arrancar el carrusel al cargar
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initMockupCarousel);
} else {
initMockupCarousel();
}
function stopAndGoHome() {
stopScanner();
showScreen('landing');
// Si veníamos de un enlace compartido, limpiamos el hash para no caer
// otra vez en el flujo automático al pulsar "Escanear otra factura".
if (location.hash) history.replaceState(null, '', location.pathname + location.search);
}
// === Compartir enlace: encode / decode con LZString ===
// El hash es el formato más privado (no viaja al servidor) y LZString
// comprime los datos a base64 URL-safe. Para ahorrar bytes guardamos sólo
// el querystring del QR — la base URL del CNMC se reconstruye al decode.
const CNMC_QR_BASE = 'https://comparador.cnmc.gob.es/comparador/QRE?';
function encodeShareHash(qrUrl) {
if (!qrUrl || typeof LZString === 'undefined') return null;
// Si la URL viene con la base estándar, guardamos solo el querystring.
const idx = qrUrl.indexOf('?');
const payload = qrUrl.startsWith(CNMC_QR_BASE) && idx >= 0 ? qrUrl.slice(idx + 1) : qrUrl;
return '#r=' + LZString.compressToEncodedURIComponent(payload);
}
function decodeShareHash(hash) {
if (!hash || hash.indexOf('#r=') !== 0 || typeof LZString === 'undefined') return null;
try {
const compressed = hash.slice(3);
const decoded = LZString.decompressFromEncodedURIComponent(compressed);
if (!decoded) return null;
// Si parece un querystring suelto, reconstruimos la URL del CNMC.
if (decoded.startsWith('http')) return decoded;
if (decoded.includes('cp=') || decoded.includes('cups=')) return CNMC_QR_BASE + decoded;
return null;
} catch (_) { return null; }
}
function tryAutoProcessFromHash() {
if (!location.hash || location.hash.indexOf('#r=') !== 0) return;
// Esperamos a que LZString esté disponible (el CDN puede tardar) hasta
// 3s con poll de 50ms. Después decodificamos y procesamos el QR.
const start = Date.now();
const tryDecode = () => {
if (typeof LZString === 'undefined') {
if (Date.now() - start < 3000) return setTimeout(tryDecode, 50);
console.warn('Enlace compartido: LZString no se cargó (CDN bloqueado?)');
return;
}
const url = decodeShareHash(location.hash);
if (!url) { console.warn('Enlace compartido: hash inválido'); return; }
processQR(url).catch(e => console.error('Enlace compartido falló:', e));
};
tryDecode();
}
async function copyShareLink() {
const btn = $('btn-share');
if (!lastProcessedQrUrl) {
if (btn) {
const txt = btn.querySelector('.btn-share-text');
if (txt) txt.textContent = 'No hay datos para compartir todavía';
}
return;
}
const hash = encodeShareHash(lastProcessedQrUrl);
if (!hash) {
if (btn) {
const txt = btn.querySelector('.btn-share-text');
if (txt) txt.textContent = 'No se pudo generar el enlace';
}
return;
}
const fullUrl = location.origin + location.pathname + hash;
try {
await navigator.clipboard.writeText(fullUrl);
track('share_copied', { method: 'clipboard' });
if (btn) {
btn.classList.add('copied');
const txt = btn.querySelector('.btn-share-text');
const original = txt ? txt.textContent : '';
if (txt) txt.textContent = '¡Enlace copiado!';
setTimeout(() => {
btn.classList.remove('copied');
if (txt) txt.textContent = original;
}, 2200);
}
} catch (e) {
// Fallback: prompt manual
window.prompt('Copia este enlace:', fullUrl);
track('share_copied', { method: 'prompt-fallback' });
}
}
// --- QR Scanner (BarcodeDetector native API + jsQR fallback) ---
async function startScanner() {
// Mientras el usuario apunta al QR, vamos calentando el proxy en
// background para que la primera llamada real ya no pague cold start.
warmupProxy();
showScreen('scanner');
const video = document.getElementById('qr-video');
const canvas = document.getElementById('qr-canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
try {
videoStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 } }
});
video.srcObject = videoStream;
await video.play();
scannerActive = true;
// Use native BarcodeDetector if available (Chrome 83+, Safari 17.2+)
const hasNativeDetector = 'BarcodeDetector' in window;
let detector = null;
if (hasNativeDetector) {
detector = new BarcodeDetector({ formats: ['qr_code'] });
console.log('Using native BarcodeDetector');
} else {
console.log('Using jsQR fallback');
}
function scanFrame() {
if (!scannerActive) return;
if (video.readyState === video.HAVE_ENOUGH_DATA) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
if (detector) {
// Native BarcodeDetector — better with screens, hardware-accelerated
detector.detect(video).then(barcodes => {
if (barcodes.length > 0) {
onQrSuccess(barcodes[0].rawValue);
return;
}
requestAnimationFrame(scanFrame);
}).catch(() => requestAnimationFrame(scanFrame));
} else {
// jsQR fallback
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: 'attemptBoth',
});
if (code && code.data) {
onQrSuccess(code.data);
return;
}
requestAnimationFrame(scanFrame);
}
} else {
requestAnimationFrame(scanFrame);
}
}
requestAnimationFrame(scanFrame);
} catch (err) {
console.error('Error starting scanner:', err);
showError(
'No se pudo acceder a la c\u00e1mara',
'Aseg\u00farate de dar permiso de c\u00e1mara a esta web. Si el problema persiste, prueba desde otro navegador.',
{ error: err.message }
);
}
}
function stopScanner() {
scannerActive = false;
if (videoStream) {
videoStream.getTracks().forEach(t => t.stop());
videoStream = null;
}
const video = document.getElementById('qr-video');
if (video) video.srcObject = null;
}
// --- QR Success ---
function onQrSuccess(decodedText) {
stopScanner();
console.log('QR decoded:', decodedText);
// Validate it's a CNMC comparador URL
if (!decodedText.includes('comparador.cnmc.gob.es') && !decodedText.includes('cnmc.es')) {
showError(
'Este QR no es de una factura de luz',
'El c\u00f3digo QR debe ser el que aparece en tu factura de electricidad. Es una URL al comparador de la CNMC.',
{ qrContent: decodedText }
);
return;
}
processQR(decodedText);
}
// --- Parse QR URL ---
function parseQrUrl(url) {
const params = new URLSearchParams(new URL(url).search);
const get = (key, fallback) => {
const val = params.get(key);
if (val == null) return fallback;
// Remove units like [kW] or [kWh]
return val.replace(/\[.*?\]/g, '');
};
const getFloat = (key, fallback) => {
const val = parseFloat(get(key, String(fallback)));
return isNaN(val) ? fallback : val;
};
const getInt = (key, fallback) => {
const val = parseInt(get(key, String(fallback)));
return isNaN(val) ? fallback : val;
};
// Parse tc (tipo contrato): can be numeric (0,1,2) or string like "F0"
const tcRaw = get('tc', '0');
let tipoContrato = parseInt(tcRaw);
if (isNaN(tipoContrato)) {
// F0/F1 = fijo, I0 = indexado, etc.
tipoContrato = tcRaw.startsWith('I') ? 2 : 0;
}
return {
cups: get('cups', ''),
codigoPostal: get('cp', ''),
bonoSocial: getInt('bs', 0),
peaje: getInt('peaje', 18),
comercializadora: get('com', ''),
// Potencia contratada
potenciaP1: getFloat('pP1', 0),
potenciaP2: getFloat('pP2', 0),
potenciaP3: getFloat('pP3', 0),
potenciaP4: getFloat('pP4', 0),
potenciaP5: getFloat('pP5', 0),
potenciaP6: getFloat('pP6', 0),
// Consumo anual por periodo
consumoAnualP1: getFloat('caP1', 0),
consumoAnualP2: getFloat('caP2', 0),
consumoAnualP3: getFloat('caP3', 0),
consumoAnualP4: getFloat('caP4', 0),
consumoAnualP5: getFloat('caP5', 0),
consumoAnualP6: getFloat('caP6', 0),
// Fechas consumo anual (finA puede no estar presente)
inicioAnual: get('iniA', ''),
finAnual: get('finA', ''),
// Consumo periodo facturado
consumoFactP1: getFloat('cfP1', 0),
consumoFactP2: getFloat('cfP2', 0),
consumoFactP3: getFloat('cfP3', 0),
consumoFactP4: getFloat('cfP4', 0),
consumoFactP5: getFloat('cfP5', 0),
consumoFactP6: getFloat('cfP6', 0),
// Fechas periodo facturado
inicioFact: get('iniF', ''),
finFact: get('finF', ''),
// Fecha facturacion
fechaFacturacion: get('fFact', ''),
// Importes
importeTotal: getFloat('imp', 0),
importeServicios: getFloat('impSA', 0),
importeOtros: getFloat('impOtros', 0),
importeOtrosSinIE: getFloat('impOtrosSinIE', 0),
excedentes: getFloat('exc', 0),
importePotencia: getFloat('impPot', 0),
importeEnergia: getFloat('impEner', 0),
// Potencia maxima demandada
pmaxP1: getFloat('pmaxP1', 0),
pmaxP2: getFloat('pmaxP2', 0),
pmaxP3: getFloat('pmaxP3', 0),
pmaxP4: getFloat('pmaxP4', 0),
pmaxP5: getFloat('pmaxP5', 0),
pmaxP6: getFloat('pmaxP6', 0),
// Contrato
tipoContrato: tipoContrato,
tipoContratoRaw: tcRaw,
finPenalizacion: get('finPen', ''),
finContrato: get('finContrato', ''),
tipoFactura: getInt('reg', 0),
// Precios actuales (del contrato vigente)
precioPotP1: getFloat('prP1', 0),
precioPotP2: getFloat('prP2', 0),
precioEnerP1: getFloat('prE1', 0),
precioEnerP2: getFloat('prE2', 0),
precioEnerP3: getFloat('prE3', 0),
// Otros
verde: getInt('verde', 0),
ajuste: getFloat('ajuste', 0),
finBS: getFloat('finBS', 0),
};
}
// --- Build CNMC API params from QR data ---
function buildCnmcParams(qrData) {
const consumoAnualE = qrData.consumoAnualP1 + qrData.consumoAnualP2 + qrData.consumoAnualP3
+ qrData.consumoAnualP4 + qrData.consumoAnualP5 + qrData.consumoAnualP6;
// Timestamps for date range (ms since epoch)
// Handle missing dates robustly — some QRs don't include finA
const now = Date.now();
const yearAgo = now - (365 * 24 * 60 * 60 * 1000);
function safeTimestamp(dateStr, fallback) {
if (!dateStr) return fallback;
const t = new Date(dateStr).getTime();
return isNaN(t) ? fallback : t;
}
const dateInicio = safeTimestamp(qrData.inicioAnual, yearAgo);
// If finA missing, estimate as iniA + 1 year
const dateFin = safeTimestamp(qrData.finAnual, dateInicio + (365 * 24 * 60 * 60 * 1000));
const fFact = safeTimestamp(qrData.fechaFacturacion, safeTimestamp(qrData.finFact, now));
return {
tipoSuministro: 'E',
codigoPostal: qrData.codigoPostal,
potencia: qrData.potenciaP1,
potenciaPrimeraFranja: qrData.potenciaP1,
potenciaSegundaFranja: qrData.potenciaP2 || qrData.potenciaP1,
potenciaTerceraFranja: qrData.potenciaP3 || qrData.potenciaP1,
potenciaCuartaFranja: qrData.potenciaP4 || qrData.potenciaP1,
potenciaQuintaFranja: qrData.potenciaP5 || qrData.potenciaP1,
potenciaSextaFranja: qrData.potenciaP6 || qrData.potenciaP1,
consumoAnualE: consumoAnualE,
consumoAnualEOrig: consumoAnualE,
consumoPrimeraFranja: qrData.consumoAnualP1,
consumoSegundaFranja: qrData.consumoAnualP2,
consumoTerceraFranja: qrData.consumoAnualP3,
consumoCuartaFranja: qrData.consumoAnualP4,
consumoQuintaFranja: qrData.consumoAnualP5,
consumoSextaFranja: qrData.consumoAnualP6,
consumoAnualEQr: 0,
consumoPrimeraFranjaQr: 0,
consumoSegundaFranjaQr: 0,
consumoTerceraFranjaQr: 0,
consumoCuartaFranjaQr: 0,
consumoQuintaFranjaQr: 0,
consumoSextaFranjaQr: 0,
consumoAnualEPQr: 0,
consumoPrimeraFranjaPQr: 0,
consumoSegundaFranjaPQr: 0,
consumoTerceraFranjaPQr: 0,
consumoCuartaFranjaPQr: 0,
consumoQuintaFranjaPQr: 0,
consumoSextaFranjaPQr: 0,
tarifa: qrData.peaje === 19 ? 5 : 4, // 4=2.0TD, 5=3.0TD
consumoAnualG: 0,
consumoAnualGOrig: 0,
serviciosAdicionales: 2,
permanencia: 2,
vivienda: true,
factura: true,
energiaAutoconsumo: 0,
idAuditoriaQR: 0,
potenciaAutoconsumo: 0,
revisionPrecios: 2,
autoconsumo: false,
importe: qrData.importeTotal || 0,
mecanismoAjuste: 0,
mecanismoAjusteIVA: 0,
importeMecanismoAjustePunta: 0,
importeMecanismoAjusteLlano: 0,
importeMecanismoAjusteValle: 0,
precioConsumoMecanismoAjusteTotal: 0,
precioConsumoMecanismoAjustePunta: 0,
precioConsumoMecanismoAjusteLlano: 0,
precioConsumoMecanismoAjusteValle: 0,
perfilConsumo: 10,
dateInicio: dateInicio,
dateFin: dateFin,
tc: qrData.tipoContrato,
bs: qrData.bonoSocial,
impSA: qrData.importeServicios,
impOtros: qrData.importeOtros || 0,
exc: qrData.excedentes || 0,
reg: qrData.tipoFactura || 0,
impOtrosConIE: 0,
impOtrosSinIE: qrData.importeOtrosSinIE || 0,
pmaxP1: qrData.pmaxP1 || 0,
pmaxP2: qrData.pmaxP2 || 0,
fFact: fFact,
dtoBS: 0,
finBS: qrData.finBS || 0,
ajuste: qrData.ajuste || 0,
impPot: qrData.importePotencia || 0,
impEner: qrData.importeEnergia || 0,
dto: 0,
prP1: qrData.precioPotP1 || 0,
prP2: qrData.precioPotP2 || 0,
prE1: qrData.precioEnerP1 || 0,
prE2: qrData.precioEnerP2 || 0,
prE3: qrData.precioEnerP3 || 0,
cfP1flex: 0,
cfP2flex: 0,
cambio: 0,
promo: 0,
verde: qrData.verde || 0,
rev: 0,
trampeo: 0,
cups: qrData.cups ? qrData.cups.slice(-4) : '0000',
};
}
// --- CNMC API ---
// Proxy needed: CNMC nginx blocks requests with Origin header (403)
// Deploy proxy-worker.js to Cloudflare Workers and set URL here
// For local dev: use direct URL (works without Origin from file://)
// Lista ordenada de proxies. La app prueba en orden hasta que uno responda.
// Cuando despliegues Vercel, pon su URL como primer elemento.
// Para testing local, puedes inyectar uno con localStorage.setItem('ahorraluz.proxy', 'https://...').
const PROXY_BASES = [
// Vercel proxy: el path se pasa como query param ?path=<endpoint>
// Descomentar y poner la URL real cuando despliegues api/cnmc.js a Vercel:
// 'https://AHORRALUZ.vercel.app/api/cnmc?path=',
'https://rough-sun-c2a5.iker-267.workers.dev/api/publico/',
];
// Override puntual desde localStorage (sin redeploy).
const lsProxy = (typeof localStorage !== 'undefined' && localStorage.getItem('ahorraluz.proxy')) || '';
if (lsProxy) PROXY_BASES.unshift(lsProxy);
const CNMC_DIRECT = 'https://comparador.cnmc.gob.es/api/publico/';
// Timeouts muy generosos: el endpoint /ofertas/electricidad de CNMC
// puede tardar 15-25s desde algunos edges de Cloudflare *.workers.dev
// (Bot Fight Mode + challenges JS). Antes de introducir AbortController
// no había timeout y la app funcionaba aunque lenta — preferimos que
// tarde a que aborte. El timeout es solo protección extrema.
// Si tarda más de 90s, algo va mal de verdad.
const PROXY_TIMEOUT_MS = 90000;
const DIRECT_TIMEOUT_MS = 30000;
// Diagnóstico del último intento — lo expone showError para que en
// caso de fallo sepamos qué pasó realmente con el proxy.
let lastApiDiag = null;
// Warm-up: ping a /health (Vercel) o /health del worker para que el
// proxy esté caliente cuando el usuario termine de escanear.
function warmupProxy() {
PROXY_BASES.forEach(base => {
let healthUrl;
if (base.includes('?path=')) {
healthUrl = base + 'health';
} else {
healthUrl = base.replace(/\/api\/publico\/?$/, '/health');
}
fetch(healthUrl, { cache: 'no-store' }).catch(() => {});
});
}
// Fetch con timeout via AbortController. Si el endpoint no responde en
// `ms` cancelamos para no quedar colgados en el paso intermedio.
async function fetchWithTimeout(url, ms, init = {}) {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), ms);
try {
return await fetch(url, { ...init, signal: ctrl.signal });
} finally {
clearTimeout(t);
}
}
function buildProxyUrl(base, pathWithQuery) {
// Vercel style: base = "https://x.vercel.app/api/cnmc?path="
// pathWithQuery = "ofertas/electricidad?cp=31006&pot=3"
// resultado = "https://x.vercel.app/api/cnmc?path=ofertas/electricidad&cp=31006&pot=3"
if (base.endsWith('?path=')) {
const qIdx = pathWithQuery.indexOf('?');
if (qIdx === -1) return base + pathWithQuery;
const endpoint = pathWithQuery.slice(0, qIdx);
const query = pathWithQuery.slice(qIdx + 1);
return base + endpoint + '&' + query;
}
// Cloudflare style: base ya termina en /api/publico/
return base + pathWithQuery;
}
async function fetchFromApi(path) {
const diag = { proxies: [], direct: null, startedAt: Date.now() };
// 1) Probar cada proxy en orden hasta que uno responda 2xx
for (const base of PROXY_BASES) {
const t = Date.now();
const url = buildProxyUrl(base, path);
try {
const response = await fetchWithTimeout(
url,
PROXY_TIMEOUT_MS,
{ headers: { 'Accept': 'application/json' } }
);
const entry = { base: base.slice(0, 50), status: response.status, ms: Date.now() - t };
diag.proxies.push(entry);
if (response.ok) {
lastApiDiag = diag;
return response;
}
console.warn(`Proxy ${entry.base}... ${response.status} en ${entry.ms}ms — siguiente fallback`);
} catch (e) {
diag.proxies.push({ base: base.slice(0, 50), error: e.name + ': ' + e.message, ms: Date.now() - t });
console.warn(`Proxy ${base.slice(0, 50)} ${e.name} en ${Date.now() - t}ms — siguiente fallback`);
}
}
// 2) Directo: funciona desde localhost/file:// y curl. En producción
// cross-origin probablemente devuelva 403 por el Origin header.
const tDirect = Date.now();
try {
const response = await fetchWithTimeout(
`${CNMC_DIRECT}${path}`,
DIRECT_TIMEOUT_MS,
{ headers: { 'Accept': 'application/json' } }
);
diag.direct = { status: response.status, ms: Date.now() - tDirect };
lastApiDiag = diag;
return response;
} catch (e) {
diag.direct = { error: e.name + ': ' + e.message, ms: Date.now() - tDirect };
lastApiDiag = diag;
throw e;
}
}
async function fetchOffers(params) {
const qs = Object.entries(params)
.filter(([, v]) => v != null && v !== '')
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
const path = `ofertas/electricidad?${qs}`;
console.log('Fetching offers, params count:', Object.keys(params).length);
const response = await fetchFromApi(path);
if (!response.ok) {
const body = await response.text().catch(() => '');
throw new Error(`API error ${response.status}: ${body.slice(0, 200)}`);
}
return response.json();
}
// Clean company names: Title Case, remove legal suffixes
function cleanCompanyName(raw) {
if (!raw) return '';
let name = raw.trim().replace(/"/g, '');
// Remove legal suffixes (with or without dots, commas)
name = name.replace(/,?\s*(S\.?L\.?U\.?|S\.?L\.?|S\.?A\.?U\.?|S\.?A\.?|SLU|S\.?COOP\.?|SOCIEDAD LIMITADA|SOCIEDAD AN[OÓ]NIMA)\s*\.?\s*$/i, '');
name = name.trim().replace(/[,.\s]+$/, '');
// Title Case if all caps
if (name === name.toUpperCase() && name.length > 3) {
name = name.toLowerCase()
.replace(/(?:^|\s|[-/])\S/g, c => c.toUpperCase())
// Keep common lowercase words
.replace(/\s(De|Del|Y|La|El|Los|Las|En)\s/g, (m) => m.toLowerCase());
}
return name;
}
async function fetchCompanyName(code) {
if (!code) return 'Tu comercializadora';
try {
const response = await fetchFromApi(`nombrecodigo/${code}`);
if (response.ok) {
const raw = await response.text();
const clean = cleanCompanyName(raw);
if (clean) return clean;
}
} catch (e) {
// ignore
}
return code;
}
// --- Process QR ---
// Guardamos la última URL procesada para poder generar el enlace de
// compartir desde la pantalla de resultados.
let lastProcessedQrUrl = null;
async function processQR(url) {
lastProcessedQrUrl = url;
showScreen('loading');
resetLoadingSteps();
try {
// Step 1: QR read
await completeStep('step-qr', 500);
// Step 2: Parse data
let qrData;
try {
qrData = parseQrUrl(url);
console.log('Parsed QR data:', JSON.stringify(qrData, null, 2));
} catch (e) {
showError(
'QR no v\u00e1lido',
'El c\u00f3digo QR no contiene datos v\u00e1lidos de una factura de luz. Aseg\u00farate de escanear el QR correcto.',
{ error: e.message, qrUrl: url, stack: e.stack }
);
return;
}
await completeStep('step-data', 600);
// Validate minimum data
const consumoTotal = qrData.consumoAnualP1 + qrData.consumoAnualP2 + qrData.consumoAnualP3;
if (consumoTotal === 0 && qrData.importeTotal === 0) {
showError(
'Datos insuficientes en el QR',
'El QR de tu factura no contiene datos de consumo. Esto puede ocurrir si la comercializadora no ha informado correctamente el QR. Contacta con tu comercializadora.'
);
return;
}
// Step 3: Fetch offers
activateStep('step-offers');
const cnmcParams = buildCnmcParams(qrData);
// El endpoint /ofertas/electricidad de CNMC tarda 8-25s.
// Cambiamos el texto progresivamente para que el usuario sepa
// que sigue trabajando y no piense que se atascó.
const tip6 = setTimeout(() => {
const el = document.querySelector('#step-offers .step-text');
if (el) el.textContent = 'Consultando la CNMC (puede tardar)...';
}, 6000);
const tip15 = setTimeout(() => {
const el = document.querySelector('#step-offers .step-text');
if (el) el.textContent = 'La CNMC está respondiendo lento, sigue trabajando...';
}, 15000);
const tip30 = setTimeout(() => {
const el = document.querySelector('#step-offers .step-text');
if (el) el.textContent = 'Casi listo, no cierres la pestaña...';
}, 30000);
let offers;
let apiError = null;
try {
offers = await fetchOffers(cnmcParams);
} catch (e) {
console.error('CNMC API failed:', e);
apiError = e;
} finally {
clearTimeout(tip6);
clearTimeout(tip15);
clearTimeout(tip30);
}
if (apiError || !offers || !offers.resultadoComparador || offers.resultadoComparador.length === 0) {
const reason = apiError
? `Error de conexi\u00f3n: ${apiError.message}`
: 'El comparador no ha devuelto ofertas para tu perfil de consumo';
showError(
'No hemos podido obtener ofertas reales',
`${reason}. Puedes consultar directamente el comparador oficial de la CNMC escaneando el QR con la c\u00e1mara de tu m\u00f3vil (sin usar esta app) o visitando comparador.cnmc.gob.es.`,
{
error: apiError ? apiError.message : 'Sin ofertas en la respuesta',
apiDiag: lastApiDiag,
codigoPostal: cnmcParams.codigoPostal,
consumoAnualE: cnmcParams.consumoAnualE,
potencia: cnmcParams.potencia,
tarifa: cnmcParams.tarifa,
ofertasRecibidas: offers ? (offers.resultadoComparador || []).length : 0,
}
);
return;
}
await completeStep('step-offers', 300);
// Step 4: Calculate
activateStep('step-calc');
const companyName = await fetchCompanyName(qrData.comercializadora);
const currentAnnualCost = estimateAnnualCost(qrData);
const results = processOffers(offers, qrData, currentAnnualCost, companyName);
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
window.__lastResults = results;
window.__lastQrData = qrData;
window.__lastOffersRaw = offers;
}
await completeStep('step-calc', 400);
// Show results
displayConsumption(qrData, companyName);
displayResults(results, qrData);
displayRecomendaciones(qrData);
// Analytics: el flow llegó hasta el resultado. Mandamos contexto
// anonimizado (sin CUPS ni CP exactos) para entender qué casuísticas
// ven más los usuarios.
track('qr_processed', {
currentCompany: results.current.company,
savings: Math.round(results.legitimateSavings != null ? results.legitimateSavings : results.savings),
totalOffers: results.totalOffers,
userRank: results.userRankPosition,
heroMode: results.heroMode,
hasSuspect: results.heroMode === 'dual',
});
} catch (e) {
console.error('Error processing QR:', e);
showError(
'Error al procesar tu factura',
'Ha ocurrido un error inesperado. Por favor, int\u00e9ntalo de nuevo.',
{ error: e.message, stack: e.stack }
);
}
}
// --- Cost estimation from QR data ---
function estimateAnnualCost(qrData) {
// Method 1 (BEST): Use contract prices from QR × annual consumption
// This is the most accurate because it uses real annual consumption
// and the actual prices from the user's contract
if (qrData.precioEnerP1 > 0 && qrData.precioPotP1 > 0) {
const consumoTotal = qrData.consumoAnualP1 + qrData.consumoAnualP2 + qrData.consumoAnualP3;
if (consumoTotal > 0) {
const costePotencia = (qrData.potenciaP1 * qrData.precioPotP1)
+ ((qrData.potenciaP2 || qrData.potenciaP1) * qrData.precioPotP2);
const costeEnergia = (qrData.consumoAnualP1 * qrData.precioEnerP1)
+ (qrData.consumoAnualP2 * qrData.precioEnerP2)
+ (qrData.consumoAnualP3 * qrData.precioEnerP3);
const subtotal = costePotencia + costeEnergia;
const impElectrico = subtotal * 0.0511;
const base = subtotal + impElectrico;
const iva = base * 0.21;
return base + iva;
}
}
// Method 2: Estimate from consumption with average market prices
const consumoTotal = qrData.consumoAnualP1 + qrData.consumoAnualP2 + qrData.consumoAnualP3;