-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1543 lines (1316 loc) · 57.5 KB
/
Copy pathscript.js
File metadata and controls
1543 lines (1316 loc) · 57.5 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
// ====================== VARIÁVEIS GLOBAIS ====================== //
let hotelDataSource = []; // Dados originais (vazio até importação)
let filteredData = [];
let currentPage = 1;
const itemsPerPage = 10;
let charts = {};
// ====================== INICIALIZAÇÃO ====================== //
document.addEventListener('DOMContentLoaded', () => {
initializeDateTime();
loadDataFromStorage();
// Atualizar relógio
setInterval(updateTime, 1000);
});
// ====================== CARREGAR DADOS DO LOCALSTORAGE ====================== //
function loadDataFromStorage() {
const savedData = localStorage.getItem('hotelDashboardData');
if (savedData) {
try {
const parsedData = JSON.parse(savedData);
if (parsedData && parsedData.length > 0) {
// Restaurar dados
hotelDataSource = parsedData;
filteredData = [...parsedData];
// Inicializar dashboard com dados carregados
populateFilters();
calculateKPIs();
renderCharts();
renderTable();
initHeaderNavigation();
updateHeaderStats();
// Mostrar informações dos dados
displayDataInfo(parsedData);
// Mostrar botão de limpar
document.getElementById('clearDataBtn').style.display = 'block';
return;
}
} catch (error) {
console.error('Erro ao carregar dados do localStorage:', error);
localStorage.removeItem('hotelDashboardData');
}
}
// Se não houver dados salvos, mostrar estado vazio
showEmptyState();
}
// ====================== SALVAR DADOS NO LOCALSTORAGE ====================== //
function saveDataToStorage(data) {
try {
localStorage.setItem('hotelDashboardData', JSON.stringify(data));
} catch (error) {
console.error('Erro ao salvar dados no localStorage:', error);
}
}
// ====================== LIMPAR DADOS CARREGADOS ====================== //
function clearLoadedData() {
// Abrir modal de confirmação customizado
const modal = document.getElementById('confirmModal');
modal.classList.add('active');
}
// ====================== FECHAR MODAL DE CONFIRMAÇÃO ====================== //
function closeConfirmModal() {
const modal = document.getElementById('confirmModal');
modal.classList.remove('active');
}
// ====================== CONFIRMAR LIMPEZA DE DADOS ====================== //
function confirmClearData() {
// Fechar modal
closeConfirmModal();
// Limpar localStorage
localStorage.removeItem('hotelDashboardData');
// Limpar variáveis
hotelDataSource = [];
filteredData = [];
// Limpar input de arquivo
document.getElementById('fileInput').value = '';
// Ocultar botão de limpar
document.getElementById('clearDataBtn').style.display = 'none';
// Mostrar estado vazio
showEmptyState();
// Resetar filtros
populateFilters();
// Mensagem de confirmação
const fileStatus = document.getElementById('fileStatus');
fileStatus.textContent = '✓ Dados removidos com sucesso!';
fileStatus.className = 'file-status success';
setTimeout(() => {
fileStatus.textContent = '';
fileStatus.className = 'file-status';
}, 3000);
}
// ====================== ESTADO VAZIO ====================== //
function showEmptyState() {
// Mostrar mensagem de estado vazio
const dataInfo = document.getElementById('dataInfo');
dataInfo.innerHTML = `
<div class="empty-state">
<i class="fas fa-file-upload" style="font-size: 48px; color: var(--primary-gradient-start); margin-bottom: 16px;"></i>
<h3>Nenhum dado carregado</h3>
<p>Importe uma planilha Excel ou CSV para começar a visualizar os dados</p>
<p style="margin-top: 8px; font-size: 13px; color: var(--text-secondary);">O sistema detectará automaticamente as categorias e departamentos</p>
</div>
`;
dataInfo.style.display = 'block';
// Limpar KPIs
document.getElementById('avgRating').textContent = '0';
document.getElementById('avgOcupacao').textContent = '0%';
document.getElementById('totalReceita').textContent = 'R$ 0';
document.getElementById('totalHospedes').textContent = '0';
// Ocultar indicadores de tendência
document.getElementById('avgRatingTrend').style.display = 'none';
document.getElementById('avgOcupacaoTrend').style.display = 'none';
document.getElementById('totalReceitaTrend').style.display = 'none';
document.getElementById('totalHospedesTrend').style.display = 'none';
// Limpar tabela
document.getElementById('tableBody').innerHTML = `
<tr>
<td colspan="11" style="text-align: center; padding: 40px; color: var(--text-secondary);">
<i class="fas fa-table" style="font-size: 32px; margin-bottom: 12px; display: block;"></i>
Aguardando importação de dados
</td>
</tr>
`;
// Limpar info de paginação
document.getElementById('pageInfo').textContent = 'Página 0 de 0';
// Limpar header stats
document.getElementById('totalRecords').textContent = '0 Registros';
document.getElementById('totalRevenue').textContent = 'R$ 0';
// Renderizar gráficos vazios
renderEmptyCharts();
}
// ====================== IMPORTAR ARQUIVO ====================== //
function handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
const fileStatus = document.getElementById('fileStatus');
fileStatus.textContent = 'Carregando...';
fileStatus.className = 'file-status';
const reader = new FileReader();
reader.onload = function (e) {
try {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
// Pegar a primeira planilha
const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonData = XLSX.utils.sheet_to_json(firstSheet);
if (jsonData.length === 0) {
throw new Error('Arquivo vazio');
}
// Processar e validar dados
const processedData = processImportedData(jsonData);
if (processedData.length === 0) {
throw new Error('Nenhum dado válido encontrado');
}
// Substituir dados
hotelDataSource = processedData;
filteredData = [...processedData];
// Salvar no localStorage para persistência
saveDataToStorage(processedData);
// Inicializar dashboard pela primeira vez
populateFilters();
calculateKPIs();
if (Object.keys(charts).length === 0) {
renderCharts();
} else {
updateCharts();
}
renderTable();
initHeaderNavigation();
updateHeaderStats();
fileStatus.textContent = `✓ ${processedData.length} registros carregados com sucesso!`;
fileStatus.className = 'file-status success';
// Mostrar informações dos dados importados
displayDataInfo(processedData);
// Mostrar botão de limpar dados
document.getElementById('clearDataBtn').style.display = 'block';
// Limpar mensagem após 5 segundos
setTimeout(() => {
fileStatus.textContent = '';
fileStatus.className = 'file-status';
}, 5000);
} catch (error) {
console.error('Erro ao processar arquivo:', error);
fileStatus.textContent = `✗ Erro: ${error.message}`;
fileStatus.className = 'file-status error';
}
};
reader.onerror = function () {
fileStatus.textContent = '✗ Erro ao ler o arquivo';
fileStatus.className = 'file-status error';
};
// Ler como ArrayBuffer para suportar Excel
reader.readAsArrayBuffer(file);
}
// ====================== PROCESSAR DADOS IMPORTADOS ====================== //
function processImportedData(rawData) {
return rawData.map(row => {
// Mapear colunas do Excel para o formato esperado
// Flexível para aceitar diferentes nomes de colunas
// Função auxiliar para parsing seguro de números
const safeParseFloat = (value) => {
const parsed = parseFloat(value);
return isNaN(parsed) || !isFinite(parsed) ? 0 : parsed;
};
const safeParseInt = (value) => {
const parsed = parseInt(value);
return isNaN(parsed) || !isFinite(parsed) ? 0 : parsed;
};
return {
data: row.data || row.Data || row.DATE || row.date || '',
mes: row.mes || row.Mes || row.MES || row.month || extractMonth(row.data || row.Data),
departamento: row.departamento || row.Departamento || row.DEPARTAMENTO || row.department || '',
categoria: row.categoria || row.Categoria || row.CATEGORIA || row.category || '',
avaliacao: safeParseFloat(row.avaliacao || row.Avaliacao || row.AVALIACAO || row.rating || row.avaliação),
hospedes: safeParseInt(row.hospedes || row.Hospedes || row.HOSPEDES || row.guests || row.hóspedes),
ocupacao: safeParseFloat(row.ocupacao || row.Ocupacao || row.OCUPACAO || row.occupancy || row.ocupação),
receita: safeParseFloat(row.receita || row.Receita || row.RECEITA || row.revenue),
reclamacoes: safeParseInt(row.reclamacoes || row.Reclamacoes || row.RECLAMACOES || row.complaints || row.reclamações),
elogios: safeParseInt(row.elogios || row.Elogios || row.ELOGIOS || row.compliments),
tempoResposta: safeParseFloat(row.tempoResposta || row.TempoResposta || row.TEMPO_RESPOSTA || row.responseTime || row.tempo_resposta)
};
}).filter(row => {
// Validar se tem dados mínimos necessários
return row.departamento && row.avaliacao > 0;
});
}
// ====================== EXTRAIR MÊS DA DATA ====================== //
function extractMonth(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
if (isNaN(date.getTime())) return '';
const months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
return months[date.getMonth()];
}
// ====================== EXIBIR INFORMAÇÕES DOS DADOS ====================== //
function displayDataInfo(data) {
const dataInfo = document.getElementById('dataInfo');
// Extrair informações únicas
const departamentos = [...new Set(data.map(d => d.departamento).filter(d => d))];
const categorias = [...new Set(data.map(d => d.categoria).filter(c => c))];
const meses = [...new Set(data.map(d => d.mes).filter(m => m))];
// Criar HTML informativo
let html = '<h4><i class="fas fa-info-circle"></i> Dados Detectados:</h4>';
// Departamentos detectados
if (departamentos.length > 0) {
html += '<div class="info-item">';
html += `<i class="fas fa-building"></i>`;
html += `<strong>${departamentos.length} Departamento(s):</strong>`;
html += '</div>';
html += '<div class="badge-list">';
departamentos.forEach(dept => {
html += `<span class="mini-badge">${dept}</span>`;
});
html += '</div>';
}
// Categorias detectadas
if (categorias.length > 0) {
html += '<div class="info-item" style="margin-top: 8px;">';
html += `<i class="fas fa-star"></i>`;
html += `<strong>${categorias.length} Categoria(s):</strong>`;
html += '</div>';
html += '<div class="badge-list">';
categorias.forEach(cat => {
html += `<span class="mini-badge">${cat}</span>`;
});
html += '</div>';
}
// Período detectado
if (meses.length > 0) {
html += '<div class="info-item" style="margin-top: 8px;">';
html += `<i class="fas fa-calendar"></i>`;
html += `<strong>Período:</strong> ${meses.length} mês(es)`;
html += '</div>';
}
dataInfo.innerHTML = html;
dataInfo.style.display = 'block';
}
// ====================== DATA E HORA ====================== //
function initializeDateTime() {
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById('currentDate').textContent = new Date().toLocaleDateString('pt-BR', options);
updateTime();
}
function updateTime() {
document.getElementById('currentTime').textContent = new Date().toLocaleTimeString('pt-BR');
}
// ====================== THEME TOGGLE ====================== //
function toggleTheme() {
document.body.classList.toggle('light-theme');
const icon = document.querySelector('.theme-toggle i');
if (document.body.classList.contains('light-theme')) {
icon.className = 'fas fa-sun';
} else {
icon.className = 'fas fa-moon';
}
}
// ====================== HEADER STATS NAVIGATION ====================== //
let currentStatIndex = 0;
const headerStats = [];
function initHeaderNavigation() {
const statsContainer = document.querySelector('.header-stats');
const allStats = statsContainer.querySelectorAll('.header-stat:not(.nav-arrow)');
headerStats.length = 0;
allStats.forEach(stat => headerStats.push(stat));
if (window.innerWidth <= 768) {
updateHeaderStatsVisibility();
}
}
function updateHeaderStatsVisibility() {
if (window.innerWidth > 768) {
headerStats.forEach(stat => stat.style.display = 'flex');
document.querySelectorAll('.nav-arrow').forEach(arrow => arrow.style.display = 'none');
return;
}
headerStats.forEach((stat, index) => {
stat.style.display = index === currentStatIndex ? 'flex' : 'none';
});
document.querySelectorAll('.nav-arrow').forEach(arrow => arrow.style.display = 'flex');
}
function navigateStats(direction) {
currentStatIndex += direction;
if (currentStatIndex < 0) currentStatIndex = headerStats.length - 1;
if (currentStatIndex >= headerStats.length) currentStatIndex = 0;
updateHeaderStatsVisibility();
}
window.addEventListener('resize', () => {
if (headerStats.length > 0) {
updateHeaderStatsVisibility();
}
});
// ====================== DATE PICKER ====================== //
let currentCalendarDate = new Date();
let selectedDate = null;
function toggleDatePicker() {
const modal = document.getElementById('datePickerModal');
modal.classList.toggle('active');
if (modal.classList.contains('active')) {
renderCalendar();
}
}
// ====================== RENDERIZAR CALENDÁRIO ====================== //
function renderCalendar() {
const year = currentCalendarDate.getFullYear();
const month = currentCalendarDate.getMonth();
// Atualizar cabeçalho
const monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
document.getElementById('calendarMonthYear').textContent = `${monthNames[month]} ${year}`;
// Obter primeiro e último dia do mês
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const daysInMonth = lastDay.getDate();
const startDayOfWeek = firstDay.getDay();
// Limpar calendário
const calendarDays = document.getElementById('calendarDays');
calendarDays.innerHTML = '';
// Dias do mês anterior (vazios)
for (let i = 0; i < startDayOfWeek; i++) {
const emptyDay = document.createElement('div');
emptyDay.className = 'calendar-day empty';
calendarDays.appendChild(emptyDay);
}
// Dias do mês atual
const today = new Date();
for (let day = 1; day <= daysInMonth; day++) {
const dayElement = document.createElement('div');
dayElement.className = 'calendar-day';
dayElement.textContent = day;
const currentDate = new Date(year, month, day);
// Marcar dia de hoje
if (currentDate.toDateString() === today.toDateString()) {
dayElement.classList.add('today');
}
// Marcar dia selecionado
if (selectedDate && currentDate.toDateString() === selectedDate.toDateString()) {
dayElement.classList.add('selected');
}
// Adicionar evento de clique
dayElement.onclick = () => selectDate(year, month, day);
calendarDays.appendChild(dayElement);
}
}
// ====================== SELECIONAR DATA NO CALENDÁRIO ====================== //
function selectDate(year, month, day) {
selectedDate = new Date(year, month, day);
renderCalendar();
// Formatar data para o input
const dateString = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
// Aplicar filtro imediatamente
filteredData = hotelDataSource.filter(item => {
const itemDate = new Date(item.data);
return itemDate.toDateString() === selectedDate.toDateString();
});
// Atualizar data exibida no header
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById('currentDate').textContent = selectedDate.toLocaleDateString('pt-BR', options);
// Resetar outros filtros
document.getElementById('filterMonth').value = 'all';
document.getElementById('filterYear').value = 'all';
document.getElementById('mesFilter').value = 'all';
document.getElementById('departamentoFilter').value = 'all';
document.getElementById('categoriaFilter').value = 'all';
currentPage = 1;
calculateKPIs();
updateCharts();
renderTable();
updateHeaderStats();
// Fechar modal após seleção
toggleDatePicker();
}
// ====================== MUDAR MÊS DO CALENDÁRIO ====================== //
function changeMonth(direction) {
currentCalendarDate.setMonth(currentCalendarDate.getMonth() + direction);
renderCalendar();
}
// ====================== IR PARA HOJE ====================== //
function goToToday() {
currentCalendarDate = new Date();
renderCalendar();
}
function applyDateFilter() {
const month = document.getElementById('filterMonth').value;
const year = document.getElementById('filterYear').value;
// Atualizar o calendário para o mês/ano selecionado
if (month !== 'all' && year !== 'all') {
currentCalendarDate = new Date(parseInt(year), parseInt(month) - 1, 1);
} else if (year !== 'all') {
currentCalendarDate = new Date(parseInt(year), currentCalendarDate.getMonth(), 1);
} else if (month !== 'all') {
currentCalendarDate = new Date(currentCalendarDate.getFullYear(), parseInt(month) - 1, 1);
}
filteredData = hotelDataSource.filter(item => {
const itemDate = new Date(item.data);
let monthMatch = true;
let yearMatch = true;
if (month !== 'all') {
const itemMonth = String(itemDate.getMonth() + 1).padStart(2, '0');
monthMatch = itemMonth === month;
}
if (year !== 'all') {
const itemYear = String(itemDate.getFullYear());
yearMatch = itemYear === year;
}
return monthMatch && yearMatch;
});
// Limpar seleção de dia específico
selectedDate = null;
renderCalendar();
// Atualizar filtros principais
document.getElementById('mesFilter').value = 'all';
document.getElementById('departamentoFilter').value = 'all';
document.getElementById('categoriaFilter').value = 'all';
currentPage = 1;
calculateKPIs();
updateCharts();
renderTable();
updateHeaderStats();
}
function resetDateFilter() {
document.getElementById('filterMonth').value = 'all';
document.getElementById('filterYear').value = 'all';
// Limpar seleção de data
selectedDate = null;
currentCalendarDate = new Date();
renderCalendar();
filteredData = [...hotelDataSource];
currentPage = 1;
calculateKPIs();
updateCharts();
renderTable();
updateHeaderStats();
}
// ====================== POPULAR FILTROS ====================== //
function populateFilters() {
// Meses
const meses = [...new Set(hotelDataSource.map(d => d.mes).filter(m => m))];
const mesSelect = document.getElementById('mesFilter');
mesSelect.innerHTML = '<option value="all">Todos os Meses</option>';
meses.forEach(mes => {
const option = document.createElement('option');
option.value = mes;
option.textContent = mes;
mesSelect.appendChild(option);
});
// Departamentos
const departamentos = [...new Set(hotelDataSource.map(d => d.departamento).filter(d => d))];
const deptSelect = document.getElementById('departamentoFilter');
deptSelect.innerHTML = '<option value="all">Todos</option>';
departamentos.forEach(dept => {
const option = document.createElement('option');
option.value = dept;
option.textContent = dept;
deptSelect.appendChild(option);
});
// Categorias
const categorias = [...new Set(hotelDataSource.map(d => d.categoria).filter(c => c))];
const catSelect = document.getElementById('categoriaFilter');
catSelect.innerHTML = '<option value="all">Todas</option>';
categorias.forEach(cat => {
const option = document.createElement('option');
option.value = cat;
option.textContent = cat;
catSelect.appendChild(option);
});
}
// ====================== APLICAR FILTROS ====================== //
function applyFilters() {
const mesFilter = document.getElementById('mesFilter').value;
const deptFilter = document.getElementById('departamentoFilter').value;
const catFilter = document.getElementById('categoriaFilter').value;
filteredData = hotelDataSource.filter(item => {
return (mesFilter === 'all' || item.mes === mesFilter) &&
(deptFilter === 'all' || item.departamento === deptFilter) &&
(catFilter === 'all' || item.categoria === catFilter);
});
currentPage = 1;
calculateKPIs();
updateCharts();
renderTable();
updateHeaderStats();
}
function resetFilters() {
document.getElementById('mesFilter').value = 'all';
document.getElementById('departamentoFilter').value = 'all';
document.getElementById('categoriaFilter').value = 'all';
applyFilters();
}
// ====================== RENDERIZAR GRÁFICOS VAZIOS ====================== //
function renderEmptyCharts() {
const chartIds = ['qualidadeChart', 'departamentoChart', 'ocupacaoReceitaChart', 'feedbackChart'];
chartIds.forEach(chartId => {
const ctx = document.getElementById(chartId).getContext('2d');
if (charts[chartId]) {
charts[chartId].destroy();
}
charts[chartId] = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Sem dados',
data: [],
borderColor: 'rgba(102, 126, 234, 0.3)',
backgroundColor: 'rgba(102, 126, 234, 0.1)'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: { enabled: false }
},
scales: {
y: { display: false },
x: { display: false }
}
}
});
});
}
// ====================== CALCULAR KPIs ====================== //
function calculateKPIs() {
if (filteredData.length === 0) {
document.getElementById('avgRating').textContent = '0';
document.getElementById('avgOcupacao').textContent = '0%';
document.getElementById('totalReceita').textContent = 'R$ 0';
document.getElementById('totalHospedes').textContent = '0';
// Ocultar indicadores de tendência quando não há dados
document.getElementById('avgRatingTrend').style.display = 'none';
document.getElementById('avgOcupacaoTrend').style.display = 'none';
document.getElementById('totalReceitaTrend').style.display = 'none';
document.getElementById('totalHospedesTrend').style.display = 'none';
return;
}
const avgRating = (filteredData.reduce((acc, d) => acc + d.avaliacao, 0) / filteredData.length).toFixed(1);
const avgOcupacao = (filteredData.reduce((acc, d) => acc + d.ocupacao, 0) / filteredData.length).toFixed(0);
const totalReceita = filteredData.reduce((acc, d) => acc + d.receita, 0);
const totalHospedes = filteredData.reduce((acc, d) => acc + d.hospedes, 0);
document.getElementById('avgRating').textContent = avgRating;
document.getElementById('avgOcupacao').textContent = avgOcupacao + '%';
document.getElementById('totalReceita').textContent = 'R$ ' + totalReceita.toLocaleString('pt-BR');
document.getElementById('totalHospedes').textContent = totalHospedes.toLocaleString('pt-BR');
// Calcular tendências
calculateTrends();
}
// ====================== CALCULAR TENDÊNCIAS ====================== //
function calculateTrends() {
// Agrupar dados por mês
const mesesUnicos = [...new Set(hotelDataSource.map(d => d.mes).filter(m => m))];
// Se houver menos de 2 meses, não é possível calcular tendência
if (mesesUnicos.length < 2) {
document.getElementById('avgRatingTrend').style.display = 'none';
document.getElementById('avgOcupacaoTrend').style.display = 'none';
document.getElementById('totalReceitaTrend').style.display = 'none';
document.getElementById('totalHospedesTrend').style.display = 'none';
return;
}
// Definir ordem dos meses
const ordemMeses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
// Ordenar meses disponíveis
const mesesOrdenados = mesesUnicos.sort((a, b) =>
ordemMeses.indexOf(a) - ordemMeses.indexOf(b)
);
// Pegar últimos 2 meses
const mesAtual = mesesOrdenados[mesesOrdenados.length - 1];
const mesAnterior = mesesOrdenados[mesesOrdenados.length - 2];
// Dados do mês atual
const dadosAtual = hotelDataSource.filter(d => d.mes === mesAtual);
const dadosAnterior = hotelDataSource.filter(d => d.mes === mesAnterior);
// Calcular médias do mês atual
const avgRatingAtual = dadosAtual.reduce((acc, d) => acc + d.avaliacao, 0) / dadosAtual.length;
const avgOcupacaoAtual = dadosAtual.reduce((acc, d) => acc + d.ocupacao, 0) / dadosAtual.length;
const receitaAtual = dadosAtual.reduce((acc, d) => acc + d.receita, 0);
const hospedesAtual = dadosAtual.reduce((acc, d) => acc + d.hospedes, 0);
// Calcular médias do mês anterior
const avgRatingAnterior = dadosAnterior.reduce((acc, d) => acc + d.avaliacao, 0) / dadosAnterior.length;
const avgOcupacaoAnterior = dadosAnterior.reduce((acc, d) => acc + d.ocupacao, 0) / dadosAnterior.length;
const receitaAnterior = dadosAnterior.reduce((acc, d) => acc + d.receita, 0);
const hospedesAnterior = dadosAnterior.reduce((acc, d) => acc + d.hospedes, 0);
// Calcular variações percentuais
const variacaoRating = ((avgRatingAtual - avgRatingAnterior) / avgRatingAnterior * 100);
const variacaoOcupacao = ((avgOcupacaoAtual - avgOcupacaoAnterior) / avgOcupacaoAnterior * 100);
const variacaoReceita = ((receitaAtual - receitaAnterior) / receitaAnterior * 100);
const variacaoHospedes = ((hospedesAtual - hospedesAnterior) / hospedesAnterior * 100);
// Atualizar indicadores de tendência
updateTrendIndicator('avgRatingTrend', variacaoRating);
updateTrendIndicator('avgOcupacaoTrend', variacaoOcupacao);
updateTrendIndicator('totalReceitaTrend', variacaoReceita);
updateTrendIndicator('totalHospedesTrend', variacaoHospedes);
}
// ====================== ATUALIZAR INDICADOR DE TENDÊNCIA ====================== //
function updateTrendIndicator(elementId, variacao) {
const element = document.getElementById(elementId);
if (isNaN(variacao) || !isFinite(variacao)) {
element.style.display = 'none';
return;
}
const isPositive = variacao >= 0;
const valorAbsoluto = Math.abs(variacao).toFixed(1);
// Atualizar classe e ícone
element.className = isPositive ? 'kpi-trend up' : 'kpi-trend down';
element.innerHTML = `<i class="fas fa-arrow-${isPositive ? 'up' : 'down'}"></i> ${isPositive ? '+' : ''}${valorAbsoluto}%`;
element.style.display = 'flex';
}
// ====================== OBTER MESES ORDENADOS ====================== //
function getMesesOrdenados(dataSource) {
const ordemMeses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
// Extrair meses únicos dos dados
const mesesUnicos = [...new Set(dataSource.map(d => d.mes).filter(m => m))];
// Ordenar pelos meses do ano
return mesesUnicos.sort((a, b) => ordemMeses.indexOf(a) - ordemMeses.indexOf(b));
}
// ====================== RENDERIZAR GRÁFICOS ====================== //
function renderCharts() {
// Obter meses reais dos dados
const mesesOrdenados = getMesesOrdenados(filteredData);
// Se não houver dados, não renderizar
if (mesesOrdenados.length === 0) {
return;
}
// Gráfico 1: Evolução da Qualidade
const qualidadeCtx = document.getElementById('qualidadeChart').getContext('2d');
const qualidadePorMes = mesesOrdenados.map(mes => {
const dados = filteredData.filter(d => d.mes === mes);
return dados.length ? (dados.reduce((acc, d) => acc + d.avaliacao, 0) / dados.length).toFixed(2) : 0;
});
charts.qualidadeChart = new Chart(qualidadeCtx, {
type: 'line',
data: {
labels: mesesOrdenados,
datasets: [{
label: 'Avaliação Média',
data: qualidadePorMes,
borderColor: '#667eea',
backgroundColor: 'rgba(102, 126, 234, 0.1)',
borderWidth: 3,
tension: 0.4,
fill: true,
pointRadius: 6,
pointHoverRadius: 8,
pointBackgroundColor: '#667eea',
pointBorderColor: '#fff',
pointBorderWidth: 2
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: true, labels: { color: getComputedStyle(document.body).getPropertyValue('--text-primary'), font: { size: 11 } } },
tooltip: { mode: 'index', intersect: false }
},
scales: {
y: {
beginAtZero: true,
max: 5,
ticks: { color: getComputedStyle(document.body).getPropertyValue('--text-secondary') },
grid: { color: getComputedStyle(document.body).getPropertyValue('--border-color') }
},
x: {
ticks: { color: getComputedStyle(document.body).getPropertyValue('--text-secondary') },
grid: { color: getComputedStyle(document.body).getPropertyValue('--border-color') }
}
}
}
});
// Gráfico 2: Distribuição por Departamento
const deptCtx = document.getElementById('departamentoChart').getContext('2d');
const departamentos = [...new Set(filteredData.map(d => d.departamento))];
const countPorDept = departamentos.map(dept =>
filteredData.filter(d => d.departamento === dept).length
);
// Gerar cores dinamicamente baseado na quantidade de departamentos
const coresPaleta = [
'rgba(102, 126, 234, 0.8)',
'rgba(245, 87, 108, 0.8)',
'rgba(79, 172, 254, 0.8)',
'rgba(67, 233, 123, 0.8)',
'rgba(139, 92, 246, 0.8)',
'rgba(245, 158, 11, 0.8)',
'rgba(236, 72, 153, 0.8)',
'rgba(14, 165, 233, 0.8)',
'rgba(132, 204, 22, 0.8)',
'rgba(168, 85, 247, 0.8)'
];
const coresDepartamentos = departamentos.map((_, i) => coresPaleta[i % coresPaleta.length]);
charts.departamentoChart = new Chart(deptCtx, {
type: 'doughnut',
data: {
labels: departamentos,
datasets: [{
data: countPorDept,
backgroundColor: coresDepartamentos,
borderColor: getComputedStyle(document.body).getPropertyValue('--bg-card'),
borderWidth: 4,
hoverOffset: 15,
spacing: 2,
borderRadius: 8
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
cutout: '65%',
plugins: {
legend: {
position: 'bottom',
labels: {
color: getComputedStyle(document.body).getPropertyValue('--text-primary'),
padding: 12,
font: { size: 11, weight: '500' },
usePointStyle: true,
pointStyle: 'circle'
}
},
tooltip: {
backgroundColor: getComputedStyle(document.body).getPropertyValue('--bg-secondary'),
titleColor: getComputedStyle(document.body).getPropertyValue('--text-primary'),
bodyColor: getComputedStyle(document.body).getPropertyValue('--text-secondary'),
borderColor: getComputedStyle(document.body).getPropertyValue('--border-color'),
borderWidth: 1,
padding: 12,
displayColors: true,
callbacks: {
label: function (context) {
const label = context.label || '';
const value = context.parsed || 0;
const total = context.dataset.data.reduce((a, b) => a + b, 0);
const percentage = ((value / total) * 100).toFixed(1);
return `${label}: ${value} (${percentage}%)`;
}
}
}
},
animation: {
animateRotate: true,
animateScale: true
}
}
});
// Gráfico 3: Ocupação vs Receita
const ocupacaoReceitaCtx = document.getElementById('ocupacaoReceitaChart').getContext('2d');
const ocupacaoPorMes = mesesOrdenados.map(mes => {
const dados = filteredData.filter(d => d.mes === mes);
return dados.length ? (dados.reduce((acc, d) => acc + d.ocupacao, 0) / dados.length).toFixed(0) : 0;
});
const receitaPorMes = mesesOrdenados.map(mes => {
const dados = filteredData.filter(d => d.mes === mes);
return dados.reduce((acc, d) => acc + d.receita, 0) / 1000;
});
charts.ocupacaoReceitaChart = new Chart(ocupacaoReceitaCtx, {
type: 'bar',
data: {
labels: mesesOrdenados,
datasets: [
{
label: 'Ocupação %',
data: ocupacaoPorMes,
backgroundColor: 'rgba(79, 172, 254, 0.7)',
borderColor: '#4facfe',
borderWidth: 2,
yAxisID: 'y'
},
{
label: 'Receita (R$ mil)',
data: receitaPorMes,
backgroundColor: 'rgba(67, 233, 123, 0.7)',
borderColor: '#43e97b',
borderWidth: 2,
yAxisID: 'y1'
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { labels: { color: getComputedStyle(document.body).getPropertyValue('--text-primary'), font: { size: 11 } } }
},
scales: {
y: {
type: 'linear',
position: 'left',
ticks: { color: getComputedStyle(document.body).getPropertyValue('--text-secondary') },
grid: { color: getComputedStyle(document.body).getPropertyValue('--border-color') }
},
y1: {
type: 'linear',
position: 'right',
ticks: { color: getComputedStyle(document.body).getPropertyValue('--text-secondary') },
grid: { drawOnChartArea: false }
},
x: {
ticks: { color: getComputedStyle(document.body).getPropertyValue('--text-secondary') },
grid: { color: getComputedStyle(document.body).getPropertyValue('--border-color') }
}
}
}
});
// Gráfico 4: Reclamações vs Elogios
const feedbackCtx = document.getElementById('feedbackChart').getContext('2d');
const reclamacoesPorMes = mesesOrdenados.map(mes => {
const dados = filteredData.filter(d => d.mes === mes);
return dados.reduce((acc, d) => acc + d.reclamacoes, 0);
});
const elogiosPorMes = mesesOrdenados.map(mes => {
const dados = filteredData.filter(d => d.mes === mes);
return dados.reduce((acc, d) => acc + d.elogios, 0);
});