import React, { useState } from 'react'; import * as XLSX from 'xlsx'; import { useAuth } from '../contexts/AuthContext'; import { Button } from '../components/Button'; import { Upload, FileText, CheckCircle, AlertTriangle } from 'lucide-react'; const API_BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:8080"; interface ImportInput { fot: string; empresa_nome: string; curso_nome: string; ano_formatura_label: string; instituicao: string; cidade: string; estado: string; observacoes: string; gastos_captacao: number; pre_venda: boolean; } export const ImportData: React.FC = () => { const { token } = useAuth(); const [data, setData] = useState([]); const [preview, setPreview] = useState([]); const [filename, setFilename] = useState(""); const [isLoading, setIsLoading] = useState(false); const [result, setResult] = useState<{ success: number; errors: string[] } | null>(null); const handleFileUpload = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; setFilename(file.name); const reader = new FileReader(); reader.onload = (evt) => { const bstr = evt.target?.result; const wb = XLSX.read(bstr, { type: 'binary' }); const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; const jsonData = XLSX.utils.sheet_to_json(ws, { header: 1 }) as any[][]; // Assuming header is row 0 // Map columns based on index (A=0, B=1, ... J=9) based on screenshot const mappedData: ImportInput[] = []; // Start from row 1 (skip header) for (let i = 1; i < jsonData.length; i++) { const row = jsonData[i]; if (!row || row.length === 0) continue; // Helper to get string safely const getStr = (idx: number) => row[idx] ? String(row[idx]).trim() : ""; // Skip empty FOT lines? const fot = getStr(0); if (!fot) continue; // Parse Gastos (Remove 'R$', replace ',' with '.') let gastosStr = getStr(8); // Col I // Remove R$, spaces, thousands separator (.) and replace decimal (,) with . // Example: "R$ 2.500,00" -> "2500.00" gastosStr = gastosStr.replace(/[R$\s.]/g, '').replace(',', '.'); const gastos = parseFloat(gastosStr) || 0; const importItem: ImportInput = { fot: fot, empresa_nome: getStr(1), // Col B curso_nome: getStr(2), // Col C observacoes: getStr(3), // Col D instituicao: getStr(4), // Col E ano_formatura_label: getStr(5), // Col F cidade: getStr(6), // Col G estado: getStr(7), // Col H gastos_captacao: gastos, // Col I pre_venda: getStr(9).toLowerCase().includes('sim'), // Col J }; mappedData.push(importItem); } setData(mappedData); setPreview(mappedData.slice(0, 5)); setResult(null); }; reader.readAsBinaryString(file); }; const handleImport = async () => { if (!token) return; setIsLoading(true); try { const response = await fetch(`${API_BASE_URL}/api/import/fot`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, body: JSON.stringify(data) }); if (!response.ok) { throw new Error(`Erro na importação: ${response.statusText}`); } const resData = await response.json(); setResult({ success: resData.SuccessCount, errors: resData.Errors || [] }); // Clear data on success? Maybe keep for review. } catch (error) { console.error("Import error:", error); alert("Erro ao importar dados. Verifique o console."); } finally { setIsLoading(false); } }; // Drag scroll logic const tableContainerRef = React.useRef(null); const [isDragging, setIsDragging] = useState(false); const [startX, setStartX] = useState(0); const [scrollLeft, setScrollLeft] = useState(0); const handleMouseDown = (e: React.MouseEvent) => { if (!tableContainerRef.current) return; setIsDragging(true); setStartX(e.pageX - tableContainerRef.current.offsetLeft); setScrollLeft(tableContainerRef.current.scrollLeft); }; const handleMouseLeave = () => { setIsDragging(false); }; const handleMouseUp = () => { setIsDragging(false); }; const handleMouseMove = (e: React.MouseEvent) => { if (!isDragging || !tableContainerRef.current) return; e.preventDefault(); const x = e.pageX - tableContainerRef.current.offsetLeft; const walk = (x - startX) * 2; // Scroll-fast tableContainerRef.current.scrollLeft = scrollLeft - walk; }; return (

Importação de Dados (FOT)

Importe dados da planilha Excel para o sistema. Certifique-se que as colunas seguem o padrão.

Colunas Esperadas (A-J): FOT, Empresa, Curso, Observações, Instituição, Ano Formatura, Cidade, Estado, Gastos Captação, Pré Venda.
{filename && (
Arquivo selecionado: {filename} ({data.length} registros)
)}
{data.length > 0 && !result && (

Pré-visualização

Total: {data.length}
{/* Scrollable Container with Drag Support */}
{data.map((row, idx) => ( ))}
FOT Empresa Curso Instituição Ano Cidade/UF Gastos Pré Venda
{row.fot} {row.empresa_nome} {row.curso_nome} {row.instituicao} {row.ano_formatura_label} {row.cidade}/{row.estado} R$ {row.gastos_captacao.toLocaleString('pt-BR', { minimumFractionDigits: 2 })} {row.pre_venda ? 'Sim' : 'Não'}
Total de Registros: {data.length}
)} {result && (
0 ? 'bg-yellow-50' : 'bg-green-50'}`}>
{result.errors.length === 0 ? ( ) : ( )}

Resultado da Importação

Sucesso: {result.success} registros importados/atualizados.

{result.errors.length > 0 && (

Erros ({result.errors.length}):

    {result.errors.map((err, idx) => (
  • {err}
  • ))}
)}
)}
); };