Lengel's picture
https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'ambient-light-sensor'.Entenda o aviso https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'battery'.Entenda o aviso https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'document-domain'.Entenda o aviso https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'layout-animations'.Entenda o aviso https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'legacy-image-formats'.Entenda o aviso https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'oversized-images'.Entenda o aviso https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'vr'.Entenda o aviso https-huggingface-co-spaces-lengel-parei:257 Unrecognized feature: 'wake-lock'.Entenda o aviso (índice):64 cdn.tailwindcss.com should not be used in production. To use Tailwind CSS in production, install it as a PostCSS plugin or use the Tailwind CLI: https://tailwindcss.com/docs/installation (anônimo) @ (índice):64Entenda o aviso index.html:473 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at setupEventListeners (index.html:473:58) at init (index.html:317:17) at HTMLDocument.<anonymous> (index.html:303:13 - Follow Up Deployment
43f9d25 verified
Raw History Blame Contribute Delete
51.7 kB
<!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>
<!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>