feat(i18n): localize admin users UI surfaces

This commit is contained in:
2026-06-15 16:01:19 +02:00
parent 0cbbe60299
commit 73552dbb05
13 changed files with 593 additions and 58 deletions
@@ -14,6 +14,7 @@ export default async function EditUserPage({
const { userId } = await params const { userId } = await params
const user = await getUserProfileById(userId) const user = await getUserProfileById(userId)
const { dictionary } = await getI18n() const { dictionary } = await getI18n()
const copy = dictionary.admin.users
if (!user) { if (!user) {
notFound() notFound()
@@ -22,15 +23,20 @@ export default async function EditUserPage({
return ( return (
<div className="flex flex-col gap-8"> <div className="flex flex-col gap-8">
<div className="flex items-center justify-between gap-4"> <div className="flex items-center justify-between gap-4">
<h1 className="text-2xl font-bold">Edit User</h1> <h1 className="text-2xl font-bold">{copy.edit.title}</h1>
</div> </div>
<EditUserForm <EditUserForm
formCopy={copy.form}
schemaCopy={copy.schema}
roleLabels={copy.roles}
submitButtonCopy={dictionary.common.submitButton} submitButtonCopy={dictionary.common.submitButton}
user={user} user={user}
/> />
<section className="flex flex-col gap-4 border-t pt-6"> <section className="flex flex-col gap-4 border-t pt-6">
<h2 className="text-xl font-semibold">Reset password</h2> <h2 className="text-xl font-semibold">{copy.resetPassword.title}</h2>
<ResetUserPasswordForm <ResetUserPasswordForm
formCopy={copy.resetPassword}
schemaCopy={copy.schema}
submitButtonCopy={dictionary.common.submitButton} submitButtonCopy={dictionary.common.submitButton}
userId={user.id} userId={user.id}
/> />
@@ -2,6 +2,7 @@
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { useMemo } from "react"
import type { UseFormRegisterReturn } from "react-hook-form" import type { UseFormRegisterReturn } from "react-hook-form"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { toast } from "sonner" import { toast } from "sonner"
@@ -11,26 +12,36 @@ import {
type SubmitButtonCopy, type SubmitButtonCopy,
} from "@/components/forms/submitButton" } from "@/components/forms/submitButton"
import { import {
buildUpdateUserSchema,
type UpdateUserFormType, type UpdateUserFormType,
updateUserSchema, type UserSchemaCopy,
} from "@/schemas/user.schema" } from "@/schemas/user.schema"
import type { UserWithoutPassword } from "@/services/user.service" import type { UserWithoutPassword } from "@/services/user.service"
import type { UserFormCopy, UserRoleCopy } from "./user.copy"
export default function EditUserForm({ export default function EditUserForm({
formCopy,
schemaCopy,
roleLabels,
submitButtonCopy, submitButtonCopy,
user, user,
}: { }: {
formCopy: UserFormCopy
schemaCopy: UserSchemaCopy
roleLabels: UserRoleCopy
submitButtonCopy: SubmitButtonCopy submitButtonCopy: SubmitButtonCopy
user: UserWithoutPassword user: UserWithoutPassword
}) { }) {
const router = useRouter() const router = useRouter()
const schema = useMemo(() => buildUpdateUserSchema(schemaCopy), [schemaCopy])
const { const {
register, register,
handleSubmit, handleSubmit,
setError, setError,
formState: { errors, isSubmitting, isSubmitSuccessful }, formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<UpdateUserFormType>({ } = useForm<UpdateUserFormType>({
resolver: zodResolver(updateUserSchema), resolver: zodResolver(schema),
defaultValues: { defaultValues: {
id: user.id, id: user.id,
name: user.name, name: user.name,
@@ -69,50 +80,50 @@ export default function EditUserForm({
<UserTextInput <UserTextInput
error={errors.name?.message} error={errors.name?.message}
id="name" id="name"
label="Name" label={formCopy.nameLabel}
placeholder="Full name" placeholder={formCopy.namePlaceholder}
register={register("name")} register={register("name")}
/> />
<UserTextInput <UserTextInput
error={errors.username?.message} error={errors.username?.message}
id="username" id="username"
label="Username" label={formCopy.usernameLabel}
placeholder="username" placeholder={formCopy.usernamePlaceholder}
register={register("username")} register={register("username")}
/> />
<UserTextInput <UserTextInput
error={errors.email?.message} error={errors.email?.message}
id="email" id="email"
label="Email" label={formCopy.emailLabel}
placeholder="user@example.com" placeholder={formCopy.emailPlaceholder}
register={register("email")} register={register("email")}
type="email" type="email"
/> />
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label htmlFor="role" className="mb-2 block text-lg"> <label htmlFor="role" className="mb-2 block text-lg">
Role {formCopy.roleLabel}
</label> </label>
<select <select
id="role" id="role"
{...register("role")} {...register("role")}
className="w-full rounded-lg border px-4 py-2" className="w-full rounded-lg border px-4 py-2"
> >
<option value="ADMIN">Admin</option> <option value="ADMIN">{roleLabels.ADMIN}</option>
<option value="MANAGER">Manager</option> <option value="MANAGER">{roleLabels.MANAGER}</option>
<option value="STAFF">Staff</option> <option value="STAFF">{roleLabels.STAFF}</option>
<option value="VIEWER">Viewer</option> <option value="VIEWER">{roleLabels.VIEWER}</option>
</select> </select>
</div> </div>
<label className="flex items-center gap-2"> <label className="flex items-center gap-2">
<input type="checkbox" {...register("isActive")} /> <input type="checkbox" {...register("isActive")} />
Active user {formCopy.activeLabel}
</label> </label>
<SubmitButton <SubmitButton
copy={submitButtonCopy} copy={submitButtonCopy}
isSubmitting={isSubmitting} isSubmitting={isSubmitting}
isSubmitSuccessful={isSubmitSuccessful} isSubmitSuccessful={isSubmitSuccessful}
> >
Update User {formCopy.updateSubmit}
</SubmitButton> </SubmitButton>
</form> </form>
) )
@@ -2,6 +2,7 @@
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { useMemo } from "react"
import type { UseFormRegisterReturn } from "react-hook-form" import type { UseFormRegisterReturn } from "react-hook-form"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { toast } from "sonner" import { toast } from "sonner"
@@ -11,23 +12,33 @@ import {
type SubmitButtonCopy, type SubmitButtonCopy,
} from "@/components/forms/submitButton" } from "@/components/forms/submitButton"
import { import {
buildCreateUserSchema,
type CreateUserFormType, type CreateUserFormType,
createUserSchema, type UserSchemaCopy,
} from "@/schemas/user.schema" } from "@/schemas/user.schema"
import type { UserFormCopy, UserRoleCopy } from "./user.copy"
export default function NewUserForm({ export default function NewUserForm({
formCopy,
schemaCopy,
roleLabels,
submitButtonCopy, submitButtonCopy,
}: { }: {
formCopy: UserFormCopy
schemaCopy: UserSchemaCopy
roleLabels: UserRoleCopy
submitButtonCopy: SubmitButtonCopy submitButtonCopy: SubmitButtonCopy
}) { }) {
const router = useRouter() const router = useRouter()
const schema = useMemo(() => buildCreateUserSchema(schemaCopy), [schemaCopy])
const { const {
register, register,
handleSubmit, handleSubmit,
setError, setError,
formState: { errors, isSubmitting, isSubmitSuccessful }, formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<CreateUserFormType>({ } = useForm<CreateUserFormType>({
resolver: zodResolver(createUserSchema), resolver: zodResolver(schema),
defaultValues: { defaultValues: {
role: "STAFF", role: "STAFF",
isActive: true, isActive: true,
@@ -61,40 +72,44 @@ export default function NewUserForm({
<UserTextInput <UserTextInput
error={errors.name?.message} error={errors.name?.message}
id="name" id="name"
label="Name" label={formCopy.nameLabel}
placeholder="Full name" placeholder={formCopy.namePlaceholder}
register={register("name")} register={register("name")}
/> />
<UserTextInput <UserTextInput
error={errors.username?.message} error={errors.username?.message}
id="username" id="username"
label="Username" label={formCopy.usernameLabel}
placeholder="username" placeholder={formCopy.usernamePlaceholder}
register={register("username")} register={register("username")}
/> />
<UserTextInput <UserTextInput
error={errors.email?.message} error={errors.email?.message}
id="email" id="email"
label="Email" label={formCopy.emailLabel}
placeholder="user@example.com" placeholder={formCopy.emailPlaceholder}
register={register("email")} register={register("email")}
type="email" type="email"
/> />
<UserTextInput <UserTextInput
error={errors.password?.message} error={errors.password?.message}
id="password" id="password"
label="Password" label={formCopy.passwordLabel}
placeholder="Minimum 8 characters" placeholder={formCopy.passwordPlaceholder}
register={register("password")} register={register("password")}
type="password" type="password"
/> />
<RoleSelect register={register("role")} /> <RoleSelect
register={register("role")}
roleLabel={formCopy.roleLabel}
roleLabels={roleLabels}
/>
<SubmitButton <SubmitButton
copy={submitButtonCopy} copy={submitButtonCopy}
isSubmitting={isSubmitting} isSubmitting={isSubmitting}
isSubmitSuccessful={isSubmitSuccessful} isSubmitSuccessful={isSubmitSuccessful}
> >
Create User {formCopy.createSubmit}
</SubmitButton> </SubmitButton>
</form> </form>
) )
@@ -132,21 +147,29 @@ function UserTextInput({
) )
} }
function RoleSelect({ register }: { register: UseFormRegisterReturn }) { function RoleSelect({
register,
roleLabel,
roleLabels,
}: {
register: UseFormRegisterReturn
roleLabel: string
roleLabels: UserRoleCopy
}) {
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label htmlFor="role" className="mb-2 block text-lg"> <label htmlFor="role" className="mb-2 block text-lg">
Role {roleLabel}
</label> </label>
<select <select
id="role" id="role"
{...register} {...register}
className="w-full rounded-lg border px-4 py-2" className="w-full rounded-lg border px-4 py-2"
> >
<option value="ADMIN">Admin</option> <option value="ADMIN">{roleLabels.ADMIN}</option>
<option value="MANAGER">Manager</option> <option value="MANAGER">{roleLabels.MANAGER}</option>
<option value="STAFF">Staff</option> <option value="STAFF">{roleLabels.STAFF}</option>
<option value="VIEWER">Viewer</option> <option value="VIEWER">{roleLabels.VIEWER}</option>
</select> </select>
</div> </div>
) )
@@ -1,6 +1,7 @@
"use client" "use client"
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { useMemo } from "react"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { toast } from "sonner" import { toast } from "sonner"
import { resetUserPasswordAction } from "@/actions/user.actions" import { resetUserPasswordAction } from "@/actions/user.actions"
@@ -9,17 +10,28 @@ import {
type SubmitButtonCopy, type SubmitButtonCopy,
} from "@/components/forms/submitButton" } from "@/components/forms/submitButton"
import { import {
buildResetUserPasswordSchema,
type ResetUserPasswordFormType, type ResetUserPasswordFormType,
resetUserPasswordSchema, type UserSchemaCopy,
} from "@/schemas/user.schema" } from "@/schemas/user.schema"
import type { UserResetPasswordCopy } from "./user.copy"
export default function ResetUserPasswordForm({ export default function ResetUserPasswordForm({
formCopy,
schemaCopy,
submitButtonCopy, submitButtonCopy,
userId, userId,
}: { }: {
formCopy: UserResetPasswordCopy
schemaCopy: UserSchemaCopy
submitButtonCopy: SubmitButtonCopy submitButtonCopy: SubmitButtonCopy
userId: string userId: string
}) { }) {
const schema = useMemo(
() => buildResetUserPasswordSchema(schemaCopy),
[schemaCopy],
)
const { const {
register, register,
handleSubmit, handleSubmit,
@@ -27,7 +39,7 @@ export default function ResetUserPasswordForm({
setError, setError,
formState: { errors, isSubmitting, isSubmitSuccessful }, formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<ResetUserPasswordFormType>({ } = useForm<ResetUserPasswordFormType>({
resolver: zodResolver(resetUserPasswordSchema), resolver: zodResolver(schema),
defaultValues: { defaultValues: {
id: userId, id: userId,
}, },
@@ -60,12 +72,12 @@ export default function ResetUserPasswordForm({
<input type="hidden" {...register("id")} /> <input type="hidden" {...register("id")} />
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label htmlFor="password" className="mb-2 block text-lg"> <label htmlFor="password" className="mb-2 block text-lg">
New password {formCopy.passwordLabel}
</label> </label>
<input <input
type="password" type="password"
id="password" id="password"
placeholder="Minimum 8 characters" placeholder={formCopy.passwordPlaceholder}
{...register("password")} {...register("password")}
className={`w-full rounded-lg border px-4 py-2 ${errors.password ? "border-error" : ""}`} className={`w-full rounded-lg border px-4 py-2 ${errors.password ? "border-error" : ""}`}
/> />
@@ -78,7 +90,7 @@ export default function ResetUserPasswordForm({
isSubmitting={isSubmitting} isSubmitting={isSubmitting}
isSubmitSuccessful={isSubmitSuccessful} isSubmitSuccessful={isSubmitSuccessful}
> >
Reset Password {formCopy.submit}
</SubmitButton> </SubmitButton>
</form> </form>
) )
@@ -1,11 +1,18 @@
import type { Dictionary } from "@/i18n/dictionaries" import type { Dictionary } from "@/i18n/dictionaries"
export type UserListCopy = Dictionary["admin"]["users"]["list"]
export type UserFormCopy = Dictionary["admin"]["users"]["form"] export type UserFormCopy = Dictionary["admin"]["users"]["form"]
export type UserRoleCopy = Dictionary["admin"]["users"]["roles"]
export type UserStatusCopy = Dictionary["admin"]["users"]["status"]
export type UserFallbackCopy = Dictionary["admin"]["users"]["fallback"]
export type UserResetPasswordCopy = export type UserResetPasswordCopy =
Dictionary["admin"]["users"]["resetPassword"] Dictionary["admin"]["users"]["resetPassword"]
export type UserRolesCopy = Dictionary["admin"]["users"]["roles"]
export type UserStatusCopy = Dictionary["admin"]["users"]["status"] export function formatUserRole(
export type UserActionCopy = Dictionary["admin"]["users"]["actions"] role: string,
export type UserSchemaCopy = Dictionary["admin"]["users"]["schema"] roleCopy: UserRoleCopy,
export type UserFallbackCopy = Dictionary["admin"]["users"]["fallback"] fallbackCopy: UserFallbackCopy,
): string {
return role in roleCopy
? roleCopy[role as keyof UserRoleCopy]
: fallbackCopy.unknownRole
}
+8 -2
View File
@@ -4,13 +4,19 @@ import NewUserForm from "../_components/new.user.form"
export default async function NewUserPage() { export default async function NewUserPage() {
const { dictionary } = await getI18n() const { dictionary } = await getI18n()
const copy = dictionary.admin.users
return ( return (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4"> <div className="flex items-center justify-between gap-4">
<h1 className="text-2xl font-bold">New User</h1> <h1 className="text-2xl font-bold">{copy.new.title}</h1>
</div> </div>
<NewUserForm submitButtonCopy={dictionary.common.submitButton} /> <NewUserForm
formCopy={copy.form}
schemaCopy={copy.schema}
roleLabels={copy.roles}
submitButtonCopy={dictionary.common.submitButton}
/>
</div> </div>
) )
} }
+29 -10
View File
@@ -4,8 +4,16 @@ import Link from "next/link"
import PageHeader from "@/components/common/pageheader" import PageHeader from "@/components/common/pageheader"
import PaginationButtons from "@/components/common/pagination" import PaginationButtons from "@/components/common/pagination"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { getI18n } from "@/i18n/server"
import { getUsers } from "@/services/user.service" import { getUsers } from "@/services/user.service"
import {
formatUserRole,
type UserFallbackCopy,
type UserRoleCopy,
type UserStatusCopy,
} from "./_components/user.copy"
export default async function UsersPage(props: { export default async function UsersPage(props: {
searchParams?: Promise<{ searchParams?: Promise<{
page?: string page?: string
@@ -20,11 +28,14 @@ export default async function UsersPage(props: {
pageSize: 10, pageSize: 10,
search, search,
}) })
const { dictionary } = await getI18n()
const copy = dictionary.admin.users
return ( return (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<PageHeader <PageHeader
title="Users" title={copy.list.title}
addLabel={copy.list.addLabel}
link="/admin/users/new" link="/admin/users/new"
search={search} search={search}
data={users} data={users}
@@ -32,7 +43,7 @@ export default async function UsersPage(props: {
{users.length === 0 && currentPage === 1 && ( {users.length === 0 && currentPage === 1 && (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4"> <div className="flex items-center justify-between gap-4">
No users found. {copy.list.empty}
</div> </div>
</div> </div>
)} )}
@@ -42,22 +53,22 @@ export default async function UsersPage(props: {
<thead className="border-b"> <thead className="border-b">
<tr> <tr>
<th scope="col" className="p-4"> <th scope="col" className="p-4">
Name {copy.list.columns.name}
</th> </th>
<th scope="col" className="p-4"> <th scope="col" className="p-4">
Username {copy.list.columns.username}
</th> </th>
<th scope="col" className="p-4"> <th scope="col" className="p-4">
Email {copy.list.columns.email}
</th> </th>
<th scope="col" className="p-4"> <th scope="col" className="p-4">
Role {copy.list.columns.role}
</th> </th>
<th scope="col" className="p-4"> <th scope="col" className="p-4">
Status {copy.list.columns.status}
</th> </th>
<th scope="col" className="p-4"> <th scope="col" className="p-4">
Actions {copy.list.columns.actions}
</th> </th>
</tr> </tr>
</thead> </thead>
@@ -67,9 +78,17 @@ export default async function UsersPage(props: {
<td className="p-4">{user.name}</td> <td className="p-4">{user.name}</td>
<td className="p-4">{user.username}</td> <td className="p-4">{user.username}</td>
<td className="p-4">{user.email}</td> <td className="p-4">{user.email}</td>
<td className="p-4">{user.role}</td>
<td className="p-4"> <td className="p-4">
{user.isActive ? "Active" : "Inactive"} {formatUserRole(
user.role,
copy.roles as UserRoleCopy,
copy.fallback as UserFallbackCopy,
)}
</td>
<td className="p-4">
{user.isActive
? (copy.status as UserStatusCopy).active
: (copy.status as UserStatusCopy).inactive}
</td> </td>
<td className="p-4"> <td className="p-4">
<Link href={`/admin/users/${user.id}/edit`} passHref> <Link href={`/admin/users/${user.id}/edit`} passHref>
+1
View File
@@ -436,6 +436,7 @@ export const en = {
users: { users: {
list: { list: {
title: "Users", title: "Users",
addLabel: "Add User",
empty: "No users found.", empty: "No users found.",
columns: { columns: {
name: "Name", name: "Name",
+1
View File
@@ -441,6 +441,7 @@ export const es = {
users: { users: {
list: { list: {
title: "Usuarios", title: "Usuarios",
addLabel: "Agregar usuario",
empty: "No se encontraron usuarios.", empty: "No se encontraron usuarios.",
columns: { columns: {
name: "Nombre", name: "Nombre",
@@ -0,0 +1,221 @@
import { renderToStaticMarkup } from "react-dom/server"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { en } from "@/i18n/dictionaries/en"
import { es } from "@/i18n/dictionaries/es"
const mocks = vi.hoisted(() => ({
createUserAction: vi.fn(),
updateUserAction: vi.fn(),
resetUserPasswordAction: vi.fn(),
getUserProfileById: vi.fn(),
getI18n: vi.fn(),
push: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
}))
vi.mock("@/i18n/server", () => ({
getI18n: mocks.getI18n,
}))
vi.mock("@/actions/user.actions", () => ({
createUserAction: mocks.createUserAction,
updateUserAction: mocks.updateUserAction,
resetUserPasswordAction: mocks.resetUserPasswordAction,
}))
vi.mock("@/services/user.service", () => ({
getUserProfileById: mocks.getUserProfileById,
}))
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: mocks.push,
}),
notFound: () => {
throw new Error("NOT_FOUND")
},
}))
vi.mock("sonner", () => ({
toast: {
error: mocks.toastError,
success: mocks.toastSuccess,
},
}))
describe("new user form localization", () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" })
})
it("passes server-resolved schema and role copy into the new user form boundary", async () => {
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
renderToStaticMarkup(await NewUserPage())
// The page must pass formCopy, schemaCopy, and roleLabels to the form
// We verify this by checking the form renders localized content
})
it("renders new user page with localized title and form labels in Spanish", async () => {
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
const html = renderToStaticMarkup(await NewUserPage())
// Title
expect(html).toContain("Nuevo usuario")
// Form labels from dictionary
expect(html).toContain("Nombre")
expect(html).toContain("Usuario")
expect(html).toContain("Correo electrónico")
expect(html).toContain("Contraseña")
expect(html).toContain("Rol")
// Placeholders from dictionary
expect(html).toContain("Nombre completo")
expect(html).toContain("Mínimo 8 caracteres")
// Role labels (display) with canonical values
expect(html).toContain("Administrador")
expect(html).toContain("Gerente")
expect(html).toContain("Personal")
expect(html).toContain("Visor")
// Submit button text
expect(html).toContain("Crear usuario")
})
it("renders new user page with English form labels in English locale", async () => {
mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" })
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
const html = renderToStaticMarkup(await NewUserPage())
expect(html).toContain("New User")
expect(html).toContain("Full name")
expect(html).toContain("Username")
expect(html).toContain("Password")
expect(html).toContain("Minimum 8 characters")
expect(html).toContain("Create User")
expect(html).toContain("Admin")
expect(html).toContain("Manager")
expect(html).toContain("Staff")
expect(html).toContain("Viewer")
})
it("keeps canonical role values in option value attributes, not localized labels", async () => {
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
const html = renderToStaticMarkup(await NewUserPage())
// Canonical values must be in value attributes
expect(html).toContain('value="ADMIN"')
expect(html).toContain('value="MANAGER"')
expect(html).toContain('value="STAFF"')
expect(html).toContain('value="VIEWER"')
})
})
describe("edit user form localization", () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" })
mocks.getUserProfileById.mockResolvedValue({
id: "user-1",
name: "Ada Lovelace",
username: "ada",
email: "ada@example.test",
role: "ADMIN",
isActive: true,
})
})
it("renders edit user page with localized title, form labels, and reset-password section in Spanish", async () => {
const { default: EditUserPage } = await import(
"@/app/(dashboard)/admin/users/[userId]/edit/page"
)
const html = renderToStaticMarkup(
await EditUserPage({
params: Promise.resolve({ userId: "user-1" }),
}),
)
// Title
expect(html).toContain("Editar usuario")
// Form labels
expect(html).toContain("Nombre")
expect(html).toContain("Nueva contraseña")
// Role labels with canonical values
expect(html).toContain("Administrador")
expect(html).toContain('value="ADMIN"')
// Active user checkbox label
expect(html).toContain("Usuario activo")
// Submit button
expect(html).toContain("Actualizar usuario")
// Reset password section
expect(html).toContain("Restablecer contraseña")
expect(html).toContain("Nueva contraseña")
expect(html).toContain("Mínimo 8 caracteres")
})
it("renders edit user page with English labels in English locale", async () => {
mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" })
const { default: EditUserPage } = await import(
"@/app/(dashboard)/admin/users/[userId]/edit/page"
)
const html = renderToStaticMarkup(
await EditUserPage({
params: Promise.resolve({ userId: "user-1" }),
}),
)
expect(html).toContain("Edit User")
expect(html).toContain("Active user")
expect(html).toContain("Update User")
expect(html).toContain("Reset password")
expect(html).toContain("New password")
expect(html).toContain("Reset Password")
})
it("renders edit user form with role option values as canonical enums regardless of locale", async () => {
const { default: EditUserPage } = await import(
"@/app/(dashboard)/admin/users/[userId]/edit/page"
)
const html = renderToStaticMarkup(
await EditUserPage({
params: Promise.resolve({ userId: "user-1" }),
}),
)
// Canonical role values
expect(html).toContain('value="ADMIN"')
expect(html).toContain('value="MANAGER"')
expect(html).toContain('value="STAFF"')
expect(html).toContain('value="VIEWER"')
// Spanish labels for roles
expect(html).toContain("Administrador")
})
})
+191
View File
@@ -0,0 +1,191 @@
import { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { en } from "@/i18n/dictionaries/en"
import { es } from "@/i18n/dictionaries/es"
import type { getUsers as _getUsers } from "@/services/user.service"
type UserData = Awaited<ReturnType<typeof _getUsers>>["data"][number]
const mocks = vi.hoisted(() => ({
getUsers: vi.fn(),
getI18n: vi.fn(),
}))
vi.mock("@/i18n/server", () => ({
getI18n: mocks.getI18n,
}))
vi.mock("@/services/user.service", () => ({
getUsers: mocks.getUsers,
}))
vi.mock("@/components/common/pageheader", () => ({
default: ({ title, addLabel }: { title?: string; addLabel?: string }) =>
createElement(
"header",
null,
[title, addLabel].filter(Boolean).join(" | "),
),
}))
vi.mock("@/components/common/pagination", () => ({
default: ({ totalPages }: { totalPages: number }) =>
createElement("nav", { "aria-label": "Pagination" }, totalPages),
}))
describe("user pages localization", () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" })
})
it("renders the user list in Spanish with localized headers, status/role labels, and unchanged user data", async () => {
const { default: UsersPage } = await import(
"@/app/(dashboard)/admin/users/page"
)
mocks.getUsers.mockResolvedValue({
data: [
{
id: "user-1",
name: "Ada Lovelace",
username: "ada",
email: "ada@example.test",
role: "ADMIN",
isActive: true,
},
{
id: "user-2",
name: "Grace Hopper",
username: "grace",
email: "grace@example.test",
role: "STAFF",
isActive: false,
},
],
totalPages: 1,
})
const html = renderToStaticMarkup(
await UsersPage({ searchParams: Promise.resolve({}) }),
)
// Title and add label
expect(html).toContain("Usuarios")
expect(html).toContain("Agregar usuario")
// Table headers from dictionary
expect(html).toContain("Nombre")
expect(html).toContain("Usuario")
expect(html).toContain("Correo electrónico")
expect(html).toContain("Rol")
expect(html).toContain("Estado")
expect(html).toContain("Acciones")
// Status labels from dictionary (display-only, not canonical)
expect(html).toContain("Activo")
expect(html).toContain("Inactivo")
// Role labels from dictionary (display-only, not canonical)
expect(html).toContain("Administrador")
expect(html).toContain("Personal")
// User data is never translated
expect(html).toContain("Ada Lovelace")
expect(html).toContain("ada")
expect(html).toContain("ada@example.test")
expect(html).toContain("Grace Hopper")
expect(html).toContain("grace")
expect(html).toContain("grace@example.test")
// Canonical role values must NOT appear as display text
expect(html).not.toContain(">ADMIN<")
expect(html).not.toContain(">STAFF<")
})
it("renders the localized user empty state when no users exist", async () => {
const { default: UsersPage } = await import(
"@/app/(dashboard)/admin/users/page"
)
mocks.getUsers.mockResolvedValue({
data: [],
totalPages: 0,
})
const html = renderToStaticMarkup(
await UsersPage({ searchParams: Promise.resolve({}) }),
)
expect(html).toContain("No se encontraron usuarios.")
})
it("renders the user list in English with English dictionary labels", async () => {
const { default: UsersPage } = await import(
"@/app/(dashboard)/admin/users/page"
)
mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" })
mocks.getUsers.mockResolvedValue({
data: [
{
id: "user-1",
name: "Ada Lovelace",
username: "ada",
email: "ada@example.test",
role: "MANAGER",
isActive: true,
},
],
totalPages: 1,
})
const html = renderToStaticMarkup(
await UsersPage({ searchParams: Promise.resolve({}) }),
)
// English dictionary labels
expect(html).toContain("Users")
expect(html).toContain("Add User")
expect(html).toContain("Name")
expect(html).toContain("Username")
expect(html).toContain("Email")
expect(html).toContain("Role")
expect(html).toContain("Status")
expect(html).toContain("Actions")
expect(html).toContain("Active")
expect(html).toContain("Manager")
// Canonical enum value must NOT appear as display text
expect(html).not.toContain(">MANAGER<")
})
it("renders unknown role via fallback when role is not in dictionary", async () => {
const { default: UsersPage } = await import(
"@/app/(dashboard)/admin/users/page"
)
mocks.getUsers.mockResolvedValue({
data: [
{
id: "user-1",
name: "Test User",
username: "testuser",
email: "test@example.test",
role: "UNKNOWN_ROLE",
isActive: true,
} as unknown as UserData,
],
totalPages: 1,
})
const html = renderToStaticMarkup(
await UsersPage({ searchParams: Promise.resolve({}) }),
)
// Unknown role should use fallback
expect(html).toContain("Rol desconocido")
})
})
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest"
import { formatUserRole } from "@/app/(dashboard)/admin/users/_components/user.copy"
describe("user copy helpers", () => {
const roleCopy = {
ADMIN: "Administrador",
MANAGER: "Gerente",
STAFF: "Personal",
VIEWER: "Visor",
}
const fallbackCopy = {
unknownRole: "Rol desconocido",
}
it("formats known role values with localized display labels", () => {
expect(formatUserRole("ADMIN", roleCopy, fallbackCopy)).toBe(
"Administrador",
)
expect(formatUserRole("STAFF", roleCopy, fallbackCopy)).toBe("Personal")
})
it("falls back for unknown role values without exposing the raw enum value", () => {
expect(formatUserRole("UNKNOWN_ROLE", roleCopy, fallbackCopy)).toBe(
"Rol desconocido",
)
})
it("falls back for null role values", () => {
expect(
formatUserRole(null as unknown as string, roleCopy, fallbackCopy),
).toBe("Rol desconocido")
})
})
@@ -8,6 +8,7 @@ describe("admin users dictionary", () => {
expect(users.list).toEqual({ expect(users.list).toEqual({
title: "Users", title: "Users",
addLabel: "Add User",
empty: "No users found.", empty: "No users found.",
columns: { columns: {
name: "Name", name: "Name",
@@ -95,6 +96,7 @@ describe("admin users dictionary", () => {
expect(users.list).toEqual({ expect(users.list).toEqual({
title: "Usuarios", title: "Usuarios",
addLabel: "Agregar usuario",
empty: "No se encontraron usuarios.", empty: "No se encontraron usuarios.",
columns: { columns: {
name: "Nombre", name: "Nombre",