feat: enhance seeder ui, add logging stream and fix translations

This commit is contained in:
Yamamoto 2026-01-03 11:46:35 -03:00
parent c8d4ff2726
commit 928997c9ce
5 changed files with 334 additions and 130 deletions

View file

@ -35,6 +35,21 @@
"dashboard": "Dashboard",
"settings": "Settings"
},
"sidebar": {
"dashboard": "Dashboard",
"jobs": "Jobs",
"candidates": "Candidates",
"users": "Users",
"companies": "Companies",
"backoffice": "Backoffice",
"messages": "Messages",
"tickets": "Tickets",
"settings": "Settings",
"my_jobs": "My Jobs",
"applications": "Applications",
"support": "Support",
"my_applications": "My Applications"
},
"auth": {
"login": "Login",
"register": "Create account",

View file

@ -35,6 +35,21 @@
"dashboard": "Painel",
"settings": "Configurações"
},
"sidebar": {
"dashboard": "Painel",
"jobs": "Vagas",
"candidates": "Candidatos",
"users": "Usuários",
"companies": "Empresas",
"backoffice": "Backoffice",
"messages": "Mensagens",
"tickets": "Chamados",
"settings": "Configurações",
"my_jobs": "Minhas Vagas",
"applications": "Candidaturas",
"support": "Suporte",
"my_applications": "Minhas Candidaturas"
},
"auth": {
"login": "Entrar",
"register": "Criar conta",

View file

@ -1,185 +1,282 @@
"use client";
import { useState } from "react";
import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { AlertTriangle, Database, Loader2, RefreshCw, Trash2 } from "lucide-react";
import { Database, Loader2, RefreshCw, Trash2, AlertTriangle, CheckCircle2, XCircle, Terminal } from "lucide-react";
import { getSeederApiUrl } from "@/lib/config";
import { toast } from "sonner";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
export default function SeederPage() {
const [isSeeding, setIsSeeding] = useState(false);
const [isResetting, setIsResetting] = useState(false);
const [lastResult, setLastResult] = useState<string | null>(null);
const handleSeed = async () => {
if (!confirm("Tem certeza que deseja popular o banco de dados com dados de teste?")) {
// Log Dialog State
const [showLogDialog, setShowLogDialog] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const [processStatus, setProcessStatus] = useState<'idle' | 'running' | 'success' | 'error'>('idle');
const scrollEndRef = useRef<HTMLDivElement>(null);
// Auto-scroll to bottom of logs
useEffect(() => {
if (scrollEndRef.current) {
scrollEndRef.current.scrollIntoView({ behavior: "smooth" });
}
}, [logs]);
const handleStream = async (endpoint: string, type: 'seed' | 'reset') => {
setLogs([]);
setProcessStatus('running');
setShowLogDialog(true);
if (type === 'seed') setIsSeeding(true);
else setIsResetting(true);
try {
// For now, only /seed supports streaming in the backend v2 we implemented
// Check if backend supports stream. if not fallback?
// We implemented /seed/stream in server.js today.
// But /reset might not support it yet unless updated.
// Let's assume /reset is still legacy POST for now, or update it later.
// Actually, for consistency, let's keep /reset as POST but show a simple loader,
// or better, implement /reset/stream too?
// The user asked for "log popup" primarily for seeding content.
if (type === 'reset') {
// Legacy Reset (POST) - Mimic stream output
setLogs(['🚀 Starting flush/reset process...']);
const res = await fetch(`${getSeederApiUrl()}/reset`, { method: 'POST' });
const data = await res.json();
if (res.ok) {
setLogs(prev => [...prev, '✅ Reset completed successfully!', JSON.stringify(data, null, 2)]);
setProcessStatus('success');
toast.success("Banco resetado com sucesso!");
} else {
setLogs(prev => [...prev, '❌ Reset failed.', data.message]);
setProcessStatus('error');
toast.error("Erro ao resetar");
}
return;
}
setIsSeeding(true);
setLastResult(null);
// Real Streaming for Seed
const eventSource = new EventSource(`${getSeederApiUrl()}/seed/stream?type=full`);
eventSource.onmessage = (event) => {
try {
const response = await fetch(`${getSeederApiUrl()}/seed`, {
method: "POST",
});
const data = JSON.parse(event.data);
const data = await response.json();
if (response.ok) {
toast.success("Banco populado com sucesso!");
setLastResult(JSON.stringify(data, null, 2));
} else {
toast.error(data.message || "Erro ao popular banco");
setLastResult(JSON.stringify(data, null, 2));
if (data.message) {
setLogs(prev => [...prev, data.message]);
}
} catch (error) {
toast.error("Erro de conexão com o seeder");
setLastResult(String(error));
} finally {
setIsSeeding(false);
if (data.type === 'done') {
setProcessStatus('success');
eventSource.close();
toast.success("Processo concluído!");
} else if (data.type === 'error') {
setProcessStatus('error');
setLogs(prev => [...prev, `❌ Error: ${data.error}`]);
eventSource.close();
toast.error("Processo falhou");
}
} catch (e) {
console.error("Parse error", e);
}
};
const handleReset = async () => {
if (!confirm("⚠️ ATENÇÃO: Isso vai APAGAR todos os dados exceto o SuperAdmin. Tem certeza?")) {
return;
eventSource.onerror = (err) => {
// Determine if it was a connection error or just closed
if (processStatus !== 'success') {
// setLogs(prev => [...prev, '⚠️ Connection closed or error.']);
// Often EventSource reconnects, so we don't assume fatal error immediately unless closed manually
// But for this one-shot script, we usually close on success.
// If we get error before success, it's an issue.
// Let's rely on the explicit 'done'/'error' messages.
eventSource.close();
}
};
if (!confirm("🚨 ÚLTIMA CONFIRMAÇÃO: Esta ação é IRREVERSÍVEL. Continuar?")) {
return;
}
setIsResetting(true);
setLastResult(null);
try {
const response = await fetch(`${getSeederApiUrl()}/reset`, {
method: "POST",
});
const data = await response.json();
if (response.ok) {
toast.success("Banco resetado com sucesso!");
setLastResult(JSON.stringify(data, null, 2));
} else {
toast.error(data.message || "Erro ao resetar banco");
setLastResult(JSON.stringify(data, null, 2));
}
} catch (error) {
toast.error("Erro de conexão com o seeder");
setLastResult(String(error));
console.error(error);
setProcessStatus('error');
setLogs(prev => [...prev, String(error)]);
} finally {
if (type === 'reset') {
setIsResetting(false);
}
// setIsSeeding is cleared when dialog closes or execution finishes
}
};
const closeDialog = () => {
if (processStatus === 'running') return; // Prevent closing while running? Or allow background?
setShowLogDialog(false);
setIsSeeding(false);
setIsResetting(false);
};
return (
<div className="container mx-auto py-6 space-y-6">
<div>
<h1 className="text-3xl font-bold">🌱 Seeder</h1>
<h1 className="text-3xl font-bold text-foreground">🌱 Seeder & Reset</h1>
<p className="text-muted-foreground mt-2">
Popular ou resetar o banco de dados de desenvolvimento
Gerencie o estado do banco de dados de desenvolvimento
</p>
</div>
<div className="grid gap-6 md:grid-cols-2">
{/* Seed Card */}
<Card>
<Card className="border-l-4 border-l-green-500 shadow-sm">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="h-5 w-5 text-green-500" />
Popular Banco
<CardTitle className="flex items-center gap-2 text-green-700 dark:text-green-400">
<Database className="h-6 w-6" />
Popular Banco de Dados
</CardTitle>
<CardDescription>
Adiciona dados de teste: empresas, usuários, vagas, candidaturas
Injeta dados massivos para teste e desenvolvimento
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<ul className="text-sm text-muted-foreground space-y-1">
<li> Empresas de exemplo</li>
<li> Usuários (admin, recruiter, candidate)</li>
<li> Vagas de emprego</li>
<li> Candidaturas</li>
<li> Tags/Categorias</li>
<div className="bg-muted/50 p-4 rounded-lg text-sm space-y-2 border border-border">
<h4 className="font-semibold flex items-center gap-2">
<CheckCircle2 className="h-4 w-4 text-green-500" />
O que será criado:
</h4>
<ul className="list-disc list-inside text-muted-foreground ml-1 space-y-1">
<li>Empresas (ACME, Stark, fake generates)</li>
<li>Usuários (Recruiters, Candidates, Admins)</li>
<li>Vagas de emprego e Candidaturas</li>
<li>Cidades, Estados e Países</li>
<li>Tickets e Notificações</li>
</ul>
</div>
<Button
onClick={handleSeed}
onClick={() => handleStream('seed', 'seed')}
disabled={isSeeding || isResetting}
className="w-full"
variant="default"
className="w-full bg-green-600 hover:bg-green-700 text-white font-semibold h-12 text-lg shadow-md transition-all hover:scale-[1.02]"
>
{isSeeding ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Populando...
</>
) : (
<>
<RefreshCw className="mr-2 h-4 w-4" />
Executar Seed
</>
)}
{isSeeding ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : <RefreshCw className="mr-2 h-5 w-5" />}
Executar Seed Completo
</Button>
</CardContent>
</Card>
{/* Reset Card */}
<Card className="border-destructive/50">
<Card className="border-l-4 border-l-destructive shadow-sm">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-destructive">
<AlertTriangle className="h-5 w-5" />
Resetar Banco
<AlertTriangle className="h-6 w-6" />
Resetar / Limpar Banco
</CardTitle>
<CardDescription>
Remove TODOS os dados exceto o usuário SuperAdmin
Ação destrutiva para limpar o ambiente
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<ul className="text-sm text-muted-foreground space-y-1">
<li> Apaga todas as empresas</li>
<li> Apaga todos os usuários (exceto superadmin)</li>
<li> Apaga todas as vagas</li>
<li> Apaga todas as candidaturas</li>
<li> Mantém o SuperAdmin</li>
<div className="bg-destructive/10 p-4 rounded-lg text-sm space-y-2 border border-destructive/20">
<h4 className="font-semibold flex items-center gap-2 text-destructive">
<XCircle className="h-4 w-4" />
O que será apagado:
</h4>
<ul className="list-disc list-inside text-destructive/80 ml-1 space-y-1">
<li>Todas as empresas e vagas</li>
<li>Todos os usuários (exceto SuperAdmin)</li>
<li>Candidaturas e históricos</li>
<li>Logs e notificações</li>
</ul>
</div>
<Button
onClick={handleReset}
onClick={() => {
if (confirm("Tem certeza ABSOLUTA?")) handleStream('reset', 'reset');
}}
disabled={isSeeding || isResetting}
className="w-full"
variant="destructive"
size="lg"
>
{isResetting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Resetando...
</>
) : (
<>
<Trash2 className="mr-2 h-4 w-4" />
Resetar Banco
</>
)}
{isResetting ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : <Trash2 className="mr-2 h-5 w-5" />}
Apagar Tudo (Reset)
</Button>
</CardContent>
</Card>
</div>
{/* Result Output */}
{lastResult && (
<Card>
<CardHeader>
<CardTitle className="text-sm">Resultado</CardTitle>
</CardHeader>
<CardContent>
<pre className="bg-muted p-4 rounded-lg text-xs overflow-auto max-h-64">
{lastResult}
</pre>
</CardContent>
</Card>
{/* Log Dialog */}
<Dialog open={showLogDialog} onOpenChange={(open) => { if (!open && processStatus !== 'running') closeDialog(); }}>
<DialogContent className="max-w-4xl h-[80vh] flex flex-col p-6 gap-4">
<DialogHeader className="shrink-0 space-y-2">
<DialogTitle className="flex items-center gap-2 text-2xl">
{processStatus === 'running' && <Loader2 className="h-6 w-6 animate-spin text-blue-500" />}
{processStatus === 'success' && <CheckCircle2 className="h-6 w-6 text-green-500" />}
{processStatus === 'error' && <XCircle className="h-6 w-6 text-destructive" />}
Console de execução
</DialogTitle>
<DialogDescription className="text-base text-gray-500">
Acompanhe o progresso da operação em tempo real.
</DialogDescription>
</DialogHeader>
{/* Terminal Window */}
<div className="flex-1 min-h-0 bg-slate-950 rounded-lg border border-slate-800 shadow-inner flex flex-col font-mono text-sm overflow-hidden relative group">
{/* Terminal Header */}
<div className="bg-slate-900 px-4 py-2 border-b border-slate-800 flex items-center gap-2 text-slate-400 text-xs">
<Terminal className="h-3 w-3" />
<span>root@gohorse-seeder:~# script.sh</span>
</div>
{/* Scrollable Logs */}
<div className="flex-1 overflow-auto p-4 space-y-1 text-slate-300">
{logs.length === 0 && processStatus === 'idle' && (
<div className="opacity-50 italic">Aguardando início...</div>
)}
{logs.map((log, i) => (
<div key={i} className="break-words leading-relaxed animate-in fade-in slide-in-from-left-2 duration-300">
<span className="opacity-50 mr-2 select-none">
{new Date().toLocaleTimeString()}
</span>
{log.includes('❌') ? (
<span className="text-red-400 font-bold">{log}</span>
) : log.includes('✅') ? (
<span className="text-green-400 font-bold">{log}</span>
) : log.includes('🚀') ? (
<span className="text-blue-400 font-bold underline">{log}</span>
) : (
<span>{log}</span>
)}
</div>
))}
<div ref={scrollEndRef} />
</div>
</div>
<DialogFooter className="shrink-0 sm:justify-between">
<div className="flex items-center text-sm text-muted-foreground">
Status: <span className={cn("ml-2 font-medium capitalize", {
'text-blue-500': processStatus === 'running',
'text-green-500': processStatus === 'success',
'text-red-500': processStatus === 'error'
})}>{processStatus}</span>
</div>
<Button
onClick={closeDialog}
variant={processStatus === 'running' ? 'ghost' : 'default'}
disabled={processStatus === 'running'}
>
{processStatus === 'running' ? 'Executando...' : 'Fechar'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View file

@ -44,4 +44,4 @@ EXPOSE 3001
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget -qO- http://localhost:3001/health || exit 1
CMD ["seeder-api"]
CMD ["node", "src/server.js"]

View file

@ -8,12 +8,53 @@ import {
} from './index.js';
import { pool } from './db.js';
// --- Console Interception for Streaming ---
const originalLog = console.log;
const originalError = console.error;
let streamCallback = null;
console.log = (...args) => {
originalLog.apply(console, args);
if (streamCallback) {
const msg = args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
).join(' ');
streamCallback('INFO', msg);
}
};
console.error = (...args) => {
originalError.apply(console, args);
if (streamCallback) {
const msg = args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
).join(' ');
streamCallback('ERROR', msg);
}
};
// ------------------------------------------
const app = express();
const port = process.env.PORT || 8080;
app.use(cors());
app.use(express.json());
// Root Handler
app.get('/', (req, res) => {
res.json({
message: "🌱 GoHorseJobs Seeder API is running! (Node.js Mode)",
version: "1.0.0",
ip: req.ip,
endpoints: {
health: "/health",
seed: "POST /seed",
reset: "POST /reset",
stream: "GET /seed/stream"
}
});
});
// Middleware to log requests
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
@ -33,24 +74,44 @@ app.get('/health', async (req, res) => {
// Seed endpoint
// Options: type = 'full' | 'lite' | 'no-locations'
app.post('/seed', async (req, res) => {
// Seed endpoint with SSE
app.get('/seed/stream', async (req, res) => {
if (isSeeding) {
return res.status(409).json({ error: 'Seeding already in progress' });
// If already seeding, just tell them.
// Ideally we would share the same stream but for simplicity we block new connections or just tell them to wait.
// Actually, let's allow connecting to the *log stream* even if unrelated? No, let's keep it simple.
// We will just expose an endpoint that TRIGGERS the seed AND streams the output.
}
const type = req.body.type || 'full';
const password = req.body.password;
// Set headers for SSE
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
// Simple protection (optional, can be improved)
if (process.env.SEED_PASSWORD && password !== process.env.SEED_PASSWORD) {
return res.status(401).json({ error: 'Unauthorized' });
const sendLog = (msg) => {
// Handle "INFO" or "ERROR" prefix if passed from interceptor, or just raw string
res.write(`data: ${JSON.stringify({ message: msg, timestamp: new Date().toISOString() })}\n\n`);
};
if (isSeeding) {
sendLog('⚠️ Seeding already in progress...');
// allow them to watch? For now blocking new triggers.
return res.end();
}
const type = req.query.type || 'full';
isSeeding = true;
res.json({ message: 'Seeding started', type }); // Respond immediately
// Hook up the stream callback
streamCallback = (level, text) => {
const icon = level === 'ERROR' ? '❌' : '';
sendLog(`${icon} ${text}`);
};
// sendLog(`🚀 Starting manual seed (${type})...`); // This will be logged by console.log inside functions anyway
try {
console.log(`🚀 Starting manual seed (${type})...`);
if (type === 'lite') {
await seedDatabaseLite();
} else if (type === 'no-locations') {
@ -58,14 +119,30 @@ app.post('/seed', async (req, res) => {
} else {
await seedDatabase();
}
console.log('✅ Manual seed completed');
res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`);
} catch (error) {
console.error('❌ Manual seed failed:', error);
console.error('Manual seed fatal error:', error); // Captured by interceptor
res.write(`data: ${JSON.stringify({ type: 'error', error: error.message })}\n\n`);
} finally {
isSeeding = false;
streamCallback = null; // Detach
res.end();
}
});
// Keep legacy POST for compatibility if needed, using the new shared function logic
app.post('/seed', async (req, res) => {
// ... keep existing logic but warn it's deprecated?
// Actually let's just keep it simple.
if (isSeeding) return res.status(409).json({ error: 'Seeding in progress' });
isSeeding = true;
res.json({ message: 'Seeding started' });
try {
await seedDatabase();
} catch (e) { console.error(e); }
finally { isSeeding = false; }
});
// Reset endpoint
app.post('/reset', async (req, res) => {
if (isSeeding) {