Fix locale sync for post job and candidates

This commit is contained in:
Tiago Yamamoto 2026-01-03 19:57:09 -03:00
parent 10d75e87ae
commit ce26de6225
7 changed files with 216 additions and 42 deletions

View file

@ -17,8 +17,10 @@ import {
} from "@/components/ui/dialog" } from "@/components/ui/dialog"
import { Search, Eye, Mail, Phone, MapPin, Briefcase } from "lucide-react" import { Search, Eye, Mail, Phone, MapPin, Briefcase } from "lucide-react"
import { adminCandidatesApi, AdminCandidate, AdminCandidateStats } from "@/lib/api" import { adminCandidatesApi, AdminCandidate, AdminCandidateStats } from "@/lib/api"
import { useTranslation } from "@/lib/i18n"
export default function AdminCandidatesPage() { export default function AdminCandidatesPage() {
const { t } = useTranslation()
const [searchTerm, setSearchTerm] = useState("") const [searchTerm, setSearchTerm] = useState("")
const [selectedCandidate, setSelectedCandidate] = useState<AdminCandidate | null>(null) const [selectedCandidate, setSelectedCandidate] = useState<AdminCandidate | null>(null)
const [candidates, setCandidates] = useState<AdminCandidate[]>([]) const [candidates, setCandidates] = useState<AdminCandidate[]>([])
@ -39,7 +41,7 @@ export default function AdminCandidatesPage() {
setStats(response.stats) setStats(response.stats)
} catch (error) { } catch (error) {
if (!isMounted) return if (!isMounted) return
setErrorMessage(error instanceof Error ? error.message : "Failed to load candidates") setErrorMessage(error instanceof Error ? error.message : t("admin.candidates_page.load_error"))
} finally { } finally {
if (isMounted) { if (isMounted) {
setIsLoading(false) setIsLoading(false)
@ -68,33 +70,33 @@ export default function AdminCandidatesPage() {
<div className="space-y-8"> <div className="space-y-8">
{/* Header */} {/* Header */}
<div> <div>
<h1 className="text-3xl font-bold text-foreground">Candidate management</h1> <h1 className="text-3xl font-bold text-foreground">{t("admin.candidates_page.title")}</h1>
<p className="text-muted-foreground mt-1">View and manage all registered candidates</p> <p className="text-muted-foreground mt-1">{t("admin.candidates_page.subtitle")}</p>
</div> </div>
{/* Stats */} {/* Stats */}
<div className="grid gap-4 md:grid-cols-4"> <div className="grid gap-4 md:grid-cols-4">
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardDescription>Total candidates</CardDescription> <CardDescription>{t("admin.candidates_page.stats.total")}</CardDescription>
<CardTitle className="text-3xl">{stats?.totalCandidates ?? 0}</CardTitle> <CardTitle className="text-3xl">{stats?.totalCandidates ?? 0}</CardTitle>
</CardHeader> </CardHeader>
</Card> </Card>
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardDescription>New (30 days)</CardDescription> <CardDescription>{t("admin.candidates_page.stats.new")}</CardDescription>
<CardTitle className="text-3xl">{stats?.newCandidates ?? 0}</CardTitle> <CardTitle className="text-3xl">{stats?.newCandidates ?? 0}</CardTitle>
</CardHeader> </CardHeader>
</Card> </Card>
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardDescription>Active applications</CardDescription> <CardDescription>{t("admin.candidates_page.stats.active")}</CardDescription>
<CardTitle className="text-3xl">{stats?.activeApplications ?? 0}</CardTitle> <CardTitle className="text-3xl">{stats?.activeApplications ?? 0}</CardTitle>
</CardHeader> </CardHeader>
</Card> </Card>
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardDescription>Hiring rate</CardDescription> <CardDescription>{t("admin.candidates_page.stats.hiring_rate")}</CardDescription>
<CardTitle className="text-3xl">{Math.round(stats?.hiringRate ?? 0)}%</CardTitle> <CardTitle className="text-3xl">{Math.round(stats?.hiringRate ?? 0)}%</CardTitle>
</CardHeader> </CardHeader>
</Card> </Card>
@ -107,7 +109,7 @@ export default function AdminCandidatesPage() {
<div className="relative flex-1"> <div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input <Input
placeholder="Search candidates by name or email..." placeholder={t("admin.candidates_page.search_placeholder")}
value={searchTerm} value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)} onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10" className="pl-10"
@ -122,26 +124,26 @@ export default function AdminCandidatesPage() {
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Candidate</TableHead> <TableHead>{t("admin.candidates_page.table.candidate")}</TableHead>
<TableHead>Email</TableHead> <TableHead>{t("admin.candidates_page.table.email")}</TableHead>
<TableHead>Phone</TableHead> <TableHead>{t("admin.candidates_page.table.phone")}</TableHead>
<TableHead>Location</TableHead> <TableHead>{t("admin.candidates_page.table.location")}</TableHead>
<TableHead>Applications</TableHead> <TableHead>{t("admin.candidates_page.table.applications")}</TableHead>
<TableHead className="text-right">Actions</TableHead> <TableHead className="text-right">{t("admin.candidates_page.table.actions")}</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{isLoading && ( {isLoading && (
<TableRow> <TableRow>
<TableCell colSpan={6} className="text-center text-sm text-muted-foreground"> <TableCell colSpan={6} className="text-center text-sm text-muted-foreground">
Loading candidates... {t("admin.candidates_page.table.loading")}
</TableCell> </TableCell>
</TableRow> </TableRow>
)} )}
{!isLoading && filteredCandidates.length === 0 && ( {!isLoading && filteredCandidates.length === 0 && (
<TableRow> <TableRow>
<TableCell colSpan={6} className="text-center text-sm text-muted-foreground"> <TableCell colSpan={6} className="text-center text-sm text-muted-foreground">
No candidates found. {t("admin.candidates_page.table.empty")}
</TableCell> </TableCell>
</TableRow> </TableRow>
)} )}
@ -170,8 +172,10 @@ export default function AdminCandidatesPage() {
</DialogTrigger> </DialogTrigger>
<DialogContent className="max-w-2xl"> <DialogContent className="max-w-2xl">
<DialogHeader> <DialogHeader>
<DialogTitle>Candidate profile</DialogTitle> <DialogTitle>{t("admin.candidates_page.dialog.title")}</DialogTitle>
<DialogDescription>Detailed information about {candidate.name}</DialogDescription> <DialogDescription>
{t("admin.candidates_page.dialog.description", { name: candidate.name })}
</DialogDescription>
</DialogHeader> </DialogHeader>
{selectedCandidate && ( {selectedCandidate && (
<div className="space-y-6"> <div className="space-y-6">
@ -220,18 +224,18 @@ export default function AdminCandidatesPage() {
</div> </div>
<div> <div>
<h4 className="font-semibold mb-2">About</h4> <h4 className="font-semibold mb-2">{t("admin.candidates_page.about.title")}</h4>
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
{selectedCandidate.bio ?? "No profile summary provided."} {selectedCandidate.bio ?? t("admin.candidates_page.about.empty")}
</p> </p>
</div> </div>
<div> <div>
<h4 className="font-semibold mb-2">Recent applications</h4> <h4 className="font-semibold mb-2">{t("admin.candidates_page.applications.title")}</h4>
<div className="space-y-2"> <div className="space-y-2">
{selectedCandidate.applications.length === 0 && ( {selectedCandidate.applications.length === 0 && (
<div className="text-sm text-muted-foreground"> <div className="text-sm text-muted-foreground">
No applications submitted yet. {t("admin.candidates_page.applications.empty")}
</div> </div>
)} )}
{selectedCandidate.applications.map((app) => ( {selectedCandidate.applications.map((app) => (
@ -252,11 +256,11 @@ export default function AdminCandidatesPage() {
: "secondary" : "secondary"
} }
> >
{app.status === "pending" && "Pending"} {app.status === "pending" && t("admin.candidates_page.status.pending")}
{app.status === "reviewed" && "Reviewed"} {app.status === "reviewed" && t("admin.candidates_page.status.reviewed")}
{app.status === "shortlisted" && "Shortlisted"} {app.status === "shortlisted" && t("admin.candidates_page.status.shortlisted")}
{app.status === "hired" && "Hired"} {app.status === "hired" && t("admin.candidates_page.status.hired")}
{app.status === "rejected" && "Rejected"} {app.status === "rejected" && t("admin.candidates_page.status.rejected")}
</Badge> </Badge>
</div> </div>
))} ))}

View file

@ -31,8 +31,8 @@ jest.mock("sonner", () => ({
jest.mock("./translations", () => ({ jest.mock("./translations", () => ({
translations: { translations: {
pt: { en: {
title: "Postar uma Vaga", title: "Post a Job",
buttons: { next: "Next Step", publish: "Publish Job", publishing: "Publishing..." }, buttons: { next: "Next Step", publish: "Publish Job", publishing: "Publishing..." },
company: { company: {
name: "Company Name", name: "Company Name",
@ -59,6 +59,16 @@ jest.mock("./translations", () => ({
contract: { permanent: "Permanent" }, contract: { permanent: "Permanent" },
hours: { fullTime: "Full Time" }, hours: { fullTime: "Full Time" },
mode: { remote: "Remote" } mode: { remote: "Remote" }
},
errors: {
company_required: "Company required",
password_mismatch: "Password mismatch",
password_length: "Password length",
job_required: "Job required",
submit_failed: "Submit failed"
},
success: {
job_created: "Job created"
} }
}, },
}, },

View file

@ -1,6 +1,6 @@
"use client"; "use client";
import { useState } from "react"; import { useMemo, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { translations, Language } from "./translations"; import { translations, Language } from "./translations";
import { toast } from "sonner"; import { toast } from "sonner";
@ -18,6 +18,7 @@ import {
import { LocationPicker } from "@/components/location-picker"; import { LocationPicker } from "@/components/location-picker";
import { RichTextEditor } from "@/components/rich-text-editor"; import { RichTextEditor } from "@/components/rich-text-editor";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useTranslation } from "@/lib/i18n";
// Common Country Codes // Common Country Codes
const COUNTRY_CODES = [ const COUNTRY_CODES = [
@ -53,9 +54,9 @@ const getCurrencySymbol = (code: string): string => {
export default function PostJobPage() { export default function PostJobPage() {
const router = useRouter(); const router = useRouter();
const [step, setStep] = useState<1 | 2>(1); const [step, setStep] = useState<1 | 2>(1);
const { locale, setLocale } = useTranslation();
// Language State const lang = useMemo<Language>(() => (locale === "pt-BR" ? "pt" : locale), [locale]);
const [lang, setLang] = useState<Language>('pt');
const t = translations[lang]; const t = translations[lang];
// Helper inside to use t // Helper inside to use t
@ -116,25 +117,25 @@ export default function PostJobPage() {
const validateForm = () => { const validateForm = () => {
if (!company.name || !company.email || !company.password) { if (!company.name || !company.email || !company.password) {
toast.error("Preencha os dados obrigatórios da empresa"); toast.error(t.errors.company_required);
setStep(1); // Ensure we are on step 1 for company data errors setStep(1); // Ensure we are on step 1 for company data errors
return false; return false;
} }
if (company.password !== company.confirmPassword) { if (company.password !== company.confirmPassword) {
toast.error("As senhas não coincidem"); toast.error(t.errors.password_mismatch);
setStep(1); // Ensure we are on step 1 for password mismatch setStep(1); // Ensure we are on step 1 for password mismatch
return false; return false;
} }
if (company.password.length < 8) { if (company.password.length < 8) {
toast.error("A senha deve ter pelo menos 8 caracteres"); toast.error(t.errors.password_length);
setStep(1); // Ensure we are on step 1 for password length setStep(1); // Ensure we are on step 1 for password length
return false; return false;
} }
if (!job.title || !job.description) { if (!job.title || !job.description) {
toast.error("Preencha os dados da vaga"); toast.error(t.errors.job_required);
setStep(1); // Stay on step 1 for job data errors setStep(1); // Stay on step 1 for job data errors
return false; return false;
} }
@ -144,15 +145,15 @@ export default function PostJobPage() {
const handleNext = () => { const handleNext = () => {
// Only validate step 1 fields to move to step 2 // Only validate step 1 fields to move to step 2
if (!company.name || !company.email || !company.password) { if (!company.name || !company.email || !company.password) {
toast.error("Preencha os dados obrigatórios da empresa"); toast.error(t.errors.company_required);
return; return;
} }
if (company.password !== company.confirmPassword) { if (company.password !== company.confirmPassword) {
toast.error("As senhas não coincidem"); toast.error(t.errors.password_mismatch);
return; return;
} }
if (company.password.length < 8) { if (company.password.length < 8) {
toast.error("A senha deve ter pelo menos 8 caracteres"); toast.error(t.errors.password_length);
return; return;
} }
setStep(2); setStep(2);
@ -225,11 +226,11 @@ export default function PostJobPage() {
localStorage.setItem("token", token); localStorage.setItem("token", token);
localStorage.setItem("auth_token", token); localStorage.setItem("auth_token", token);
toast.success("Vaga criada com sucesso! Aguardando aprovação."); toast.success(t.success.job_created);
router.push("/dashboard/jobs"); router.push("/dashboard/jobs");
} catch (err: any) { } catch (err: any) {
toast.error(err.message || "Erro ao processar solicitação"); toast.error(err.message || t.errors.submit_failed);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@ -243,7 +244,13 @@ export default function PostJobPage() {
<div className="container max-w-2xl mx-auto px-4"> <div className="container max-w-2xl mx-auto px-4">
<div className="relative mb-8"> <div className="relative mb-8">
<div className="absolute right-0 top-0"> <div className="absolute right-0 top-0">
<Select value={lang} onValueChange={(v) => setLang(v as Language)}> <Select
value={lang}
onValueChange={(value) => {
const nextLang = value as Language;
setLocale(nextLang === "pt" ? "pt-BR" : nextLang);
}}
>
<SelectTrigger className="w-[140px]"> <SelectTrigger className="w-[140px]">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>

View file

@ -87,6 +87,16 @@ export const translations = {
next: "Próximo: Confirmar", next: "Próximo: Confirmar",
publish: "Publicar Vaga", publish: "Publicar Vaga",
publishing: "Publicando..." publishing: "Publicando..."
},
errors: {
company_required: "Preencha os dados obrigatórios da empresa",
password_mismatch: "As senhas não coincidem",
password_length: "A senha deve ter pelo menos 8 caracteres",
job_required: "Preencha os dados da vaga",
submit_failed: "Erro ao processar solicitação"
},
success: {
job_created: "Vaga criada com sucesso! Aguardando aprovação."
} }
}, },
en: { en: {
@ -177,6 +187,16 @@ export const translations = {
next: "Next: Confirm", next: "Next: Confirm",
publish: "Publish Job", publish: "Publish Job",
publishing: "Publishing..." publishing: "Publishing..."
},
errors: {
company_required: "Please fill in the required company details",
password_mismatch: "Passwords do not match",
password_length: "Password must be at least 8 characters",
job_required: "Please fill in the job details",
submit_failed: "Error while processing the request"
},
success: {
job_created: "Job created successfully! Awaiting approval."
} }
}, },
es: { es: {
@ -267,6 +287,16 @@ export const translations = {
next: "Siguiente: Confirmar", next: "Siguiente: Confirmar",
publish: "Publicar Empleo", publish: "Publicar Empleo",
publishing: "Publicando..." publishing: "Publicando..."
},
errors: {
company_required: "Complete los datos obligatorios de la empresa",
password_mismatch: "Las contraseñas no coinciden",
password_length: "La contraseña debe tener al menos 8 caracteres",
job_required: "Complete los datos del empleo",
submit_failed: "Error al procesar la solicitud"
},
success: {
job_created: "Empleo creado correctamente. En espera de aprobación."
} }
} }
} }

View file

@ -771,6 +771,47 @@
"delete_error": "Failed to delete user", "delete_error": "Failed to delete user",
"load_error": "Failed to load users" "load_error": "Failed to load users"
} }
},
"candidates_page": {
"title": "Candidate management",
"subtitle": "View and manage all registered candidates",
"load_error": "Failed to load candidates",
"stats": {
"total": "Total candidates",
"new": "New (30 days)",
"active": "Active applications",
"hiring_rate": "Hiring rate"
},
"search_placeholder": "Search candidates by name or email...",
"table": {
"candidate": "Candidate",
"email": "Email",
"phone": "Phone",
"location": "Location",
"applications": "Applications",
"actions": "Actions",
"loading": "Loading candidates...",
"empty": "No candidates found."
},
"dialog": {
"title": "Candidate profile",
"description": "Detailed information about {name}"
},
"about": {
"title": "About",
"empty": "No profile summary provided."
},
"applications": {
"title": "Recent applications",
"empty": "No applications submitted yet."
},
"status": {
"pending": "Pending",
"reviewed": "Reviewed",
"shortlisted": "Shortlisted",
"hired": "Hired",
"rejected": "Rejected"
}
} }
}, },
"company": { "company": {

View file

@ -772,6 +772,47 @@
"delete_error": "Error al eliminar usuario", "delete_error": "Error al eliminar usuario",
"load_error": "Error al cargar usuarios" "load_error": "Error al cargar usuarios"
} }
},
"candidates_page": {
"title": "Gestión de candidatos",
"subtitle": "Ver y administrar todos los candidatos registrados",
"load_error": "Error al cargar candidatos",
"stats": {
"total": "Total de candidatos",
"new": "Nuevos (30 días)",
"active": "Postulaciones activas",
"hiring_rate": "Tasa de contratación"
},
"search_placeholder": "Buscar candidatos por nombre o correo...",
"table": {
"candidate": "Candidato",
"email": "Correo",
"phone": "Teléfono",
"location": "Ubicación",
"applications": "Postulaciones",
"actions": "Acciones",
"loading": "Cargando candidatos...",
"empty": "No se encontraron candidatos."
},
"dialog": {
"title": "Perfil del candidato",
"description": "Información detallada de {name}"
},
"about": {
"title": "Acerca de",
"empty": "No se proporcionó un resumen del perfil."
},
"applications": {
"title": "Postulaciones recientes",
"empty": "Aún no hay postulaciones."
},
"status": {
"pending": "Pendiente",
"reviewed": "Revisado",
"shortlisted": "Preseleccionado",
"hired": "Contratado",
"rejected": "Rechazado"
}
} }
}, },
"company": { "company": {

View file

@ -771,6 +771,47 @@
"delete_error": "Falha ao excluir usuário", "delete_error": "Falha ao excluir usuário",
"load_error": "Falha ao carregar usuários" "load_error": "Falha ao carregar usuários"
} }
},
"candidates_page": {
"title": "Gestão de candidatos",
"subtitle": "Veja e gerencie todos os candidatos cadastrados",
"load_error": "Falha ao carregar candidatos",
"stats": {
"total": "Total de candidatos",
"new": "Novos (30 dias)",
"active": "Candidaturas ativas",
"hiring_rate": "Taxa de contratação"
},
"search_placeholder": "Buscar candidatos por nome ou e-mail...",
"table": {
"candidate": "Candidato",
"email": "E-mail",
"phone": "Telefone",
"location": "Localização",
"applications": "Candidaturas",
"actions": "Ações",
"loading": "Carregando candidatos...",
"empty": "Nenhum candidato encontrado."
},
"dialog": {
"title": "Perfil do candidato",
"description": "Informações detalhadas sobre {name}"
},
"about": {
"title": "Sobre",
"empty": "Nenhum resumo do perfil foi fornecido."
},
"applications": {
"title": "Candidaturas recentes",
"empty": "Nenhuma candidatura enviada ainda."
},
"status": {
"pending": "Pendente",
"reviewed": "Em análise",
"shortlisted": "Pré-selecionado",
"hired": "Contratado",
"rejected": "Rejeitado"
}
} }
}, },
"company": { "company": {