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", "dashboard": "Dashboard",
"settings": "Settings" "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": { "auth": {
"login": "Login", "login": "Login",
"register": "Create account", "register": "Create account",

View file

@ -35,6 +35,21 @@
"dashboard": "Painel", "dashboard": "Painel",
"settings": "Configurações" "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": { "auth": {
"login": "Entrar", "login": "Entrar",
"register": "Criar conta", "register": "Criar conta",

View file

@ -1,185 +1,282 @@
"use client"; "use client";
import { useState } from "react"; import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; 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 { getSeederApiUrl } from "@/lib/config";
import { toast } from "sonner"; 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() { export default function SeederPage() {
const [isSeeding, setIsSeeding] = useState(false); const [isSeeding, setIsSeeding] = useState(false);
const [isResetting, setIsResetting] = useState(false); const [isResetting, setIsResetting] = useState(false);
const [lastResult, setLastResult] = useState<string | null>(null);
const handleSeed = async () => { // Log Dialog State
if (!confirm("Tem certeza que deseja popular o banco de dados com dados de teste?")) { 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; return;
} }
setIsSeeding(true); // Real Streaming for Seed
setLastResult(null); const eventSource = new EventSource(`${getSeederApiUrl()}/seed/stream?type=full`);
eventSource.onmessage = (event) => {
try { try {
const response = await fetch(`${getSeederApiUrl()}/seed`, { const data = JSON.parse(event.data);
method: "POST",
});
const data = await response.json(); if (data.message) {
setLogs(prev => [...prev, data.message]);
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));
} }
} catch (error) {
toast.error("Erro de conexão com o seeder"); if (data.type === 'done') {
setLastResult(String(error)); setProcessStatus('success');
} finally { eventSource.close();
setIsSeeding(false); 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 () => { eventSource.onerror = (err) => {
if (!confirm("⚠️ ATENÇÃO: Isso vai APAGAR todos os dados exceto o SuperAdmin. Tem certeza?")) { // Determine if it was a connection error or just closed
return; 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) { } catch (error) {
toast.error("Erro de conexão com o seeder"); console.error(error);
setLastResult(String(error)); setProcessStatus('error');
setLogs(prev => [...prev, String(error)]);
} finally { } finally {
if (type === 'reset') {
setIsResetting(false); 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 ( return (
<div className="container mx-auto py-6 space-y-6"> <div className="container mx-auto py-6 space-y-6">
<div> <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"> <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> </p>
</div> </div>
<div className="grid gap-6 md:grid-cols-2"> <div className="grid gap-6 md:grid-cols-2">
{/* Seed Card */} {/* Seed Card */}
<Card> <Card className="border-l-4 border-l-green-500 shadow-sm">
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2"> <CardTitle className="flex items-center gap-2 text-green-700 dark:text-green-400">
<Database className="h-5 w-5 text-green-500" /> <Database className="h-6 w-6" />
Popular Banco Popular Banco de Dados
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
Adiciona dados de teste: empresas, usuários, vagas, candidaturas Injeta dados massivos para teste e desenvolvimento
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<ul className="text-sm text-muted-foreground space-y-1"> <div className="bg-muted/50 p-4 rounded-lg text-sm space-y-2 border border-border">
<li> Empresas de exemplo</li> <h4 className="font-semibold flex items-center gap-2">
<li> Usuários (admin, recruiter, candidate)</li> <CheckCircle2 className="h-4 w-4 text-green-500" />
<li> Vagas de emprego</li> O que será criado:
<li> Candidaturas</li> </h4>
<li> Tags/Categorias</li> <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> </ul>
</div>
<Button <Button
onClick={handleSeed} onClick={() => handleStream('seed', 'seed')}
disabled={isSeeding || isResetting} disabled={isSeeding || isResetting}
className="w-full" 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]"
variant="default"
> >
{isSeeding ? ( {isSeeding ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : <RefreshCw className="mr-2 h-5 w-5" />}
<> Executar Seed Completo
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Populando...
</>
) : (
<>
<RefreshCw className="mr-2 h-4 w-4" />
Executar Seed
</>
)}
</Button> </Button>
</CardContent> </CardContent>
</Card> </Card>
{/* Reset Card */} {/* Reset Card */}
<Card className="border-destructive/50"> <Card className="border-l-4 border-l-destructive shadow-sm">
<CardHeader> <CardHeader>
<CardTitle className="flex items-center gap-2 text-destructive"> <CardTitle className="flex items-center gap-2 text-destructive">
<AlertTriangle className="h-5 w-5" /> <AlertTriangle className="h-6 w-6" />
Resetar Banco Resetar / Limpar Banco
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
Remove TODOS os dados exceto o usuário SuperAdmin Ação destrutiva para limpar o ambiente
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<ul className="text-sm text-muted-foreground space-y-1"> <div className="bg-destructive/10 p-4 rounded-lg text-sm space-y-2 border border-destructive/20">
<li> Apaga todas as empresas</li> <h4 className="font-semibold flex items-center gap-2 text-destructive">
<li> Apaga todos os usuários (exceto superadmin)</li> <XCircle className="h-4 w-4" />
<li> Apaga todas as vagas</li> O que será apagado:
<li> Apaga todas as candidaturas</li> </h4>
<li> Mantém o SuperAdmin</li> <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> </ul>
</div>
<Button <Button
onClick={handleReset} onClick={() => {
if (confirm("Tem certeza ABSOLUTA?")) handleStream('reset', 'reset');
}}
disabled={isSeeding || isResetting} disabled={isSeeding || isResetting}
className="w-full" className="w-full"
variant="destructive" variant="destructive"
size="lg"
> >
{isResetting ? ( {isResetting ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : <Trash2 className="mr-2 h-5 w-5" />}
<> Apagar Tudo (Reset)
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Resetando...
</>
) : (
<>
<Trash2 className="mr-2 h-4 w-4" />
Resetar Banco
</>
)}
</Button> </Button>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
{/* Result Output */} {/* Log Dialog */}
{lastResult && ( <Dialog open={showLogDialog} onOpenChange={(open) => { if (!open && processStatus !== 'running') closeDialog(); }}>
<Card> <DialogContent className="max-w-4xl h-[80vh] flex flex-col p-6 gap-4">
<CardHeader> <DialogHeader className="shrink-0 space-y-2">
<CardTitle className="text-sm">Resultado</CardTitle> <DialogTitle className="flex items-center gap-2 text-2xl">
</CardHeader> {processStatus === 'running' && <Loader2 className="h-6 w-6 animate-spin text-blue-500" />}
<CardContent> {processStatus === 'success' && <CheckCircle2 className="h-6 w-6 text-green-500" />}
<pre className="bg-muted p-4 rounded-lg text-xs overflow-auto max-h-64"> {processStatus === 'error' && <XCircle className="h-6 w-6 text-destructive" />}
{lastResult} Console de execução
</pre> </DialogTitle>
</CardContent> <DialogDescription className="text-base text-gray-500">
</Card> 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> </div>
); );
} }

View file

@ -44,4 +44,4 @@ EXPOSE 3001
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget -qO- http://localhost:3001/health || exit 1 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'; } from './index.js';
import { pool } from './db.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 app = express();
const port = process.env.PORT || 8080; const port = process.env.PORT || 8080;
app.use(cors()); app.use(cors());
app.use(express.json()); 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 // Middleware to log requests
app.use((req, res, next) => { app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
@ -33,24 +74,44 @@ app.get('/health', async (req, res) => {
// Seed endpoint // Seed endpoint
// Options: type = 'full' | 'lite' | 'no-locations' // 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) { 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'; // Set headers for SSE
const password = req.body.password; 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) const sendLog = (msg) => {
if (process.env.SEED_PASSWORD && password !== process.env.SEED_PASSWORD) { // Handle "INFO" or "ERROR" prefix if passed from interceptor, or just raw string
return res.status(401).json({ error: 'Unauthorized' }); 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; 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 { try {
console.log(`🚀 Starting manual seed (${type})...`);
if (type === 'lite') { if (type === 'lite') {
await seedDatabaseLite(); await seedDatabaseLite();
} else if (type === 'no-locations') { } else if (type === 'no-locations') {
@ -58,14 +119,30 @@ app.post('/seed', async (req, res) => {
} else { } else {
await seedDatabase(); await seedDatabase();
} }
console.log('✅ Manual seed completed'); res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`);
} catch (error) { } 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 { } finally {
isSeeding = false; 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 // Reset endpoint
app.post('/reset', async (req, res) => { app.post('/reset', async (req, res) => {
if (isSeeding) { if (isSeeding) {