File size: 51,720 Bytes
9a95520 43f9d25 8fe104d 43f9d25 85ac771 9a95520 f6a37a3 8fe104d f6a37a3 9a95520 8fe104d ef562b8 9a95520 f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 9a95520 8fe104d f6a37a3 8fe104d f6a37a3 8fe104d dbc7314 f6a37a3 9a95520 8fe104d 9a95520 8fe104d 9a95520 85ac771 f6a37a3 8fe104d 9a95520 ef562b8 9a95520 8fe104d 9a95520 8fe104d f6a37a3 9a95520 8fe104d dbc7314 9a95520 dbc7314 8fe104d dbc7314 9a95520 f6a37a3 9a95520 f6a37a3 8fe104d f6a37a3 9a95520 ef562b8 8fe104d ef562b8 8fe104d ef562b8 8fe104d dbc7314 9a95520 85ac771 9a95520 85ac771 9a95520 ef562b8 9a95520 f6a37a3 9a95520 e428acb 9a95520 85ac771 9a95520 e428acb 85ac771 9a95520 dbc7314 8d2f60f 9a95520 f6a37a3 9a95520 f6a37a3 9a95520 f6a37a3 9a95520 8d2f60f 9a95520 3a47562 85ac771 3a47562 85ac771 3a47562 9a95520 43f9d25 8fe104d ef562b8 8fe104d f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 8fe104d dbc7314 8fe104d dbc7314 9a95520 f6a37a3 9a95520 64281e9 9a95520 64281e9 9a95520 64281e9 9a95520 64281e9 9a95520 64281e9 9a95520 64281e9 9a95520 f6a37a3 9a95520 f6a37a3 9a95520 f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 dbc7314 8fe104d dbc7314 8fe104d dbc7314 f6a37a3 9a95520 f6a37a3 9a95520 f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 9a95520 f6a37a3 9a95520 f6a37a3 8fe104d f6a37a3 8fe104d f6a37a3 9a95520 f6a37a3 9a95520 ef562b8 9a95520 8fe104d 9a95520 ef562b8 9a95520 dbc7314 8fe104d 9a95520 ef562b8 85ac771 ef562b8 85ac771 ef562b8 85ac771 ef562b8 85ac771 ef562b8 85ac771 ef562b8 9a95520 8fe104d 9a95520 f6a37a3 ef562b8 9a95520 f6a37a3 8fe104d f6a37a3 9a95520 | 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 1001 1002 1003 1004 1005 1006 1007 1008 | <!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Permissions-Policy" content="interest-cohort=()">
<title>PAREI v1.2</title>
<!-- Remove Tailwind CDN - will be handled by build process -->
<script src="https://apis.google.com/js/api.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* Custom scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* Filter styles */
.filter-group select[multiple] {
min-height: 150px;
border: 2px solid #4ade80 !important; /* green-400 */
border-radius: 0.375rem;
}
.filter-group select[multiple] option {
padding: 4px 8px;
}
/* Mobile filter panel */
.mobile-filter-panel {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: white;
z-index: 50;
overflow-y: auto;
padding: 1rem;
transform: translateX(-100%);
transition: transform 0.3s ease;
}
.mobile-filter-panel.active {
transform: translateX(0);
}
/* Animation for loading */
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.animate-spin {
animation: spin 1s linear infinite;
}
/* Header checkbox styling */
th div {
display: flex;
align-items: center;
gap: 8px;
min-height: 40px;
}
/* Table row styling */
tbody tr {
border-bottom: 1px solid #e5f5e0; /* Light green border */
}
tbody tr:hover {
background-color: #f0fff0; /* Very light green on hover */
}
tbody td {
border-right: 1px solid #e5f5e0; /* Light green vertical lines */
}
tbody td:last-child {
border-right: none; /* Remove border from last cell */
}
</style>
</head>
<body class="bg-gray-100 min-h-screen flex">
<!-- Filter Panel -->
<div class="w-96 bg-white shadow-lg p-6 overflow-y-auto hidden md:block relative" style="max-height: calc(100vh - 2rem);">
<div class="absolute bottom-0 left-0 right-0 h-4 bg-gradient-to-t from-green-300 to-green-100"></div>
<div class="flex items-center justify-between mb-4">
<h2 class="text-lg font-semibold text-gray-700">Filtros</h2>
<button id="clearFilters" class="text-green-500 hover:text-green-700 text-sm">
Limpar tudo
</button>
</div>
<div id="filterContainer" class="space-y-6">
<div class="filter-group flex-1 min-h-0">
<h3 class="text-sm font-medium text-gray-700 mb-2">ÁREA</h3>
<select id="areaFilter" multiple class="w-full h-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
<!-- Options will be added dynamically -->
</select>
</div>
<div class="filter-group flex-1 min-h-0">
<h3 class="text-sm font-medium text-gray-700 mb-2">RESPONSÁVEL</h3>
<select id="responsavelFilter" multiple class="w-full h-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
<!-- Options will be added dynamically -->
</select>
</div>
<div class="filter-group flex-1 min-h-0">
<h3 class="text-sm font-medium text-gray-700 mb-2">ATUALIZADOR 1 (EMAIL)</h3>
<select id="atualizador1Filter" multiple class="w-full h-full border-gray-300 rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm">
<!-- Options will be added dynamically -->
</select>
</div>
</div>
</div>
<!-- Main Content -->
<div class="flex-1">
<div class="container mx-auto px-4 py-8">
<div class="bg-white rounded-xl shadow-lg overflow-hidden">
<!-- Header -->
<div class="bg-gradient-to-r from-green-500 to-green-300 px-6 py-6 flex flex-col md:flex-row justify-between items-center" style="min-height: 96px">
<div class="flex items-center mb-4 md:mb-0">
<i class="fas fa-database text-white text-2xl mr-3"></i>
<h1 class="text-2xl font-bold text-white">PAREI v1.2</h1>
</div>
<div class="flex items-center space-x-3">
<button id="authButton" class="bg-gradient-to-r from-yellow-300 to-yellow-400 hover:from-yellow-400 hover:to-yellow-500 text-white px-4 py-2 rounded-lg flex items-center transition duration-200">
<i class="fas fa-sign-in-alt mr-2"></i> Login Google
</button>
<div id="authStatus" class="text-sm text-white hidden">
<i class="fas fa-circle text-green-400 mr-1"></i>
<span>Conectado</span>
</div>
<button id="toggleFilters" class="md:hidden bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-2 rounded-lg flex items-center transition duration-200">
<i class="fas fa-filter mr-2"></i> Filtros
</button>
<button id="refreshBtn" class="bg-gradient-to-r from-green-300 to-green-400 hover:from-green-400 hover:to-green-500 text-white px-4 py-2 rounded-lg flex items-center transition duration-200">
<i class="fas fa-sync-alt mr-2"></i> Atualizar
</button>
<button id="exportExcelBtn" class="bg-gradient-to-r from-blue-300 to-blue-400 hover:from-blue-400 hover:to-blue-500 text-white px-4 py-2 rounded-lg flex items-center transition duration-200">
<i class="fas fa-file-excel mr-2"></i> Exportar Excel
</button>
<div class="relative">
<input type="text" id="searchInput" placeholder="Pesquisar..." class="pl-10 pr-4 py-2 rounded-lg border-0 focus:ring-2 focus:ring-green-400">
<i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
</div>
</div>
</div>
<!-- Loading State -->
<div id="loading" class="p-8 flex flex-col items-center justify-center">
<div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-green-400 mb-4"></div>
<p class="text-gray-600">Carregando dados... Por favor aguarde</p>
</div>
<!-- Data Table -->
<div id="dataContainer" class="hidden overflow-x-auto">
<div class="overflow-auto" style="max-height: calc(100vh - 250px);">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50 sticky top-0 z-10">
<tr id="tableHeaders">
<!-- Headers will be inserted here by JavaScript -->
</tr>
</thead>
<tbody id="tableBody" class="bg-white divide-y divide-gray-200">
<!-- Data will be inserted here by JavaScript -->
</tbody>
</table>
</div>
<!-- Pagination -->
<div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
<div class="flex-1 flex justify-between sm:hidden">
<button id="prevPageMobile" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
Anterior
</button>
<button id="nextPageMobile" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
Próxima
</button>
</div>
<div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
<div>
<p id="paginationInfo" class="text-sm text-gray-700"></p>
</div>
<div>
<nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
<button id="prevPage" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
<span class="sr-only">Anterior</span>
<i class="fas fa-chevron-left"></i>
</button>
<div id="pageNumbers" class="flex">
<!-- Page numbers will be inserted here -->
</div>
<button id="nextPage" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
<span class="sr-only">Próxima</span>
<i class="fas fa-chevron-right"></i>
</button>
</nav>
</div>
</div>
</div>
</div>
<!-- Error State -->
<div id="errorContainer" class="hidden p-8 text-center bg-red-50 rounded-lg border border-red-200 mx-6 my-4">
<i class="fas fa-exclamation-triangle text-red-500 text-5xl mb-4"></i>
<h2 class="text-2xl font-bold text-red-600 mb-2">ERRO AO CARREGAR DADOS</h2>
<p class="text-gray-700 mb-6" id="errorMessage">Erro ao carregar dados após aplicar filtros. Por favor verifique:</p>
<ul class="text-left max-w-md mx-auto text-gray-600 mb-6 space-y-2">
<li class="flex items-start">
<i class="fas fa-check-circle text-red-500 mt-1 mr-2"></i>
Se os filtros aplicados são válidos
</li>
<li class="flex items-start">
<i class="fas fa-check-circle text-red-500 mt-1 mr-2"></i>
Se há dados correspondentes aos filtros
</li>
<li class="flex items-start">
<i class="fas fa-check-circle text-red-500 mt-1 mr-2"></i>
Sua conexão com a internet
</li>
<li class="flex items-start">
<i class="fas fa-check-circle text-red-500 mt-1 mr-2"></i>
A URL da planilha está correta
</li>
</ul>
<button id="retryBtn" class="bg-gradient-to-r from-green-300 to-green-400 hover:from-green-400 hover:to-green-500 text-white px-8 py-3 rounded-lg transition duration-200 font-medium">
<i class="fas fa-sync-alt mr-2"></i> Tentar novamente
</button>
</div>
</div>
<!-- Footer -->
<div class="mt-6 text-center text-gray-500 text-xs bg-white py-2 rounded-lg border border-gray-200">
<div class="flex flex-wrap items-center justify-center gap-2 px-2">
<span>Sistema para importação de dados do Google Sheets</span>
<span class="hidden sm:inline">•</span>
<span class="flex items-center">
<span class="mr-1">Planilha:</span>
<input type="text" id="sheetUrl" placeholder="URL da planilha" class="w-40 px-2 py-1 border rounded text-xs">
<button id="updateSheetBtn" class="ml-1 bg-gray-200 hover:bg-gray-300 text-gray-700 px-2 py-1 rounded text-xs">Atualizar</button>
</span>
<span class="hidden sm:inline">•</span>
<span>Última atualização: <span id="lastUpdated"></span></span>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Configuration
const API_KEY = 'AIzaSyB4wGkF4hP8QYh4wXZQ3Q3Q3Q3Q3Q3Q3Q'; // Note: In production, use a backend service to hide this key
const CLIENT_ID = 'YOUR_CLIENT_ID.apps.googleusercontent.com'; // Replace with your actual client ID
const SCOPES = 'https://www.googleapis.com/auth/spreadsheets';
let SHEET_ID = '1hs8LtsybSCLIsfO-4G-EtZpBrIzf339PeuhdjOU5UeI';
let isSignedIn = false;
const FIXED_HEADERS = [
'ID Exclusiva', 'CENTRO DE TRABALHO', 'ORDEM', 'LOCAL DA INSTALAÇÃO(TAG)',
'DESCRIÇÃO LOCAL DA INSTALAÇÃO', 'NOME DA TAREFA', 'DURAÇÃO', 'INÍCIO',
'TÉRMINO', 'RESPONSÁVEL', 'PREDECESSORAS', 'SUCESSORAS', 'CALENDÁRIO DA TAREFA',
'NOME DOS RECURSOS', 'MODO', 'ID EXCLUSIVA', 'RESUMO(SIM/NÃO)', 'TIPO',
'TIPO DE RESTRIÇÃO', 'INÍCIO DA LINHA DE BASE', 'TÉRMINO DA LINHA DE BASE',
'TRABALO', 'QUANTIDADE DE RECURSOS', 'DISCIPLINA', 'ÁREA', 'SUBAREA',
'ATUALIZADOR 1(EMAIL)', 'ATUALIZADOR 2 (EMAIL)', 'ATUALIZADOR 3 (EMAIL)',
'ATUALIZADOR 4(EMAIL)', 'ATUALIZADOR 5 (EMAIL)', 'CURVA ESCOPO GERAL',
'CURVA ANDAIME', 'CURVA ESPECIAL', 'CURVA PROJETO', 'CAMINHO CRÍTICO(SIM/NÃO)',
'TIPO DE PARADA (PP,PE,PG)', 'AVANÇO'
];
const ROWS_PER_PAGE = 15;
// DOM Elements
const loadingElement = document.getElementById('loading');
const dataContainer = document.getElementById('dataContainer');
const errorContainer = document.getElementById('errorContainer');
const errorMessage = document.getElementById('errorMessage');
const tableHeaders = document.getElementById('tableHeaders');
const tableBody = document.getElementById('tableBody');
const refreshBtn = document.getElementById('refreshBtn');
const retryBtn = document.getElementById('retryBtn');
const searchInput = document.getElementById('searchInput');
const prevPage = document.getElementById('prevPage');
const nextPage = document.getElementById('nextPage');
const prevPageMobile = document.getElementById('prevPageMobile');
const nextPageMobile = document.getElementById('nextPageMobile');
const pageNumbers = document.getElementById('pageNumbers');
const paginationInfo = document.getElementById('paginationInfo');
const lastUpdated = document.getElementById('lastUpdated');
// State variables
let allData = [];
let filteredData = [];
let currentPage = 1;
let totalPages = 1;
let headers = [];
let savedData = [];
let activeFilters = {};
// Initialize the app
init();
// Move handleAuthClick to be accessible globally
function handleAuthClick() {
if (isSignedIn) {
gapi.auth2.getAuthInstance().signOut();
} else {
gapi.auth2.getAuthInstance().signIn();
}
}
function init() {
updateLastUpdated();
fetchData();
setupEventListeners();
// Load the Google API client and initialize it
gapi.load('client:auth2', initClient);
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
scope: SCOPES,
discoveryDocs: ["https://sheets.googleapis.com/$discovery/rest?version=v4"]
}).then(function() {
// Listen for sign-in state changes
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
}, function(error) {
console.error('Error initializing Google API client:', error);
});
}
function updateSigninStatus(isSignedInNow) {
isSignedIn = isSignedInNow;
const authButton = document.getElementById('authButton');
const authStatus = document.getElementById('authStatus');
if (isSignedInNow) {
authButton.innerHTML = '<i class="fas fa-sign-out-alt mr-2"></i> Logout Google';
authStatus.classList.remove('hidden');
} else {
authButton.innerHTML = '<i class="fas fa-sign-in-alt mr-2"></i> Login Google';
authStatus.classList.add('hidden');
}
}
// Load saved sheet ID if exists
const savedSheetId = localStorage.getItem('sheetId');
if (savedSheetId) {
document.getElementById('sheetUrl').value = `https://docs.google.com/spreadsheets/d/${savedSheetId}/edit?usp=sharing`;
SHEET_ID = savedSheetId;
}
// Setup auth button click handler - moved outside init()
// Setup auth button click handler
document.getElementById('authButton').addEventListener('click', handleAuthClick);
// Setup config save button
// Update sheet button
document.getElementById('updateSheetBtn').addEventListener('click', function() {
const url = document.getElementById('sheetUrl').value;
const sheetIdMatch = url.match(/https:\/\/docs\.google\.com\/spreadsheets\/d\/([a-zA-Z0-9-_]+)\/edit/);
if (sheetIdMatch && sheetIdMatch[1]) {
SHEET_ID = sheetIdMatch[1];
localStorage.setItem('sheetId', SHEET_ID);
alert('Planilha atualizada com sucesso!\n\nID da Planilha: ' + SHEET_ID);
fetchData(); // Refresh data with new sheet ID
} else {
alert('URL inválida. Por favor, verifique se:\n\n1. A URL começa com https://docs.google.com/spreadsheets/d/\n2. Contém /edit no final\n3. A planilha está compartilhada publicamente');
}
});
// Save configuration button
document.getElementById('saveConfig').addEventListener('click', function() {
const url = document.getElementById('sheetUrl').value;
const sheetIdMatch = url.match(/https:\/\/docs\.google\.com\/spreadsheets\/d\/([a-zA-Z0-9-_]+)\/edit/);
if (sheetIdMatch && sheetIdMatch[1]) {
SHEET_ID = sheetIdMatch[1];
localStorage.setItem('sheetId', SHEET_ID);
alert('Configuração salva com sucesso!\n\nID da Planilha: ' + SHEET_ID);
fetchData(); // Refresh data with new sheet ID
} else {
alert('URL inválida. Por favor, verifique se:\n\n1. A URL começa com https://docs.google.com/spreadsheets/d/\n2. Contém /edit no final\n3. A planilha está compartilhada publicamente');
}
});
}
// Save data button
document.getElementById('saveDataBtn').addEventListener('click', function() {
if (allData.length === 0) {
alert('Nenhum dado para salvar. Por favor, importe os dados primeiro.');
return;
}
savedData = [...allData];
localStorage.setItem('savedData', JSON.stringify(savedData));
alert('Dados salvos localmente com sucesso!');
});
function updateLastUpdated() {
const now = new Date();
lastUpdated.textContent = now.toLocaleString('pt-BR');
}
async function saveProgressToGoogleSheets(rowId, newValue) {
if (!isSignedIn) {
alert('Por favor, faça login no Google primeiro.');
return;
}
try {
// Get the row index (add +2 because Sheets start at 1 and header is row 1)
const rowIndex = rowId + 1;
// Get the column index for "AVANÇO"
const progressColIndex = headers.indexOf('AVANÇO') + 1;
const columnLetter = getColumnLetter(progressColIndex);
const response = await gapi.client.sheets.spreadsheets.values.update({
spreadsheetId: SHEET_ID,
range: `Sheet1!${columnLetter}${rowIndex}`,
valueInputOption: 'USER_ENTERED',
resource: {
values: [[newValue]]
}
});
console.log('Progress updated:', response);
return response;
} catch (error) {
console.error('Error updating sheet:', error);
throw error;
}
}
// Helper function to convert column number to letter (1 -> A, 2 -> B, etc.)
function getColumnLetter(columnNumber) {
let temp, letter = '';
while (columnNumber > 0) {
temp = (columnNumber - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
columnNumber = (columnNumber - temp - 1) / 26;
}
return letter;
}
function saveProgressToLocalStorage(rowId, newValue) {
let progressData = JSON.parse(localStorage.getItem('progressData') || '{}');
progressData[rowId] = newValue;
localStorage.setItem('progressData', JSON.stringify(progressData));
}
function loadProgressFromLocalStorage() {
const savedProgress = localStorage.getItem('progressData');
if (savedProgress) {
const progressData = JSON.parse(savedProgress);
allData.forEach(row => {
if (progressData[row.id]) {
row['AVANÇO'] = progressData[row.id];
}
});
}
}
function setupEventListeners() {
// Show all columns button - only add if element exists
const showAllColumnsBtn = document.getElementById('showAllColumns');
if (showAllColumnsBtn) {
showAllColumnsBtn.addEventListener('click', function() {
// Reset all checkboxes
document.querySelectorAll('#tableHeaders input[type="checkbox"]').forEach(checkbox => {
checkbox.checked = true;
});
// Show all columns
document.querySelectorAll('th, td').forEach(cell => {
cell.style.display = '';
});
// Clear saved visibility
localStorage.removeItem('columnVisibility');
// Create empty visibility state with all columns visible
const visibilityState = {};
headers.forEach(header => {
visibilityState[header] = true;
});
localStorage.setItem('columnVisibility', JSON.stringify(visibilityState));
});
// Clear all filters button
document.getElementById('clearFilters').addEventListener('click', function() {
// Clear all active filters
activeFilters = {
'ÁREA': [],
'RESPONSÁVEL': [],
'ATUALIZADOR 1(EMAIL)': []
};
// Reset dropdown selections
document.getElementById('areaFilter').selectedIndex = -1;
document.getElementById('responsavelFilter').selectedIndex = -1;
document.getElementById('atualizador1Filter').selectedIndex = -1;
// Reset search
searchInput.value = '';
// Refresh data
filterData();
currentPage = 1;
renderTable();
});
// Area filter change handler
document.getElementById('areaFilter').addEventListener('change', function() {
const selectedOptions = Array.from(this.selectedOptions).map(opt => opt.value);
activeFilters['ÁREA'] = selectedOptions;
filterData();
currentPage = 1;
renderTable();
});
// Responsavel filter change handler
document.getElementById('responsavelFilter').addEventListener('change', function() {
const selectedOptions = Array.from(this.selectedOptions).map(opt => opt.value);
activeFilters['RESPONSÁVEL'] = selectedOptions;
filterData();
currentPage = 1;
renderTable();
});
// Atualizador1 filter change handler
document.getElementById('atualizador1Filter').addEventListener('change', function() {
const selectedOptions = Array.from(this.selectedOptions).map(opt => opt.value);
activeFilters['ATUALIZADOR 1(EMAIL)'] = selectedOptions;
filterData();
currentPage = 1;
renderTable();
});
refreshBtn.addEventListener('click', function() {
updateLastUpdated();
fetchData();
});
retryBtn.addEventListener('click', function() {
updateLastUpdated();
fetchData();
});
searchInput.addEventListener('input', function() {
filterData();
currentPage = 1;
renderTable();
});
prevPage.addEventListener('click', goToPreviousPage);
nextPage.addEventListener('click', goToNextPage);
prevPageMobile.addEventListener('click', goToPreviousPage);
nextPageMobile.addEventListener('click', goToNextPage);
}
function goToPreviousPage() {
if (currentPage > 1) {
currentPage--;
renderTable();
}
}
function goToNextPage() {
if (currentPage < totalPages) {
currentPage++;
renderTable();
}
}
function goToPage(page) {
if (page >= 1 && page <= totalPages) {
currentPage = page;
renderTable();
}
}
async function fetchData() {
try {
showLoading();
// Use the public gviz endpoint
const response = await fetch(`https://docs.google.com/spreadsheets/d/${SHEET_ID}/gviz/tq?tqx=out:json`);
if (!response.ok) {
throw new Error('Erro ao buscar dados - Verifique se a planilha está publicamente compartilhada');
}
// Parse the special Google Visualization API response
const text = await response.text();
const json = JSON.parse(text.substring(47).slice(0, -2));
// Use fixed headers
headers = FIXED_HEADERS;
// Extract data rows
allData = json.table.rows.map((row, index) => {
const rowObj = { id: index + 1 };
headers.forEach((header, i) => {
const cell = row.c[i];
rowObj[header] = cell ? (cell.v || '') : '';
});
return rowObj;
});
filterData();
renderHeaders();
renderTable();
showData();
populateFilterDropdowns();
// Only initialize filters after data is fully loaded
setTimeout(() => {
populateFilterDropdowns();
headers.forEach(header => {
activeFilters[header] = [];
});
}, 100);
} catch (error) {
console.error('Error:', error);
if (Object.values(activeFilters).some(val => val)) {
errorMessage.textContent = `ERRO: Problema ao filtrar dados - ${error.message}`;
} else {
errorMessage.textContent = `ERRO: ${error.message}`;
}
showError();
}
}
function populateFilterDropdowns() {
const areaFilter = document.getElementById('areaFilter');
const responsavelFilter = document.getElementById('responsavelFilter');
// Get all unique area values from the data
const uniqueAreas = [...new Set(allData.map(item => item['ÁREA']).filter(Boolean))];
const uniqueResponsaveis = [...new Set(allData.map(item => item['RESPONSÁVEL']).filter(Boolean))];
const uniqueAtualizadores1 = [...new Set(allData.map(item => item['ATUALIZADOR 1(EMAIL)']).filter(Boolean))];
// Clear existing options
areaFilter.innerHTML = '';
responsavelFilter.innerHTML = '';
document.getElementById('atualizador1Filter').innerHTML = '';
// Add new options
uniqueAreas.forEach(area => {
const option = document.createElement('option');
option.value = area;
option.textContent = area;
areaFilter.appendChild(option);
});
uniqueResponsaveis.forEach(responsavel => {
const option = document.createElement('option');
option.value = responsavel;
option.textContent = responsavel;
responsavelFilter.appendChild(option);
});
uniqueAtualizadores1.forEach(atualizador => {
const option = document.createElement('option');
option.value = atualizador;
option.textContent = atualizador;
document.getElementById('atualizador1Filter').appendChild(option);
});
}
function filterData() {
// Don't filter if data isn't loaded yet
if (allData.length === 0) {
filteredData = [];
return;
}
const searchTerm = searchInput.value.toLowerCase();
// Start with all data
filteredData = [...allData];
// Apply search filter
if (searchTerm) {
filteredData = filteredData.filter(row =>
Object.values(row).some(value =>
String(value).toLowerCase().includes(searchTerm)
)
);
}
// Apply column filters
filteredData = filteredData.filter(row => {
// Check area filter if any areas are selected
if (activeFilters['ÁREA'] && activeFilters['ÁREA'].length > 0) {
if (!activeFilters['ÁREA'].includes(row['ÁREA'])) {
return false;
}
}
// Check responsavel filter if any responsaveis are selected
if (activeFilters['RESPONSÁVEL'] && activeFilters['RESPONSÁVEL'].length > 0) {
if (!activeFilters['RESPONSÁVEL'].includes(row['RESPONSÁVEL'])) {
return false;
}
}
// Check atualizador1 filter if any emails are selected
if (activeFilters['ATUALIZADOR 1(EMAIL)'] && activeFilters['ATUALIZADOR 1(EMAIL)'].length > 0) {
if (!activeFilters['ATUALIZADOR 1(EMAIL)'].includes(row['ATUALIZADOR 1(EMAIL)'])) {
return false;
}
}
return true;
});
totalPages = Math.ceil(filteredData.length / ROWS_PER_PAGE);
}
function renderHeaders() {
tableHeaders.innerHTML = '';
headers.forEach(header => {
const th = document.createElement('th');
th.scope = 'col';
th.className = 'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider';
th.textContent = header;
tableHeaders.appendChild(th);
});
}
function renderTable() {
tableBody.innerHTML = '';
const startIndex = (currentPage - 1) * ROWS_PER_PAGE;
const endIndex = Math.min(startIndex + ROWS_PER_PAGE, filteredData.length);
const pageData = filteredData.slice(startIndex, endIndex);
pageData.forEach(row => {
const tr = document.createElement('tr');
headers.forEach(header => {
const td = document.createElement('td');
td.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-900 border-r border-green-50';
// Special formatting for certain columns
if (header === 'INÍCIO' || header === 'TÉRMINO') {
const value = row[header];
// If empty, show empty
if (!value) {
td.textContent = '';
}
// If it's already in DD/MM/YYYY format, use as is
else if (typeof value === 'string' && value.match(/^\d{2}\/\d{2}\/\d{4}$/)) {
td.textContent = value;
}
// Try parsing as Google Sheets date string (YYYY-MM-DD)
else if (typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}/)) {
const [year, month, day] = value.split('-');
td.textContent = `${day.padStart(2, '0')}/${month.padStart(2, '0')}/${year}`;
}
// Try parsing as Excel serial date
else if (!isNaN(value)) {
const excelDate = parseFloat(value);
if (excelDate > 0) {
// Excel dates are days since 1900 (minus 1 day due to Excel bug)
const dateValue = new Date(1900, 0, excelDate - 1);
const day = String(dateValue.getDate()).padStart(2, '0');
const month = String(dateValue.getMonth() + 1).padStart(2, '0');
const year = dateValue.getFullYear();
td.textContent = `${day}/${month}/${year}`;
} else {
td.textContent = value;
}
} else {
// Fallback - show raw value
td.textContent = value;
}
} else if (header.toLowerCase().includes('data')) {
// Try to format as date if it looks like a date
const dateValue = new Date(row[header]);
if (!isNaN(dateValue)) {
td.textContent = dateValue.toLocaleDateString('pt-BR');
} else {
td.textContent = row[header];
}
} else if (header.toLowerCase().includes('valor') || header.toLowerCase().includes('preço')) {
// Format as currency if it looks like a number
const numValue = parseFloat(row[header].replace(',', '.'));
if (!isNaN(numValue)) {
td.textContent = numValue.toLocaleString('pt-BR', {
style: 'currency',
currency: 'BRL'
});
} else {
td.textContent = row[header];
}
} else if (header === 'AVANÇO') {
// Create container for AVANÇO controls
const container = document.createElement('div');
container.className = 'flex items-center justify-between';
// Current value display
const valueSpan = document.createElement('span');
valueSpan.className = 'w-12 text-center';
const progressValue = parseInt(row[header]) || 0;
valueSpan.textContent = `${progressValue}%`;
// Increment button
const incrementBtn = document.createElement('button');
incrementBtn.className = 'text-green-500 hover:text-green-700 mx-1';
incrementBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
incrementBtn.addEventListener('click', async () => {
const current = parseInt(row[header]) || 0;
const newValue = Math.min(100, current + 1);
const formattedValue = `${newValue}%`;
row[header] = formattedValue;
valueSpan.textContent = formattedValue;
saveProgressToLocalStorage(row.id, formattedValue);
try {
await saveProgressToGoogleSheets(row.id, newValue);
} catch (error) {
console.error('Failed to update Google Sheets:', error);
// Show detailed error to user
alert('Erro ao atualizar a planilha. Os dados foram salvos localmente mas não na base.\n\nMotivo: Por questões de segurança, o navegador não pode modificar diretamente a planilha do Google Sheets.\n\nSolução recomendada:\n1. Exporte os dados atualizados (botão "Exportar Excel")\n2. Abra a planilha original no Google Sheets\n3. Importe os dados atualizados manualmente\n\nOs dados locais permanecerão salvos até a próxima atualização.');
}
});
// Decrement button
const decrementBtn = document.createElement('button');
decrementBtn.className = 'text-red-500 hover:text-red-700 mx-1';
decrementBtn.innerHTML = '<i class="fas fa-arrow-down"></i>';
decrementBtn.addEventListener('click', async () => {
const current = parseInt(row[header]) || 0;
const newValue = Math.max(0, current - 1);
const formattedValue = `${newValue}%`;
row[header] = formattedValue;
valueSpan.textContent = formattedValue;
saveProgressToLocalStorage(row.id, formattedValue);
// No longer trying to update Google Sheets directly
});
container.appendChild(decrementBtn);
container.appendChild(valueSpan);
container.appendChild(incrementBtn);
td.appendChild(container);
} else {
td.textContent = row[header];
}
tr.appendChild(td);
});
tableBody.appendChild(tr);
});
renderPagination();
}
function renderPagination() {
paginationInfo.textContent = `Mostrando ${Math.min((currentPage - 1) * ROWS_PER_PAGE + 1, filteredData.length)} a ${Math.min(currentPage * ROWS_PER_PAGE, filteredData.length)} de ${filteredData.length} registros`;
pageNumbers.innerHTML = '';
// Always show first page
addPageNumber(1);
// Show ellipsis if needed
if (currentPage > 3) {
const ellipsis = document.createElement('span');
ellipsis.className = 'relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700';
ellipsis.textContent = '...';
pageNumbers.appendChild(ellipsis);
}
// Show current page and neighbors
const startPage = Math.max(2, currentPage - 1);
const endPage = Math.min(totalPages - 1, currentPage + 1);
for (let i = startPage; i <= endPage; i++) {
addPageNumber(i);
}
// Show ellipsis if needed
if (currentPage < totalPages - 2) {
const ellipsis = document.createElement('span');
ellipsis.className = 'relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700';
ellipsis.textContent = '...';
pageNumbers.appendChild(ellipsis);
}
// Always show last page if different from first
if (totalPages > 1) {
addPageNumber(totalPages);
}
// Disable/enable pagination buttons
prevPage.disabled = currentPage === 1;
nextPage.disabled = currentPage === totalPages;
prevPageMobile.disabled = currentPage === 1;
nextPageMobile.disabled = currentPage === totalPages;
if (currentPage === 1) {
prevPage.classList.add('opacity-50', 'cursor-not-allowed');
prevPageMobile.classList.add('opacity-50', 'cursor-not-allowed');
} else {
prevPage.classList.remove('opacity-50', 'cursor-not-allowed');
prevPageMobile.classList.remove('opacity-50', 'cursor-not-allowed');
}
if (currentPage === totalPages) {
nextPage.classList.add('opacity-50', 'cursor-not-allowed');
nextPageMobile.classList.add('opacity-50', 'cursor-not-allowed');
} else {
nextPage.classList.remove('opacity-50', 'cursor-not-allowed');
nextPageMobile.classList.remove('opacity-50', 'cursor-not-allowed');
}
}
function addPageNumber(page) {
const pageBtn = document.createElement('button');
pageBtn.className = `relative inline-flex items-center px-4 py-2 border text-sm font-medium ${currentPage === page ? 'z-10 bg-green-50 border-green-400 text-green-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'}`;
pageBtn.textContent = page;
pageBtn.addEventListener('click', () => goToPage(page));
pageNumbers.appendChild(pageBtn);
}
function showLoading() {
loadingElement.classList.remove('hidden');
dataContainer.classList.add('hidden');
errorContainer.classList.add('hidden');
}
function showData() {
loadingElement.classList.add('hidden');
dataContainer.classList.remove('hidden');
errorContainer.classList.add('hidden');
}
function showError() {
loadingElement.classList.add('hidden');
dataContainer.classList.add('hidden');
errorContainer.classList.remove('hidden');
}
// Excel export function
document.getElementById('exportExcelBtn').addEventListener('click', function() {
// Create CSV content
let csvContent = "data:text/csv;charset=utf-8,";
// Add headers
csvContent += headers.join(";") + "\r\n";
// Add data rows
allData.forEach(row => {
const rowData = headers.map(header => {
// Remove % from AVANÇO value for cleaner export
if (header === 'AVANÇO' && row[header]) {
return row[header].replace('%', '');
}
// Escape special characters in other fields
return `"${String(row[header] || '').replace(/"/g, '""')}"`;
});
csvContent += rowData.join(";") + "\r\n";
});
// Create download link
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "parei_export.csv");
document.body.appendChild(link);
// Trigger download
link.click();
document.body.removeChild(link);
});
});
</script>
<!-- Mobile Filter Panel -->
<div id="mobileFilterPanel" class="mobile-filter-panel">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-bold">Filtros</h2>
<button id="closeMobileFilters" class="text-gray-500 hover:text-gray-700">
<i class="fas fa-times text-2xl"></i>
</button>
</div>
<div id="mobileFilterContainer" class="space-y-4">
<!-- Mobile filters will be added here -->
</div>
<div class="mt-6">
<button id="applyMobileFilters" class="w-full bg-gradient-to-r from-green-300 to-green-400 hover:from-green-400 hover:to-green-500 text-white py-3 rounded-lg">
Aplicar Filtros
</button>
</div>
</div>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=Lengel/https-huggingface-co-spaces-lengel-parei" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html> |