-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
6315 lines (5507 loc) · 237 KB
/
Copy pathscript.js
File metadata and controls
6315 lines (5507 loc) · 237 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
// Importa a função de exportação do boletim
// <script src="boletim.js"></script> deve estar incluído no index.html antes de script.js para garantir que a função esteja disponível
// URL base da API — em desenvolvimento local o server.js injeta window.API_BASE_URL via index.html
const API_BASE = window.API_BASE_URL ||
(((window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') && window.location.port === '3000')
? 'http://localhost:3000'
: 'https://ak4ai-sigaa.duckdns.org');
const STORAGE_LAST_CONSULTA = 'sigaaUltimaConsulta';
const STORAGE_SAVED_PROFILES = 'sigaaPerfisSalvos';
const STORAGE_SELECTED_PROFILE = 'sigaaPerfilSelecionado';
const STORAGE_COMPARISON_MODE = 'sigaaComparisonMode';
const STORAGE_SKIP_SCHEDULE = 'sigaaSkipSchedule';
const STORAGE_HOME_MODE = 'sigaaHomeMode';
const MAX_SAVED_PROFILES = 2;
const DEBUG_LOG_MAX_ENTRIES = 250;
const HOME_MODES = new Set(['graduacao', 'tecnico', 'responsavel']);
const HOME_MODE_LAYOUTS = {
graduacao: {
showHomeAviso: true,
showHomeLists: true,
showNovidades: true,
showAtividades: true,
showToggle: true
},
tecnico: {
showHomeAviso: true,
showHomeLists: true,
showNovidades: false,
showAtividades: true,
showToggle: false
},
responsavel: {
showHomeAviso: true,
showHomeLists: true,
showNovidades: false,
showAtividades: false,
showToggle: false
}
};
const debugConsoleState = {
initialized: false,
entries: []
};
const originalConsole = {
log: console.log.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
debug: console.debug.bind(console)
};
function formatDebugConsoleArg(value) {
if (value instanceof Error) {
return value.stack || `${value.name}: ${value.message}`;
}
if (typeof value === 'string') {
return value;
}
try {
return JSON.stringify(value);
} catch (e) {
return String(value);
}
}
function appendDebugConsoleEntry(level, args) {
const timestamp = new Date().toLocaleTimeString('pt-BR', { hour12: false });
const message = (args || []).map(formatDebugConsoleArg).join(' ');
const line = `[${timestamp}] [${String(level || 'log').toUpperCase()}] ${message}`;
debugConsoleState.entries.push(line);
if (debugConsoleState.entries.length > DEBUG_LOG_MAX_ENTRIES) {
debugConsoleState.entries.shift();
}
renderDebugConsoleOutput();
}
// Delegated global handlers for home-aviso buttons (ensures clicks captured
// even if DOMContentLoaded timing or overlays interfere). Uses capture to run early.
(function setupGlobalHomeAvisoDelegation() {
const KEY = 'sigaa_nao_mostrar_aviso';
function persistDontShow() {
try { localStorage.setItem(KEY, '1'); return; } catch (e) { }
try { sessionStorage.setItem(KEY, '1'); return; } catch (e) { }
try {
const expires = new Date(Date.now() + 10 * 365 * 24 * 60 * 60 * 1000).toUTCString();
document.cookie = `${KEY}=1; expires=${expires}; path=/; samesite=lax`;
} catch (e) { }
}
function handleClick(e) {
try {
const btn = e.target && e.target.closest && e.target.closest('#fechar-aviso, #nao-mostrar-aviso');
if (!btn) return;
e.preventDefault(); e.stopPropagation();
const aviso = document.getElementById('home-aviso');
if (btn.id === 'fechar-aviso') {
try { sessionStorage.setItem(KEY, '1'); } catch (e) { }
if (aviso) aviso.remove();
console.log('[Aviso] fechar clicado (delegated global)');
return;
}
// nao-mostrar-aviso
persistDontShow();
if (aviso) aviso.remove();
console.log('[Aviso] não mostrar mais clicado (delegated global)');
} catch (err) { /* ignore */ }
}
document.addEventListener('click', handleClick, true);
document.addEventListener('touchstart', handleClick, { passive: false, capture: true });
})();
function renderDebugConsoleOutput() {
const output = document.getElementById('debug-log-output');
if (!output) return;
output.textContent = debugConsoleState.entries.length
? debugConsoleState.entries.join('\n')
: 'Sem logs capturados até o momento.';
output.scrollTop = output.scrollHeight;
}
function initDebugConsolePanel() {
const copyBtn = document.getElementById('debug-log-copy-btn');
const clearBtn = document.getElementById('debug-log-clear-btn');
if (copyBtn && copyBtn.dataset.bound !== '1') {
copyBtn.dataset.bound = '1';
copyBtn.addEventListener('click', async () => {
const text = debugConsoleState.entries.length
? debugConsoleState.entries.join('\n')
: 'Sem logs capturados até o momento.';
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
const originalLabel = copyBtn.textContent;
copyBtn.textContent = 'Copiado';
setTimeout(() => {
copyBtn.textContent = originalLabel || 'Copiar';
}, 1200);
} catch (err) {
appendDebugConsoleEntry('error', ['Falha ao copiar log:', err]);
}
});
}
if (clearBtn && clearBtn.dataset.bound !== '1') {
clearBtn.dataset.bound = '1';
clearBtn.addEventListener('click', () => {
debugConsoleState.entries = [];
renderDebugConsoleOutput();
});
}
renderDebugConsoleOutput();
}
function initDebugConsoleCapture() {
if (debugConsoleState.initialized) return;
debugConsoleState.initialized = true;
['log', 'info', 'warn', 'error', 'debug'].forEach((level) => {
console[level] = (...args) => {
originalConsole[level](...args);
appendDebugConsoleEntry(level, args);
};
});
window.addEventListener('error', (event) => {
const location = event?.filename ? `${event.filename}:${event.lineno || 0}` : '';
appendDebugConsoleEntry('error', [event?.message || 'Erro de script', location].filter(Boolean));
});
window.addEventListener('unhandledrejection', (event) => {
const reason = event?.reason instanceof Error
? (event.reason.stack || event.reason.message)
: formatDebugConsoleArg(event?.reason);
appendDebugConsoleEntry('error', ['Promise rejeitada sem tratamento:', reason]);
});
appendDebugConsoleEntry('info', ['Console de depuração inicializado']);
}
initDebugConsoleCapture();
// Verifica preferência global de "não mostrar aviso" (localStorage, sessionStorage, cookie)
function isAvisoSuppressedGlobal() {
const KEY = 'sigaa_nao_mostrar_aviso';
try { if (localStorage.getItem(KEY) === '1') return true; } catch (e) { }
try { if (sessionStorage.getItem(KEY) === '1') return true; } catch (e) { }
try { const re = new RegExp('(?:^|; )' + KEY + '=1(?:;|$)'); if (re.test(document.cookie)) return true; } catch (e) { }
return false;
}
function isSkipScheduleEnabled() {
return localStorage.getItem(STORAGE_SKIP_SCHEDULE) === '1';
}
function setSkipScheduleEnabled(enabled) {
localStorage.setItem(STORAGE_SKIP_SCHEDULE, enabled ? '1' : '0');
}
function isComparisonModeEnabled() {
return localStorage.getItem(STORAGE_COMPARISON_MODE) === '1';
}
function setComparisonModeEnabled(enabled) {
localStorage.setItem(STORAGE_COMPARISON_MODE, enabled ? '1' : '0');
}
function normalizeAppMode(mode) {
const value = String(mode || '').trim().toLowerCase();
return HOME_MODES.has(value) ? value : 'graduacao';
}
function getAppMode() {
return normalizeAppMode(localStorage.getItem(STORAGE_HOME_MODE) || 'graduacao');
}
function setAppMode(mode) {
localStorage.setItem(STORAGE_HOME_MODE, normalizeAppMode(mode));
}
function getAppModeLayout(mode = getAppMode()) {
return HOME_MODE_LAYOUTS[normalizeAppMode(mode)] || HOME_MODE_LAYOUTS.graduacao;
}
function applyHomeModeLayout(mode = getAppMode()) {
const layout = getAppModeLayout(mode);
const homeAviso = document.getElementById('home-aviso');
const listasContainer = document.getElementById('home-listas-container');
const novidadesToggle = document.querySelector('.novidades-toggle');
const panelNov = document.getElementById('tabela-novidades-container');
const panelAtiv = document.getElementById('tabela-atividades-container');
const toggleWrapper = document.getElementById('home-calendar-toggle-wrapper');
const calendarCheckbox = document.getElementById('calendar-view-checkbox');
const normalizedMode = normalizeAppMode(mode);
if (homeAviso) {
if (layout.showHomeAviso && !isAvisoSuppressedGlobal()) {
homeAviso.style.display = '';
} else {
homeAviso.style.display = 'none';
}
}
if (listasContainer) {
listasContainer.style.display = layout.showHomeLists ? '' : 'none';
}
// Controle do Toggle e Visão do Calendário para Graduação vs Responsável vs Técnico
let showCalendarInsteadOfLists = false;
if (normalizedMode === 'responsavel') {
if (toggleWrapper) toggleWrapper.style.display = 'none';
showCalendarInsteadOfLists = true;
} else if (normalizedMode === 'graduacao') {
if (toggleWrapper) toggleWrapper.style.display = isHomeTabActive() ? 'flex' : 'none';
if (calendarCheckbox && calendarCheckbox.checked) {
showCalendarInsteadOfLists = true;
} else {
showCalendarInsteadOfLists = false;
}
} else {
if (toggleWrapper) toggleWrapper.style.display = 'none';
showCalendarInsteadOfLists = false;
}
if (showCalendarInsteadOfLists) {
// Esconde as tabelas e o alternador de novidades
if (novidadesToggle) novidadesToggle.style.display = 'none';
if (panelNov) panelNov.style.display = 'none';
if (panelAtiv) panelAtiv.style.display = 'none';
// Mostra o calendário e renderiza
renderResponsibleCalendar(normalizedMode);
} else {
// Comportamento normal da interface
if (novidadesToggle) {
novidadesToggle.style.display = layout.showToggle && layout.showHomeLists ? '' : 'none';
}
if (panelNov) {
panelNov.style.display = layout.showHomeLists && layout.showNovidades ? '' : 'none';
}
if (panelAtiv) {
panelAtiv.style.display = layout.showHomeLists && layout.showAtividades ? '' : 'none';
}
clearResponsibleCalendar();
}
if (!layout.showHomeLists) {
return;
}
atualizarHomePainelNovidadesAtividades();
}
function clearResponsibleCalendar() {
const container = document.getElementById('responsavel-calendar-container');
const grid = document.getElementById('responsavel-calendar-grid');
if (container) container.style.display = 'none';
if (grid) grid.innerHTML = '';
}
function ajustarAlturaCalendarioResponsavel() {
try {
const form = document.getElementById('sigaa-form');
const dados = document.getElementById('dados-institucionais');
const calendar = document.getElementById('responsavel-calendar-container');
if (!form || !dados || !calendar) return;
if (window.innerWidth < 1040 || !isResponsibleCalendarActive()) {
calendar.style.height = '';
calendar.style.maxHeight = '';
calendar.style.overflow = '';
return;
}
let availableHeight;
if (!document.body.classList.contains('sem-dados')) {
const dadosRect = dados.getBoundingClientRect();
availableHeight = Math.max(180, Math.round(dadosRect.height));
} else if (isHideHomeInputsEnabled()) {
const dadosRect = dados.getBoundingClientRect();
availableHeight = Math.max(120, Math.round(dadosRect.height) - 38);
} else {
const formRect = form.getBoundingClientRect();
const dadosRect = dados.getBoundingClientRect();
const formStyle = window.getComputedStyle(form);
const dadosStyle = window.getComputedStyle(dados);
const formMarginTop = parseFloat(formStyle.marginTop || '0') || 0;
const dadosMarginBottom = parseFloat(dadosStyle.marginBottom || '0') || 0;
const top = formRect.top - formMarginTop;
const bottom = dadosRect.bottom + dadosMarginBottom;
availableHeight = Math.max(120, Math.round(bottom - top)) + 182;
}
calendar.dataset.availableHeight = String(availableHeight);
calendar.style.height = `${availableHeight}px`;
calendar.style.maxHeight = `${availableHeight}px`;
calendar.style.overflow = 'hidden';
return availableHeight;
} catch (e) {
console.warn('Erro ao ajustar altura do calendário responsável:', e);
return 0;
}
}
function getResponsibleCalendarWeeksToRender(availableHeight) {
if (isHideHomeInputsEnabled()) {
return 24;
}
const usableHeight = Math.max(0, Number(availableHeight) || 0);
const headerReserve = 126;
const rowHeight = 92;
const rowGap = 10;
const baseWeeks = 6;
const spaceForGrid = Math.max(0, usableHeight - headerReserve);
const fitWeeks = Math.max(baseWeeks, Math.floor((spaceForGrid + rowGap) / (rowHeight + rowGap)));
return Math.min(10, fitWeeks);
}
let cachedCalendarEvents = null;
let fetchingCalendarEvents = false;
let lastFetchedCurso = null;
function obterCursoDoPerfil() {
try {
const raw = localStorage.getItem(STORAGE_LAST_CONSULTA);
if (!raw) return 'mecatronica';
const data = JSON.parse(raw);
const dados = data.dadosInstitucionais || {};
const curso = dados.Curso || dados.curso || '';
const cursoNormalized = curso.toUpperCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
const temDCDV = cursoNormalized.includes('DCDV');
const temDivinopolis = cursoNormalized.includes('DIVINOPOLIS');
const temBacharelado = cursoNormalized.includes('BACHARELADO');
const temMT = cursoNormalized.includes('MT');
const isComputacao = cursoNormalized.includes('ENGENHARIA DE COMPUTACAO') && temDCDV && temDivinopolis && temBacharelado && temMT;
return isComputacao ? 'computacao' : 'mecatronica';
} catch (e) {
console.warn('Erro ao obter curso do perfil, usando padrão mecatronica:', e);
return 'mecatronica';
}
}
async function fetchCalendarEvents(curso) {
if (lastFetchedCurso === curso && cachedCalendarEvents !== null) {
return cachedCalendarEvents;
}
if (fetchingCalendarEvents) return null;
fetchingCalendarEvents = true;
try {
const url = `${API_BASE}/api/calendario/eventos?curso=${curso}`;
console.log(`📡 Buscando eventos de calendário para ${curso} via ${url}...`);
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
cachedCalendarEvents = data.eventos || [];
lastFetchedCurso = curso;
console.log(`✨ Eventos carregados: ${cachedCalendarEvents.length} itens.`);
} else {
console.warn(`⚠️ Erro ao buscar eventos (status ${response.status})`);
cachedCalendarEvents = [];
}
} catch (e) {
console.error('❌ Falha ao buscar eventos de calendário:', e);
cachedCalendarEvents = [];
} finally {
fetchingCalendarEvents = false;
}
return cachedCalendarEvents;
}
// Helper para encurtar e limpar o nome da disciplina para exibição compacta no calendário
function getCleanDisciplineName(name) {
if (!name) return 'Tarefa';
let clean = name.split(' - ')[0].split('/')[0].trim();
clean = clean.replace(/ENGENHARIA DE/i, 'ENG.')
.replace(/PROGRAMAÇÃO EM/i, 'PROG.')
.replace(/INTELIGÊNCIA ARTIFICIAL/i, 'I.A.')
.replace(/MICROPROCESSADORES E MICROCONTROLADORES/i, 'MICROS')
.replace(/MICROPROCESSADORES/i, 'MICROS')
.replace(/PESQUISA OPERACIONAL/i, 'P. OPER.')
.replace(/COMPILADORES/i, 'COMP.')
.replace(/INTERNET DAS COISAS/i, 'IOT');
// Trunca a no máximo 9 caracteres
if (clean.length > 9) {
clean = clean.substring(0, 8) + '.';
}
return clean;
}
let responsibleCalendarMonthsCount = 3;
let _loadingMoreMonths = false;
function createEmptyCalendarFillerCell() {
const cell = document.createElement('div');
cell.className = 'home-calendar-day is-muted is-empty-filler';
return cell;
}
function createResponsibleCalendarDayCell(date, now, targetMonthStart, targetMonthEnd) {
const cell = document.createElement('div');
cell.className = 'home-calendar-day';
const isSameMonth = date.getMonth() === targetMonthStart.getMonth() && date.getFullYear() === targetMonthStart.getFullYear();
const isToday = date.toDateString() === now.toDateString();
const isNextMonth = date.getTime() > targetMonthEnd.getTime();
const isPrevMonth = date.getTime() < targetMonthStart.getTime();
if (isToday && isSameMonth) {
cell.classList.add('is-today');
}
if (!isSameMonth) {
cell.classList.add('is-muted');
}
if (isNextMonth) {
cell.classList.add('is-next-month');
}
const number = document.createElement('span');
number.className = 'home-calendar-day-number';
number.textContent = String(date.getDate()).padStart(2, '0');
const label = document.createElement('span');
label.className = 'home-calendar-day-label';
if (isToday && isSameMonth) {
label.textContent = 'Hoje';
} else if (isSameMonth) {
label.textContent = 'Dia';
} else if (isPrevMonth) {
label.textContent = 'Mês anterior';
} else {
const monthName = date.toLocaleDateString('pt-BR', { month: 'long' });
label.textContent = monthName.charAt(0).toUpperCase() + monthName.slice(1);
}
cell.appendChild(number);
cell.appendChild(label);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const dateStr = `${year}-${month}-${day}`;
const dayEvents = (cachedCalendarEvents || []).filter(e => e.data === dateStr);
const pendingDeliveries = (atividadesGlobais || [])
.filter(a => a.entregaMarcada && !a.concluida)
.filter(a => {
const aDate = parseAtividadeDate(a.data);
if (!aDate) return false;
const aYear = aDate.getFullYear();
const aMonth = String(aDate.getMonth() + 1).padStart(2, '0');
const aDay = String(aDate.getDate()).padStart(2, '0');
return `${aYear}-${aMonth}-${aDay}` === dateStr;
})
.map(a => ({
data: dateStr,
tipo: 'entrega',
titulo: `${a.disciplina}: ${a.descricao}`,
disciplina: a.disciplina
}));
const allDayEvents = [...dayEvents, ...pendingDeliveries];
if (allDayEvents.length > 0) {
cell.classList.add('has-events');
let primaryType = 'outros';
if (allDayEvents.some(e => e.tipo === 'feriado')) primaryType = 'feriado';
else if (allDayEvents.some(e => e.tipo === 'recesso')) primaryType = 'recesso';
else if (allDayEvents.some(e => e.tipo === 'prova')) primaryType = 'prova';
else if (allDayEvents.some(e => e.tipo === 'entrega')) primaryType = 'entrega';
else if (allDayEvents.some(e => e.tipo === 'inicio-aulas')) primaryType = 'inicio-aulas';
else if (allDayEvents.some(e => e.tipo === 'fim-aulas')) primaryType = 'fim-aulas';
cell.classList.add(`has-event-${primaryType}`);
const dotsContainer = document.createElement('div');
dotsContainer.className = 'home-calendar-day-events';
allDayEvents.forEach(evt => {
const eventTag = document.createElement('span');
eventTag.className = `home-calendar-event-tag home-calendar-event-tag-${evt.tipo}`;
const dot = document.createElement('span');
dot.className = `home-calendar-dot home-calendar-dot-${evt.tipo}`;
const text = document.createElement('span');
text.className = 'home-calendar-event-tag-text';
let shortType = 'Outros';
if (evt.tipo === 'feriado') shortType = 'Feriado';
else if (evt.tipo === 'recesso') shortType = 'Recesso';
else if (evt.tipo === 'prova') shortType = getCleanDisciplineName(evt.disciplina);
else if (evt.tipo === 'entrega') shortType = getCleanDisciplineName(evt.disciplina);
else if (evt.tipo === 'inicio-aulas') shortType = 'Início';
else if (evt.tipo === 'fim-aulas') shortType = 'Fim';
text.textContent = shortType;
eventTag.appendChild(dot);
eventTag.appendChild(text);
dotsContainer.appendChild(eventTag);
});
cell.appendChild(dotsContainer);
const tooltip = document.createElement('div');
tooltip.className = 'home-calendar-tooltip';
allDayEvents.forEach(evt => {
const item = document.createElement('div');
item.className = 'home-calendar-tooltip-item';
const indicator = document.createElement('span');
indicator.className = `home-calendar-tooltip-dot home-calendar-tooltip-dot-${evt.tipo}`;
const text = document.createElement('span');
text.className = 'home-calendar-tooltip-text';
text.textContent = evt.titulo;
item.appendChild(indicator);
item.appendChild(text);
tooltip.appendChild(item);
});
cell.appendChild(tooltip);
}
return cell;
}
function renderSingleResponsibleMonth(mIndex, now, gridContainer) {
const targetMonthStart = new Date(now.getFullYear(), now.getMonth() + mIndex, 1);
const targetMonthEnd = new Date(now.getFullYear(), now.getMonth() + mIndex + 1, 0);
if (mIndex > 0) {
const divider = document.createElement('div');
divider.className = 'home-calendar-month-divider';
const monthName = targetMonthStart.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
divider.innerHTML = `<span>${monthName.charAt(0).toUpperCase() + monthName.slice(1)}</span>`;
gridContainer.appendChild(divider);
}
if (mIndex === 0) {
const firstVisible = new Date(targetMonthStart);
firstVisible.setDate(targetMonthStart.getDate() - targetMonthStart.getDay());
let cur = new Date(firstVisible);
while (cur <= targetMonthEnd || cur.getDay() !== 0) {
gridContainer.appendChild(createResponsibleCalendarDayCell(new Date(cur), now, targetMonthStart, targetMonthEnd));
cur.setDate(cur.getDate() + 1);
}
} else {
const startDow = targetMonthStart.getDay();
for (let i = 0; i < startDow; i++) {
gridContainer.appendChild(createEmptyCalendarFillerCell());
}
const lastDayNum = targetMonthEnd.getDate();
for (let d = 1; d <= lastDayNum; d++) {
const cur = new Date(targetMonthStart.getFullYear(), targetMonthStart.getMonth(), d);
gridContainer.appendChild(createResponsibleCalendarDayCell(cur, now, targetMonthStart, targetMonthEnd));
}
const endDow = targetMonthEnd.getDay();
if (endDow < 6) {
for (let i = 0; i < 6 - endDow; i++) {
gridContainer.appendChild(createEmptyCalendarFillerCell());
}
}
}
}
function loadMoreResponsibleCalendarMonths() {
if (_loadingMoreMonths) return;
_loadingMoreMonths = true;
const grid = document.getElementById('responsavel-calendar-grid');
if (!grid) {
_loadingMoreMonths = false;
return;
}
const now = new Date();
const nextMonthIndex = responsibleCalendarMonthsCount;
responsibleCalendarMonthsCount += 2;
for (let m = nextMonthIndex; m < responsibleCalendarMonthsCount; m++) {
renderSingleResponsibleMonth(m, now, grid);
}
setTimeout(() => {
_loadingMoreMonths = false;
}, 100);
}
function renderResponsibleCalendar(mode = getAppMode()) {
const container = document.getElementById('responsavel-calendar-container');
const grid = document.getElementById('responsavel-calendar-grid');
const title = document.getElementById('responsavel-calendar-title');
if (!container || !grid || !title) return;
const normalizedMode = normalizeAppMode(mode);
const isDesktop = window.innerWidth >= 1040;
const isCalendarActive = normalizedMode === 'responsavel' ||
(normalizedMode === 'graduacao' && document.getElementById('calendar-view-checkbox')?.checked);
if (!isCalendarActive || !isDesktop) {
clearResponsibleCalendar();
return;
}
container.style.display = '';
const now = new Date();
const monthLabel = now.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
title.textContent = monthLabel.charAt(0).toUpperCase() + monthLabel.slice(1);
ajustarAlturaCalendarioResponsavel();
if (!grid.dataset.scrollBound) {
grid.dataset.scrollBound = 'true';
grid.addEventListener('scroll', () => {
if (grid.scrollTop + grid.clientHeight >= grid.scrollHeight - 150) {
loadMoreResponsibleCalendarMonths();
}
}, { passive: true });
}
const curso = obterCursoDoPerfil();
if (cachedCalendarEvents === null || lastFetchedCurso !== curso) {
fetchCalendarEvents(curso).then(events => {
if (events) {
renderResponsibleCalendar(mode);
}
});
}
const savedScrollTop = grid.scrollTop;
grid.innerHTML = '';
for (let m = 0; m < responsibleCalendarMonthsCount; m++) {
renderSingleResponsibleMonth(m, now, grid);
}
if (savedScrollTop > 0) {
grid.scrollTop = savedScrollTop;
}
}
function syncAppModeSelect(mode) {
const select = document.getElementById('home-mode-select');
if (select && select.value !== mode) {
select.value = mode;
}
}
function applyAppMode(mode) {
const normalizedMode = normalizeAppMode(mode);
const panels = document.querySelectorAll('.home-mode-panel');
document.body.dataset.homeMode = normalizedMode;
document.body.dataset.appMode = normalizedMode;
document.documentElement.dataset.appMode = normalizedMode;
panels.forEach((panel) => {
const isActive = panel.dataset.homeMode === normalizedMode;
panel.classList.toggle('is-active', isActive);
panel.hidden = !isActive;
});
syncAppModeSelect(normalizedMode);
if (document.body.classList.contains('sem-dados')) {
const homeAviso = document.getElementById('home-aviso');
if (homeAviso) homeAviso.style.display = 'none';
const listasContainer = document.getElementById('home-listas-container');
if (listasContainer) listasContainer.style.display = 'none';
const dadosInst = document.getElementById('dados-institucionais');
if (dadosInst) dadosInst.style.display = 'none';
const toggleWrapper = document.getElementById('home-calendar-toggle-wrapper');
if (toggleWrapper) toggleWrapper.style.display = 'none';
return;
}
applyHomeModeLayout(normalizedMode);
renderResponsibleCalendar(normalizedMode);
refreshHomeHeightSyncLoop();
refreshResponsibleCalendarSyncLoop();
// Reorder view toggle buttons according to mode (responsavel wants 5-day first)
try { reorderViewToggleButtons(normalizedMode); } catch (e) { /* ignore */ }
}
function reorderViewToggleButtons(mode) {
const group = document.querySelector('.view-toggle-group');
if (!group) return;
// Desired orders
const respOrder = ['semanal', '3dias', 'lista'];
const defaultOrder = ['lista', '3dias', 'semanal'];
const order = normalizeAppMode(mode) === 'responsavel' ? respOrder : defaultOrder;
const buttons = {};
group.querySelectorAll('.view-toggle-btn').forEach(btn => {
const key = btn.dataset.view;
buttons[key] = btn;
});
// Re-append in desired order if buttons exist
order.forEach(key => {
if (buttons[key]) group.appendChild(buttons[key]);
});
// Ensure one button remains active; if none active, activate first in group
const active = group.querySelector('.view-toggle-btn.active');
if (!active) {
const first = group.querySelector('.view-toggle-btn');
if (first) first.classList.add('active');
}
}
function atualizarPainelSemDadosParaModo(modo) {
const normalized = normalizeAppMode(modo);
const eyebrow = document.getElementById('visitor-eyebrow');
const title = document.getElementById('visitor-title');
const description = document.getElementById('visitor-description');
const badgeTitle = document.getElementById('visitor-badge-title');
const badgeDesc = document.getElementById('visitor-badge-desc');
const note = document.getElementById('visitor-note');
if (normalized === 'graduacao') {
if (eyebrow) eyebrow.textContent = 'Acesso Público: Graduação';
if (title) title.textContent = 'Serviços da Graduação';
if (description) description.textContent = 'Acesse documentos e canais de comunicação com a coordenação dos cursos de graduação mesmo sem estar logado.';
if (badgeTitle) badgeTitle.textContent = 'Graduação';
if (badgeDesc) badgeDesc.textContent = 'Faça login para visualizar notas, horários, frequências e o calendário letivo da graduação.';
if (note) note.innerHTML = '<strong>Lembrete:</strong> Após realizar o login com seu CPF e senha de graduação, o painel completo com seus dados institucionais e calendário letivo será carregado.';
} else if (normalized === 'tecnico') {
if (eyebrow) eyebrow.textContent = 'Acesso Público: Técnico';
if (title) title.textContent = 'Serviços do Ensino Técnico';
if (description) description.textContent = 'Acesse informações, requerimentos e canais de comunicação da coordenação do ensino técnico integrado ou subsequente.';
if (badgeTitle) badgeTitle.textContent = 'Técnico';
if (badgeDesc) badgeDesc.textContent = 'Faça login para acompanhar boletins, horários de aula, frequências e o calendário letivo do técnico.';
if (note) note.innerHTML = '<strong>Lembrete:</strong> Após realizar o login com seu CPF e senha de estudante técnico, o painel com diários de classe e calendário do técnico será carregado.';
} else if (normalized === 'responsavel') {
if (eyebrow) eyebrow.textContent = 'Acesso Público: Responsável';
if (title) title.textContent = 'Acompanhamento Acadêmico';
if (description) description.textContent = 'Acesse documentos gerais e orientações para que pais e responsáveis possam acompanhar a rotina escolar dos alunos.';
if (badgeTitle) badgeTitle.textContent = 'Responsável';
if (badgeDesc) badgeDesc.textContent = 'Faça login com seu CPF de responsável cadastrado para visualizar o boletim, faltas e ocorrências do aluno.';
if (note) note.innerHTML = '<strong>Lembrete:</strong> Após realizar o login com seu CPF e senha cadastrados como responsável, a visão resumida de monitoramento do estudante será carregada.';
}
}
function initCalendarToggle() {
const checkbox = document.getElementById('calendar-view-checkbox');
if (!checkbox || checkbox.dataset.bound === '1') return;
checkbox.dataset.bound = '1';
// Recupera o estado anterior do toggle de calendário no modo graduação se existir
const savedState = localStorage.getItem('sigaa_calendar_view_graduacao') === '1';
checkbox.checked = savedState;
checkbox.addEventListener('change', () => {
localStorage.setItem('sigaa_calendar_view_graduacao', checkbox.checked ? '1' : '0');
applyHomeModeLayout(getAppMode());
});
}
function initHomeModeSwitcher() {
const select = document.getElementById('home-mode-select');
if (!select || select.dataset.bound === '1') return;
select.dataset.bound = '1';
select.addEventListener('change', () => {
const modo = select.value;
if (document.body.classList.contains('sem-dados')) {
applyAppMode(modo);
atualizarPainelSemDadosParaModo(modo);
}
});
initCalendarToggle();
const currentMode = getAppMode();
applyAppMode(currentMode);
if (document.body.classList.contains('sem-dados')) {
atualizarPainelSemDadosParaModo(currentMode);
}
}
function getComparisonProfilesContext() {
const profiles = getSavedProfiles();
const selectedUser = getSelectedProfileUser() || (profiles[0]?.user || '');
const compareProfile = profiles.find(profile => profile.user !== selectedUser) || null;
const compareHorarios = compareProfile?.data?.horariosSimplificados || [];
const canCompare = profiles.length >= 2;
const enabled = canCompare && isComparisonModeEnabled() && compareHorarios.length > 0;
return {
enabled,
canCompare,
mainUser: selectedUser,
compareUser: compareProfile?.user || '',
compareHorarios
};
}
function updateComparisonToggleState() {
const toggle = document.getElementById('comparison-mode-toggle');
if (!toggle) return;
const ctx = getComparisonProfilesContext();
if (!ctx.canCompare) {
toggle.checked = false;
toggle.disabled = true;
toggle.title = 'Salve 2 perfis para ativar a comparação';
setComparisonModeEnabled(false);
return;
}
toggle.disabled = false;
toggle.checked = isComparisonModeEnabled();
toggle.title = '';
}
function initComparisonModeToggle() {
const toggle = document.getElementById('comparison-mode-toggle');
if (!toggle || toggle.dataset.bound === '1') return;
toggle.dataset.bound = '1';
toggle.addEventListener('change', () => {
setComparisonModeEnabled(toggle.checked);
preencherTabelaSimplificada(horariosGlobais || []);
atualizarViewAtiva();
});
updateComparisonToggleState();
}
function getSavedProfiles() {
const raw = localStorage.getItem(STORAGE_SAVED_PROFILES);
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed
.filter(item => item && typeof item.user === 'string' && item.user.trim() && item.data)
.map(item => ({
user: item.user.trim(),
data: item.data,
updatedAt: Number(item.updatedAt) || Date.now()
}));
} catch (e) {
console.warn('Falha ao ler perfis salvos:', e);
return [];
}
}
function setSavedProfiles(profiles) {
localStorage.setItem(STORAGE_SAVED_PROFILES, JSON.stringify(profiles.slice(0, MAX_SAVED_PROFILES)));
}
function getSelectedProfileUser() {
const selected = localStorage.getItem(STORAGE_SELECTED_PROFILE);
return selected ? selected.trim() : '';
}
function setSelectedProfileUser(user) {
if (!user) {
localStorage.removeItem(STORAGE_SELECTED_PROFILE);
return;
}
localStorage.setItem(STORAGE_SELECTED_PROFILE, user);
}
function saveConsultaForUser(user, data) {
const normalizedUser = (user || '').trim();
localStorage.setItem(STORAGE_LAST_CONSULTA, JSON.stringify(data));
if (!normalizedUser) return;
const currentProfiles = getSavedProfiles().filter(item => item.user !== normalizedUser);
currentProfiles.unshift({
user: normalizedUser,
data,
updatedAt: Date.now()
});
setSavedProfiles(currentProfiles);
setSelectedProfileUser(normalizedUser);
atualizarSelectPerfisSalvos();
}
function getProfileByUser(user) {
const normalizedUser = (user || '').trim();
if (!normalizedUser) return null;
return getSavedProfiles().find(profile => profile.user === normalizedUser) || null;
}
function escapeHtml(value) {
return String(value || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function normalizeTextForMatch(value) {
return String(value || '')
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toUpperCase()
.trim();
}
function extractSiglaFromCodigoPrefix(disciplina) {
const text = String(disciplina || '').trim();
// Ex.: G05FOFT0.01 - FUNDAMENTOS ... => FOFT
const match = text.match(/^[A-Z]\d{2}([A-Z]{2,6})\d(?:\.\d+)?\s*-/i);
return match ? match[1].toUpperCase() : '';
}
function buildSiglaFromWords(text) {
const stopWords = new Set(['DE', 'DA', 'DO', 'DAS', 'DOS', 'E', 'COM', 'EM', 'PARA']);