feat(export): adicionar exportação Excel do ranking com barra de progresso

- Novo endpoint GET /api/v1/ranking/exportar/excel
- Exporta apenas consultores com pontuação > 0
- Usa xlsxwriter para geração rápida (~40s para 300k registros)
- Layout profissional com formatação, filtros e cores condicionais
- Barra de progresso real no frontend com dois estados:
  - Animação indeterminada durante geração no servidor
  - Progresso real durante download do arquivo
- Botão de exportação integrado ao layout do sistema
- Suporte a cancelamento da exportação
This commit is contained in:
Frederico Castro
2025-12-28 01:45:52 -03:00
parent 015c8f5741
commit 840934a187
9 changed files with 822 additions and 0 deletions

View File

@@ -145,6 +145,34 @@
transform: translateY(-1px);
}
.btn-exportar {
padding: 0.5rem 1rem;
background: linear-gradient(135deg, rgba(34, 197, 94, 0.2), rgba(16, 185, 129, 0.15));
border: 1px solid rgba(34, 197, 94, 0.4);
color: #86efac;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
font-size: 0.85rem;
transition: all 150ms ease;
white-space: nowrap;
display: flex;
align-items: center;
gap: 0.4rem;
}
.btn-exportar:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(34, 197, 94, 0.3), rgba(16, 185, 129, 0.2));
border-color: rgba(34, 197, 94, 0.6);
transform: translateY(-1px);
}
.btn-exportar:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
}
.pagination {
display: flex;
align-items: center;

View File

@@ -4,6 +4,7 @@ import ConsultorCard from './components/ConsultorCard';
import CompararModal from './components/CompararModal';
import FiltroSelos from './components/FiltroSelos';
import SugerirConsultores from './components/SugerirConsultores';
import ExportProgress from './components/ExportProgress';
import { rankingService } from './services/api';
import './App.css';
@@ -25,6 +26,10 @@ function App() {
const [modalAberto, setModalAberto] = useState(false);
const [filtroSelos, setFiltroSelos] = useState([]);
const [sugerirAberto, setSugerirAberto] = useState(false);
const [exportando, setExportando] = useState(false);
const [exportProgress, setExportProgress] = useState({ loaded: 0, total: 0, percent: 0 });
const [exportStatus, setExportStatus] = useState('preparing');
const abortControllerRef = useRef(null);
const toggleSelecionado = (consultor) => {
setSelecionados((prev) => {
@@ -60,6 +65,45 @@ function App() {
}
};
const handleExportarExcel = async () => {
if (exportando) return;
try {
setExportando(true);
setExportStatus('preparing');
setExportProgress({ loaded: 0, total: 0, percent: 0 });
abortControllerRef.current = new AbortController();
await rankingService.downloadRankingExcel(
filtroSelos,
(progress) => {
setExportStatus('downloading');
setExportProgress(progress);
},
abortControllerRef.current
);
setExportStatus('complete');
setTimeout(() => setExportando(false), 1000);
} catch (err) {
if (err.name === 'CanceledError' || err.code === 'ERR_CANCELED') {
console.log('Exportação cancelada pelo usuário');
} else {
console.error('Erro ao exportar Excel:', err);
setExportStatus('error');
setTimeout(() => setExportando(false), 2000);
}
}
};
const handleCancelExport = () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
setExportando(false);
};
useEffect(() => {
loadRanking();
}, [page, pageSize, filtroSelos]);
@@ -220,6 +264,15 @@ function App() {
Sugerir por Tema
</button>
<button
className="btn-exportar"
onClick={handleExportarExcel}
disabled={exportando || loading}
title="Exportar ranking para Excel (apenas consultores com pontuação)"
>
{exportando ? 'Exportando...' : '📊 Exportar Excel'}
</button>
<form className="search-box" onSubmit={handleSubmitBuscar}>
<input
type="text"
@@ -290,6 +343,14 @@ function App() {
/>
)}
{exportando && (
<ExportProgress
progress={exportProgress}
status={exportStatus}
onCancel={handleCancelExport}
/>
)}
<footer>
<p>Dados: ATUACAPES (Elasticsearch) + Oracle</p>
<p>Clique em qualquer consultor para ver detalhes</p>

View File

@@ -0,0 +1,196 @@
.export-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.85);
backdrop-filter: blur(8px);
display: flex;
align-items: center;
justify-content: center;
z-index: 1100;
animation: fadeIn 200ms ease;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.export-modal {
background: linear-gradient(155deg, rgba(15, 23, 42, 0.98), rgba(30, 41, 59, 0.95));
border: 1px solid var(--stroke);
border-radius: 20px;
padding: 2rem 2.5rem;
min-width: 320px;
max-width: 400px;
text-align: center;
box-shadow: 0 25px 80px rgba(0, 0, 0, 0.6), 0 0 40px rgba(34, 197, 94, 0.1);
animation: slideUp 300ms ease;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.export-icon {
width: 60px;
height: 60px;
margin: 0 auto 1rem;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.8rem;
background: linear-gradient(135deg, rgba(34, 197, 94, 0.2), rgba(16, 185, 129, 0.15));
border: 1px solid rgba(34, 197, 94, 0.3);
border-radius: 16px;
}
.export-icon.generating {
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.export-title {
font-size: 1.25rem;
font-weight: 700;
margin-bottom: 0.5rem;
background: linear-gradient(120deg, #86efac, #22c55e);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.export-status {
font-size: 0.9rem;
color: var(--muted);
margin-bottom: 1.5rem;
}
.progress-container {
margin-bottom: 1.5rem;
}
.progress-bar {
height: 8px;
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
overflow: hidden;
margin-bottom: 0.75rem;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #22c55e, #16a34a);
border-radius: 4px;
transition: width 150ms ease;
position: relative;
}
.progress-fill::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(
90deg,
transparent,
rgba(255, 255, 255, 0.3),
transparent
);
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
.progress-fill.complete {
background: linear-gradient(90deg, #22c55e, #16a34a);
}
.progress-fill.complete::after {
animation: none;
}
.progress-fill.error {
background: linear-gradient(90deg, #ef4444, #dc2626);
}
.progress-fill.indeterminate {
width: 30%;
animation: indeterminate 1.5s ease-in-out infinite;
}
@keyframes indeterminate {
0% {
transform: translateX(-100%);
}
50% {
transform: translateX(230%);
}
100% {
transform: translateX(-100%);
}
}
.progress-generating {
font-size: 0.85rem;
color: var(--muted);
animation: blink 1.5s ease-in-out infinite;
}
@keyframes blink {
0%, 100% { opacity: 0.5; }
50% { opacity: 1; }
}
.progress-info {
display: flex;
justify-content: space-between;
align-items: center;
}
.progress-percent {
font-size: 1.1rem;
font-weight: 700;
color: #86efac;
}
.progress-bytes {
font-size: 0.8rem;
color: var(--muted);
}
.export-cancel {
padding: 0.6rem 1.5rem;
background: rgba(255, 255, 255, 0.08);
border: 1px solid var(--stroke);
color: var(--text);
border-radius: 8px;
cursor: pointer;
font-weight: 500;
font-size: 0.9rem;
transition: all 150ms ease;
}
.export-cancel:hover {
background: rgba(239, 68, 68, 0.2);
border-color: rgba(239, 68, 68, 0.4);
color: #fca5a5;
}

View File

@@ -0,0 +1,82 @@
import './ExportProgress.css';
function ExportProgress({ progress, status, onCancel }) {
const formatBytes = (bytes) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
const isGenerating = status === 'preparing' || (status === 'downloading' && progress.total === 0);
const isDownloading = status === 'downloading' && progress.total > 0;
const getStatusText = () => {
if (isGenerating) {
return 'Gerando arquivo no servidor...';
}
switch (status) {
case 'downloading':
return 'Baixando arquivo...';
case 'complete':
return 'Concluído!';
case 'error':
return 'Erro na exportação';
default:
return 'Exportando...';
}
};
const percent = Math.min(Math.round(progress.percent || 0), 100);
const downloaded = progress.loaded || 0;
const total = progress.total || 0;
return (
<div className="export-overlay">
<div className="export-modal">
<div className={`export-icon ${isGenerating ? 'generating' : ''}`}>
{status === 'complete' ? '✓' : status === 'error' ? '✕' : '📊'}
</div>
<h3 className="export-title">Exportação Excel</h3>
<p className="export-status">{getStatusText()}</p>
<div className="progress-container">
<div className="progress-bar">
{isGenerating ? (
<div className="progress-fill indeterminate" />
) : (
<div
className={`progress-fill ${status === 'complete' ? 'complete' : ''} ${status === 'error' ? 'error' : ''}`}
style={{ width: `${percent}%` }}
/>
)}
</div>
<div className="progress-info">
{isGenerating ? (
<span className="progress-generating">Processando ~300k registros...</span>
) : (
<>
<span className="progress-percent">{percent}%</span>
{total > 0 && (
<span className="progress-bytes">
{formatBytes(downloaded)} / {formatBytes(total)}
</span>
)}
</>
)}
</div>
</div>
{status !== 'complete' && status !== 'error' && (
<button className="export-cancel" onClick={onCancel}>
Cancelar
</button>
)}
</div>
</div>
);
}
export default ExportProgress;

View File

@@ -186,6 +186,73 @@ export const rankingService = {
const response = await api.get(`/consultor/${idPessoa}/lattes`);
return response.data;
},
async getExportInfo(selos = []) {
const params = {};
if (selos && selos.length > 0) {
const normalizados = selos
.map((s) => String(s || '').trim().toUpperCase())
.filter(Boolean);
if (normalizados.length > 0) {
params.selos = normalizados.join(',');
}
}
const response = await api.get('/ranking/exportar/info', { params });
return response.data;
},
async downloadRankingExcel(selos = [], onProgress = null, abortController = null) {
const params = {};
if (selos && selos.length > 0) {
const normalizados = selos
.map((s) => String(s || '').trim().toUpperCase())
.filter(Boolean);
if (normalizados.length > 0) {
params.selos = normalizados.join(',');
}
}
const config = {
params,
responseType: 'blob',
timeout: 300000,
};
if (onProgress) {
config.onDownloadProgress = (progressEvent) => {
const { loaded, total } = progressEvent;
const percent = total ? Math.round((loaded * 100) / total) : 0;
onProgress({ loaded, total, percent });
};
}
if (abortController) {
config.signal = abortController.signal;
}
const response = await api.get('/ranking/exportar/excel', config);
const contentDisposition = response.headers['content-disposition'];
let nomeArquivo = 'ranking_consultores_capes.xlsx';
if (contentDisposition) {
const match = contentDisposition.match(/filename="(.+)"/);
if (match) {
nomeArquivo = match[1];
}
}
const blob = new Blob([response.data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = nomeArquivo;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
},
};
export default api;