feat: unify Person and User creation form with conditional password

This commit is contained in:
2026-06-16 21:48:59 +02:00
parent e5717461cf
commit 1f5a849bf5
21 changed files with 462 additions and 171 deletions
+3 -6
View File
@@ -64,18 +64,15 @@ export async function createNewPerson(formData: CreatePersonFormType) {
} }
} }
export async function createPersonUserAction( export async function createPersonUserAction(formData: UnifiedCreateFormType) {
formData: UnifiedCreateFormType,
) {
const { dictionary } = await getI18n() const { dictionary } = await getI18n()
const userCopy = dictionary.admin.users const userCopy = dictionary.admin.users
const schemaCopy = { const schemaCopy = {
...userCopy.schema, ...userCopy.schema,
...dictionary.inventory.people.schema, ...dictionary.inventory.people.schema,
} }
const validatedFields = buildUnifiedCreateSchema(schemaCopy).safeParse( const validatedFields =
formData, buildUnifiedCreateSchema(schemaCopy).safeParse(formData)
)
if (!validatedFields.success) { if (!validatedFields.success) {
return { return {
+4 -16
View File
@@ -72,27 +72,15 @@ export function localizeUnifiedCreateFieldErrors(
field, field,
messages.map((message) => { messages.map((message) => {
// Schema-level validation messages come from schemaCopy // Schema-level validation messages come from schemaCopy
if ( if (field === "firstName" && message === schemaCopy.firstNameRequired)
field === "firstName" &&
message === schemaCopy.firstNameRequired
)
return message return message
if ( if (field === "lastName" && message === schemaCopy.lastNameRequired)
field === "lastName" &&
message === schemaCopy.lastNameRequired
)
return message return message
if ( if (field === "department" && message === schemaCopy.departmentRequired)
field === "department" &&
message === schemaCopy.departmentRequired
)
return message return message
if (field === "email" && message === schemaCopy.emailInvalid) if (field === "email" && message === schemaCopy.emailInvalid)
return message return message
if ( if (field === "password" && message === schemaCopy.passwordMinLength)
field === "password" &&
message === schemaCopy.passwordMinLength
)
return message return message
// Action-level messages (like "Email already exists") come from action copy // Action-level messages (like "Email already exists") come from action copy
@@ -6,38 +6,53 @@ 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"
import { createUserAction } from "@/actions/user.actions" import { createPersonUserAction } from "@/actions/person.actions"
import { import {
SubmitButton, SubmitButton,
type SubmitButtonCopy, type SubmitButtonCopy,
} from "@/components/forms/submitButton" } from "@/components/forms/submitButton"
import { PERSON_DEPARTMENTS } from "@/lib/constants"
import { import {
buildCreateUserSchema, buildUnifiedCreateSchema,
type CreateUserFormType, type UnifiedCreateFormType,
type UserSchemaCopy, type UnifiedSchemaCopy,
} from "@/schemas/user.schema" } from "@/schemas/user.schema"
import type { UserFormCopy, UserRoleCopy } from "./user.copy" import {
formatPersonDepartment,
type PersonDepartmentCopy,
type PersonFallbackCopy,
type UserFormCopy,
type UserRoleCopy,
} from "./user.copy"
export default function NewUserForm({ export default function NewUserForm({
formCopy, formCopy,
schemaCopy, schemaCopy,
roleLabels, roleLabels,
departmentCopy,
fallbackCopy,
submitButtonCopy, submitButtonCopy,
}: { }: {
formCopy: UserFormCopy formCopy: UserFormCopy
schemaCopy: UserSchemaCopy schemaCopy: UnifiedSchemaCopy
roleLabels: UserRoleCopy roleLabels: UserRoleCopy
departmentCopy: PersonDepartmentCopy
fallbackCopy: PersonFallbackCopy
submitButtonCopy: SubmitButtonCopy submitButtonCopy: SubmitButtonCopy
}) { }) {
const router = useRouter() const router = useRouter()
const schema = useMemo(() => buildCreateUserSchema(schemaCopy), [schemaCopy]) const schema = useMemo(
() => buildUnifiedCreateSchema(schemaCopy),
[schemaCopy],
)
const { const {
register, register,
handleSubmit, handleSubmit,
watch,
setError, setError,
formState: { errors, isSubmitting, isSubmitSuccessful }, formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<CreateUserFormType>({ } = useForm<UnifiedCreateFormType>({
resolver: zodResolver(schema), resolver: zodResolver(schema),
defaultValues: { defaultValues: {
role: "STAFF", role: "STAFF",
@@ -45,13 +60,16 @@ export default function NewUserForm({
}, },
}) })
const onSubmit = async (formData: CreateUserFormType) => { const selectedRole = watch("role")
const response = await createUserAction(formData) const showPassword = selectedRole !== "NO_USER"
const onSubmit = async (formData: UnifiedCreateFormType) => {
const response = await createPersonUserAction(formData)
if (response?.errors) { if (response?.errors) {
Object.entries(response.errors).forEach(([fieldName, messages]) => { Object.entries(response.errors).forEach(([fieldName, messages]) => {
messages.forEach((message: string) => { messages.forEach((message: string) => {
setError(fieldName as keyof CreateUserFormType, { setError(fieldName as keyof UnifiedCreateFormType, {
type: "server", type: "server",
message, message,
}) })
@@ -70,11 +88,25 @@ export default function NewUserForm({
return ( return (
<form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}> <form className="flex flex-col gap-4" onSubmit={handleSubmit(onSubmit)}>
<UserTextInput <UserTextInput
error={errors.name?.message} error={errors.firstName?.message}
id="name" id="firstName"
label={formCopy.nameLabel} label={formCopy.firstNameLabel}
placeholder={formCopy.namePlaceholder} placeholder={formCopy.firstNamePlaceholder}
register={register("name")} register={register("firstName")}
/>
<UserTextInput
error={errors.lastName?.message}
id="lastName"
label={formCopy.lastNameLabel}
placeholder={formCopy.lastNamePlaceholder}
register={register("lastName")}
/>
<DepartmentSelect
error={errors.department?.message}
formCopy={formCopy}
departmentCopy={departmentCopy}
fallbackCopy={fallbackCopy}
register={register("department")}
/> />
<UserTextInput <UserTextInput
error={errors.email?.message} error={errors.email?.message}
@@ -85,18 +117,27 @@ export default function NewUserForm({
type="email" type="email"
/> />
<UserTextInput <UserTextInput
error={errors.password?.message} error={errors.phone?.message}
id="password" id="phone"
label={formCopy.passwordLabel} label={formCopy.phoneLabel}
placeholder={formCopy.passwordPlaceholder} placeholder={formCopy.phonePlaceholder}
register={register("password")} register={register("phone")}
type="password"
/> />
<RoleSelect <RoleSelect
register={register("role")} register={register("role")}
roleLabel={formCopy.roleLabel} roleLabel={formCopy.roleLabel}
roleLabels={roleLabels} roleLabels={roleLabels}
/> />
{showPassword && (
<UserTextInput
error={errors.password?.message}
id="password"
label={formCopy.passwordLabel}
placeholder={formCopy.passwordPlaceholder}
register={register("password")}
type="password"
/>
)}
<SubmitButton <SubmitButton
copy={submitButtonCopy} copy={submitButtonCopy}
isSubmitting={isSubmitting} isSubmitting={isSubmitting}
@@ -163,7 +204,43 @@ function RoleSelect({
<option value="MANAGER">{roleLabels.MANAGER}</option> <option value="MANAGER">{roleLabels.MANAGER}</option>
<option value="STAFF">{roleLabels.STAFF}</option> <option value="STAFF">{roleLabels.STAFF}</option>
<option value="VIEWER">{roleLabels.VIEWER}</option> <option value="VIEWER">{roleLabels.VIEWER}</option>
<option value="NO_USER">{roleLabels.NO_USER}</option>
</select> </select>
</div> </div>
) )
} }
function DepartmentSelect({
error,
formCopy,
departmentCopy,
fallbackCopy,
register,
}: {
error?: string
formCopy: UserFormCopy
departmentCopy: PersonDepartmentCopy
fallbackCopy: PersonFallbackCopy
register: UseFormRegisterReturn
}) {
return (
<div className="flex flex-col gap-2">
<label htmlFor="department" className="mb-2 block text-lg">
{formCopy.departmentLabel}
</label>
<select
id="department"
{...register}
className={`w-full rounded-lg border px-4 py-2 ${error ? "border-error" : ""}`}
>
<option value="">{formCopy.departmentPlaceholder}</option>
{Object.keys(PERSON_DEPARTMENTS).map((department) => (
<option key={department} value={department}>
{formatPersonDepartment(department, departmentCopy, fallbackCopy)}
</option>
))}
</select>
{error && <p className="text-error">{error}</p>}
</div>
)
}
@@ -6,6 +6,9 @@ export type UserStatusCopy = Dictionary["admin"]["users"]["status"]
export type UserFallbackCopy = Dictionary["admin"]["users"]["fallback"] export type UserFallbackCopy = Dictionary["admin"]["users"]["fallback"]
export type UserResetPasswordCopy = export type UserResetPasswordCopy =
Dictionary["admin"]["users"]["resetPassword"] Dictionary["admin"]["users"]["resetPassword"]
export type PersonDepartmentCopy =
Dictionary["inventory"]["people"]["departments"]
export type PersonFallbackCopy = Dictionary["inventory"]["people"]["fallback"]
export function formatUserRole( export function formatUserRole(
role: string, role: string,
@@ -16,3 +19,17 @@ export function formatUserRole(
? roleCopy[role as keyof UserRoleCopy] ? roleCopy[role as keyof UserRoleCopy]
: fallbackCopy.unknownRole : fallbackCopy.unknownRole
} }
export function formatPersonDepartment(
department: string | null | undefined,
departmentCopy: PersonDepartmentCopy,
fallbackCopy: PersonFallbackCopy,
): string {
if (!department) {
return fallbackCopy.unknownDepartment
}
return department in departmentCopy
? departmentCopy[department as keyof PersonDepartmentCopy]
: fallbackCopy.unknownDepartment
}
+3 -1
View File
@@ -13,8 +13,10 @@ export default async function NewUserPage() {
</div> </div>
<NewUserForm <NewUserForm
formCopy={copy.form} formCopy={copy.form}
schemaCopy={copy.schema} schemaCopy={{ ...copy.schema, ...dictionary.inventory.people.schema }}
roleLabels={copy.roles} roleLabels={copy.roles}
departmentCopy={dictionary.inventory.people.departments}
fallbackCopy={dictionary.inventory.people.fallback}
submitButtonCopy={dictionary.common.submitButton} submitButtonCopy={dictionary.common.submitButton}
/> />
</div> </div>
+3 -22
View File
@@ -1,24 +1,5 @@
import { getI18n } from "@/i18n/server" import { redirect } from "next/navigation"
import PersonForm from "../_components/person.form" export default function NewPersonPage() {
redirect("/admin/users/new")
export default async function NewPersonPage() {
const { dictionary } = await getI18n()
const copy = dictionary.inventory.people
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<h1 className="text-2xl font-bold">{copy.new.title}</h1>
</div>
<PersonForm
mode="create"
formCopy={copy.form}
schemaCopy={copy.schema}
departmentCopy={copy.departments}
fallbackCopy={copy.fallback}
submitButtonCopy={dictionary.common.submitButton}
/>
</div>
)
} }
+1 -1
View File
@@ -38,7 +38,7 @@ const items: { key: keyof AddMenuCopy; href: string }[] = [
}, },
{ {
key: "person", key: "person",
href: "/people/new", href: "/admin/users/new",
}, },
{ {
key: "assignment", key: "assignment",
+8
View File
@@ -453,8 +453,16 @@ export const en = {
form: { form: {
nameLabel: "Name", nameLabel: "Name",
namePlaceholder: "Full name", namePlaceholder: "Full name",
firstNameLabel: "First Name",
firstNamePlaceholder: "First name",
lastNameLabel: "Last Name",
lastNamePlaceholder: "Last name",
departmentLabel: "Department",
departmentPlaceholder: "Select a department",
emailLabel: "Email", emailLabel: "Email",
emailPlaceholder: "user@example.com", emailPlaceholder: "user@example.com",
phoneLabel: "Phone",
phonePlaceholder: "Phone",
passwordLabel: "Password", passwordLabel: "Password",
passwordPlaceholder: "Minimum 8 characters", passwordPlaceholder: "Minimum 8 characters",
roleLabel: "Role", roleLabel: "Role",
+8
View File
@@ -458,8 +458,16 @@ export const es = {
form: { form: {
nameLabel: "Nombre", nameLabel: "Nombre",
namePlaceholder: "Nombre completo", namePlaceholder: "Nombre completo",
firstNameLabel: "Nombre",
firstNamePlaceholder: "Nombre",
lastNameLabel: "Apellido",
lastNamePlaceholder: "Apellido",
departmentLabel: "Departamento",
departmentPlaceholder: "Selecciona un departamento",
emailLabel: "Correo electrónico", emailLabel: "Correo electrónico",
emailPlaceholder: "usuario@ejemplo.com", emailPlaceholder: "usuario@ejemplo.com",
phoneLabel: "Teléfono",
phonePlaceholder: "Teléfono",
passwordLabel: "Contraseña", passwordLabel: "Contraseña",
passwordPlaceholder: "Mínimo 8 caracteres", passwordPlaceholder: "Mínimo 8 caracteres",
roleLabel: "Rol", roleLabel: "Rol",
+11 -3
View File
@@ -6,8 +6,8 @@ import type {
UpdatePersonFormType, UpdatePersonFormType,
} from "@/schemas/person.schema" } from "@/schemas/person.schema"
import type { UnifiedCreateFormType } from "@/schemas/user.schema" import type { UnifiedCreateFormType } from "@/schemas/user.schema"
import { getUserByEmail } from "@/services/user.service"
import { PersonService } from "@/services/person.service" import { PersonService } from "@/services/person.service"
import { getUserByEmail } from "@/services/user.service"
type FieldErrors = Record<string, string[]> type FieldErrors = Record<string, string[]>
@@ -134,8 +134,16 @@ export async function updatePersonUseCase(
export async function createPersonUserUseCase( export async function createPersonUserUseCase(
input: UnifiedCreateFormType, input: UnifiedCreateFormType,
): Promise<PersonUseCaseResult> { ): Promise<PersonUseCaseResult> {
const { firstName, lastName, department, email, phone, role, password, isActive } = const {
input firstName,
lastName,
department,
email,
phone,
role,
password,
isActive,
} = input
try { try {
return await prisma.$transaction(async (tx) => { return await prisma.$transaction(async (tx) => {
@@ -86,7 +86,9 @@ describe("user use-cases", () => {
await expect(prisma.user.count()).resolves.toBe(1) await expect(prisma.user.count()).resolves.toBe(1)
await expect( await expect(
prisma.user.findUniqueOrThrow({ where: { email: "existing@example.test" } }), prisma.user.findUniqueOrThrow({
where: { email: "existing@example.test" },
}),
).resolves.toMatchObject({ email: "existing@example.test" }) ).resolves.toMatchObject({ email: "existing@example.test" })
}) })
+15 -45
View File
@@ -1,17 +1,12 @@
import { renderToStaticMarkup } from "react-dom/server" import { renderToStaticMarkup } from "react-dom/server"
import { beforeEach, describe, expect, it, vi } from "vitest" import { beforeEach, describe, expect, it, vi } from "vitest"
import { en } from "@/i18n/dictionaries/en"
import { es } from "@/i18n/dictionaries/es" import { es } from "@/i18n/dictionaries/es"
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
getI18n: vi.fn(), getI18n: vi.fn(),
findById: vi.fn(), findById: vi.fn(),
createNewPerson: vi.fn(), redirect: vi.fn(),
updatePerson: vi.fn(),
push: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
})) }))
vi.mock("@/i18n/server", () => ({ vi.mock("@/i18n/server", () => ({
@@ -24,52 +19,39 @@ vi.mock("@/services/person.service", () => ({
}, },
})) }))
vi.mock("@/actions/person.actions", () => ({ vi.mock("next/navigation", () => ({
createNewPerson: mocks.createNewPerson, redirect: mocks.redirect,
updatePerson: mocks.updatePerson, useRouter: () => ({
push: vi.fn(),
}),
})) }))
vi.mock("next/navigation", () => ({ vi.mock("@/actions/person.actions", () => ({
useRouter: () => ({ createNewPerson: vi.fn(),
push: mocks.push, updatePerson: vi.fn(),
}),
})) }))
vi.mock("sonner", () => ({ vi.mock("sonner", () => ({
toast: { toast: {
error: mocks.toastError, error: vi.fn(),
success: mocks.toastSuccess, success: vi.fn(),
}, },
})) }))
describe("person form pages", () => { describe("person pages", () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks() vi.clearAllMocks()
mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" }) mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" })
}) })
it("renders the new person page with Person form copy and no username field", async () => { it("redirects /people/new to /admin/users/new", async () => {
const { default: NewPersonPage } = await import( const { default: NewPersonPage } = await import(
"@/app/(dashboard)/people/new/page" "@/app/(dashboard)/people/new/page"
) )
const html = renderToStaticMarkup(await NewPersonPage()) await NewPersonPage()
// Person form, not Recipient expect(mocks.redirect).toHaveBeenCalledWith("/admin/users/new")
expect(html).toContain("Agregar persona")
// No username label or placeholder
expect(html).not.toContain("Usuario")
expect(html).not.toContain('placeholder="Usuario"')
// Has expected person form fields
expect(html).toContain("Nombre")
expect(html).toContain("Apellido")
expect(html).toContain("Selecciona un departamento")
expect(html).toContain('option value="ENGINEERING"')
expect(html).toContain(">Ingeniería</option>")
// Has department options from PERSON_DEPARTMENTS
expect(html).toContain("Correo electrónico")
expect(html).toContain("Teléfono")
expect(html).toContain("Crear persona")
}) })
it("renders the edit person page with Person heading and no username", async () => { it("renders the edit person page with Person heading and no username", async () => {
@@ -112,16 +94,4 @@ describe("person form pages", () => {
expect(html).toContain("Persona no encontrada") expect(html).toContain("Persona no encontrada")
}) })
it("wires English Person form submit copy through the new page", async () => {
const { default: NewPersonPage } = await import(
"@/app/(dashboard)/people/new/page"
)
mocks.getI18n.mockResolvedValueOnce({ dictionary: en, locale: "en" })
const html = renderToStaticMarkup(await NewPersonPage())
expect(html).toContain("Create Person")
})
}) })
@@ -3,7 +3,6 @@ import { renderToStaticMarkup } from "react-dom/server"
import { beforeEach, describe, expect, it, vi } from "vitest" import { beforeEach, describe, expect, it, vi } from "vitest"
import { en } from "@/i18n/dictionaries/en" import { en } from "@/i18n/dictionaries/en"
import { es } from "@/i18n/dictionaries/es"
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
getI18n: vi.fn(), getI18n: vi.fn(),
@@ -33,23 +32,6 @@ describe("person form schema wiring", () => {
vi.clearAllMocks() vi.clearAllMocks()
}) })
it("passes server-resolved Person schema copy into the new person form boundary", async () => {
mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" })
const { default: NewPersonPage } = await import(
"@/app/(dashboard)/people/new/page"
)
renderToStaticMarkup(await NewPersonPage())
expect(mocks.personForm).toHaveBeenCalledWith(
expect.objectContaining({
mode: "create",
schemaCopy: es.inventory.people.schema,
}),
)
})
it("passes server-resolved Person schema copy into the edit person form boundary", async () => { it("passes server-resolved Person schema copy into the edit person form boundary", async () => {
mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" }) mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" })
mocks.findById.mockResolvedValue({ mocks.findById.mockResolvedValue({
@@ -0,0 +1,125 @@
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(() => ({
createPersonUser: vi.fn(),
getI18n: vi.fn(),
push: vi.fn(),
toastError: vi.fn(),
toastSuccess: vi.fn(),
}))
vi.mock("@/i18n/server", () => ({
getI18n: mocks.getI18n,
}))
vi.mock("@/actions/person.actions", () => ({
createPersonUserAction: mocks.createPersonUser,
}))
vi.mock("@/services/person.service", () => ({
PersonService: {
findById: vi.fn(),
},
}))
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: mocks.push,
}),
}))
vi.mock("sonner", () => ({
toast: {
error: mocks.toastError,
success: mocks.toastSuccess,
},
}))
describe("unified creation form page", () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" })
})
it("renders unified form with Person fields, email, password, role, and NO_USER option in Spanish", async () => {
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
const html = renderToStaticMarkup(await NewUserPage())
// Person fields
expect(html).toContain("Nombre")
expect(html).toContain("Apellido")
expect(html).toContain("Departamento")
expect(html).toContain("Teléfono")
// User fields
expect(html).toContain("Correo electrónico")
expect(html).toContain("Contraseña")
expect(html).toContain("Rol")
// NO_USER role option
expect(html).toContain("Sin cuenta de usuario")
expect(html).toContain('value="NO_USER"')
// Other role options still present
expect(html).toContain('value="ADMIN"')
expect(html).toContain('value="MANAGER"')
expect(html).toContain('value="STAFF"')
expect(html).toContain('value="VIEWER"')
})
it("renders unified form with Person fields and NO_USER option in English", async () => {
mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" })
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
const html = renderToStaticMarkup(await NewUserPage())
// Person fields
expect(html).toContain("First Name")
expect(html).toContain("Last Name")
expect(html).toContain("Department")
expect(html).toContain("Phone")
// User fields
expect(html).toContain("Password")
expect(html).toContain("Email")
// NO_USER role option
expect(html).toContain("No user account")
expect(html).toContain('value="NO_USER"')
})
it("renders Person field placeholders from the unified form dictionary", async () => {
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
const html = renderToStaticMarkup(await NewUserPage())
// Person field placeholders
expect(html).toContain('placeholder="Nombre"') // firstNamePlaceholder (es)
expect(html).toContain('placeholder="Apellido"') // lastNamePlaceholder (es)
expect(html).toContain("Selecciona un departamento") // departmentPlaceholder
expect(html).toContain('placeholder="Teléfono"') // phonePlaceholder (es)
})
it("renders department select with all PERSON_DEPARTMENTS values", async () => {
const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page"
)
const html = renderToStaticMarkup(await NewUserPage())
// Department values must use canonical enum values
expect(html).toContain('value="ADMINISTRATION"')
})
})
+36 -27
View File
@@ -5,9 +5,7 @@ import { en } from "@/i18n/dictionaries/en"
import { es } from "@/i18n/dictionaries/es" import { es } from "@/i18n/dictionaries/es"
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
createUserAction: vi.fn(), createPersonUser: vi.fn(),
updateUserAction: vi.fn(),
resetUserPasswordAction: vi.fn(),
getUserProfileById: vi.fn(), getUserProfileById: vi.fn(),
getI18n: vi.fn(), getI18n: vi.fn(),
push: vi.fn(), push: vi.fn(),
@@ -19,10 +17,19 @@ vi.mock("@/i18n/server", () => ({
getI18n: mocks.getI18n, getI18n: mocks.getI18n,
})) }))
vi.mock("@/actions/person.actions", () => ({
createPersonUserAction: mocks.createPersonUser,
}))
vi.mock("@/actions/user.actions", () => ({ vi.mock("@/actions/user.actions", () => ({
createUserAction: mocks.createUserAction, updateUserAction: vi.fn(),
updateUserAction: mocks.updateUserAction, resetUserPasswordAction: vi.fn(),
resetUserPasswordAction: mocks.resetUserPasswordAction, }))
vi.mock("@/services/person.service", () => ({
PersonService: {
findById: vi.fn(),
},
})) }))
vi.mock("@/services/user.service", () => ({ vi.mock("@/services/user.service", () => ({
@@ -51,18 +58,7 @@ describe("new user form localization", () => {
mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" }) mocks.getI18n.mockResolvedValue({ dictionary: es, locale: "es" })
}) })
it("passes server-resolved schema and role copy into the new user form boundary", async () => { it("renders new user page with localized title and unified form labels in Spanish", 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( const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page" "@/app/(dashboard)/admin/users/new/page"
) )
@@ -72,27 +68,29 @@ describe("new user form localization", () => {
// Title // Title
expect(html).toContain("Nuevo usuario") expect(html).toContain("Nuevo usuario")
// Form labels from dictionary // Person field labels
expect(html).toContain("Nombre") expect(html).toContain("Nombre")
expect(html).toContain("Apellido")
expect(html).toContain("Departamento")
expect(html).toContain("Teléfono")
// User field labels
expect(html).toContain("Correo electrónico") expect(html).toContain("Correo electrónico")
expect(html).toContain("Contraseña") expect(html).toContain("Contraseña")
expect(html).toContain("Rol") 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 // Role labels (display) with canonical values
expect(html).toContain("Administrador") expect(html).toContain("Administrador")
expect(html).toContain("Gerente") expect(html).toContain("Gerente")
expect(html).toContain("Personal") expect(html).toContain("Personal")
expect(html).toContain("Visor") expect(html).toContain("Visor")
expect(html).toContain("Sin cuenta de usuario")
// Submit button text // Submit button text
expect(html).toContain("Crear usuario") expect(html).toContain("Crear usuario")
}) })
it("renders new user page with English form labels in English locale", async () => { it("renders new user page with English unified form labels in English locale", async () => {
mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" }) mocks.getI18n.mockResolvedValue({ dictionary: en, locale: "en" })
const { default: NewUserPage } = await import( const { default: NewUserPage } = await import(
@@ -102,17 +100,27 @@ describe("new user form localization", () => {
const html = renderToStaticMarkup(await NewUserPage()) const html = renderToStaticMarkup(await NewUserPage())
expect(html).toContain("New User") expect(html).toContain("New User")
expect(html).toContain("Full name")
// Person fields
expect(html).toContain("First Name")
expect(html).toContain("Last Name")
expect(html).toContain("Department")
expect(html).toContain("Phone")
// User fields
expect(html).toContain("Email")
expect(html).toContain("Password") expect(html).toContain("Password")
expect(html).toContain("Minimum 8 characters") expect(html).toContain("Role")
expect(html).toContain("Create User") expect(html).toContain("Create User")
expect(html).toContain("Admin") expect(html).toContain("Admin")
expect(html).toContain("Manager") expect(html).toContain("Manager")
expect(html).toContain("Staff") expect(html).toContain("Staff")
expect(html).toContain("Viewer") expect(html).toContain("Viewer")
expect(html).toContain("No user account")
}) })
it("keeps canonical role values in option value attributes, not localized labels", async () => { it("keeps canonical role values in option value attributes including NO_USER, not localized labels", async () => {
const { default: NewUserPage } = await import( const { default: NewUserPage } = await import(
"@/app/(dashboard)/admin/users/new/page" "@/app/(dashboard)/admin/users/new/page"
) )
@@ -124,6 +132,7 @@ describe("new user form localization", () => {
expect(html).toContain('value="MANAGER"') expect(html).toContain('value="MANAGER"')
expect(html).toContain('value="STAFF"') expect(html).toContain('value="STAFF"')
expect(html).toContain('value="VIEWER"') expect(html).toContain('value="VIEWER"')
expect(html).toContain('value="NO_USER"')
}) })
}) })
+48 -1
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest" import { describe, expect, it } from "vitest"
import { formatUserRole } from "@/app/(dashboard)/admin/users/_components/user.copy" import {
formatPersonDepartment,
formatUserRole,
} from "@/app/(dashboard)/admin/users/_components/user.copy"
describe("user copy helpers", () => { describe("user copy helpers", () => {
const roleCopy = { const roleCopy = {
@@ -34,3 +37,47 @@ describe("user copy helpers", () => {
).toBe("Rol desconocido") ).toBe("Rol desconocido")
}) })
}) })
describe("formatPersonDepartment helper", () => {
const departmentCopy = {
IT: "IT",
ENGINEERING: "Ingeniería",
LOGISTICS: "Logística",
TRAFFIC: "Tráfico",
DRIVER: "Chofer",
ADMINISTRATION: "Administración",
SALES: "Ventas",
OTHER: "Otro",
}
const fallbackCopy = {
unknownDepartment: "Departamento desconocido",
}
it("formats known department values with localized labels", () => {
expect(
formatPersonDepartment("ENGINEERING", departmentCopy, fallbackCopy),
).toBe("Ingeniería")
expect(
formatPersonDepartment("ADMINISTRATION", departmentCopy, fallbackCopy),
).toBe("Administración")
})
it("falls back for unknown department values", () => {
expect(
formatPersonDepartment("UNKNOWN_DEPT", departmentCopy, fallbackCopy),
).toBe("Departamento desconocido")
})
it("falls back for null department values", () => {
expect(formatPersonDepartment(null, departmentCopy, fallbackCopy)).toBe(
"Departamento desconocido",
)
})
it("falls back for undefined department values", () => {
expect(
formatPersonDepartment(undefined, departmentCopy, fallbackCopy),
).toBe("Departamento desconocido")
})
})
@@ -28,8 +28,16 @@ describe("admin users dictionary", () => {
expect(users.form).toEqual({ expect(users.form).toEqual({
nameLabel: "Name", nameLabel: "Name",
namePlaceholder: "Full name", namePlaceholder: "Full name",
firstNameLabel: "First Name",
firstNamePlaceholder: "First name",
lastNameLabel: "Last Name",
lastNamePlaceholder: "Last name",
departmentLabel: "Department",
departmentPlaceholder: "Select a department",
emailLabel: "Email", emailLabel: "Email",
emailPlaceholder: "user@example.com", emailPlaceholder: "user@example.com",
phoneLabel: "Phone",
phonePlaceholder: "Phone",
passwordLabel: "Password", passwordLabel: "Password",
passwordPlaceholder: "Minimum 8 characters", passwordPlaceholder: "Minimum 8 characters",
roleLabel: "Role", roleLabel: "Role",
@@ -112,8 +120,16 @@ describe("admin users dictionary", () => {
expect(users.form).toEqual({ expect(users.form).toEqual({
nameLabel: "Nombre", nameLabel: "Nombre",
namePlaceholder: "Nombre completo", namePlaceholder: "Nombre completo",
firstNameLabel: "Nombre",
firstNamePlaceholder: "Nombre",
lastNameLabel: "Apellido",
lastNamePlaceholder: "Apellido",
departmentLabel: "Departamento",
departmentPlaceholder: "Selecciona un departamento",
emailLabel: "Correo electrónico", emailLabel: "Correo electrónico",
emailPlaceholder: "usuario@ejemplo.com", emailPlaceholder: "usuario@ejemplo.com",
phoneLabel: "Teléfono",
phonePlaceholder: "Teléfono",
passwordLabel: "Contraseña", passwordLabel: "Contraseña",
passwordPlaceholder: "Mínimo 8 caracteres", passwordPlaceholder: "Mínimo 8 caracteres",
roleLabel: "Rol", roleLabel: "Rol",
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest"
import { dictionaries, getDictionary } from "@/i18n/dictionaries"
describe("admin users unified form dictionary", () => {
it("provides unified form Person field keys in English admin.users.form", () => {
const form = getDictionary("en").admin.users.form
expect(form.firstNameLabel).toBe("First Name")
expect(form.firstNamePlaceholder).toBe("First name")
expect(form.lastNameLabel).toBe("Last Name")
expect(form.lastNamePlaceholder).toBe("Last name")
expect(form.departmentLabel).toBe("Department")
expect(form.departmentPlaceholder).toBe("Select a department")
expect(form.phoneLabel).toBe("Phone")
expect(form.phonePlaceholder).toBe("Phone")
})
it("provides unified form Person field keys in Spanish admin.users.form", () => {
const form = getDictionary("es").admin.users.form
expect(form.firstNameLabel).toBe("Nombre")
expect(form.firstNamePlaceholder).toBe("Nombre")
expect(form.lastNameLabel).toBe("Apellido")
expect(form.lastNamePlaceholder).toBe("Apellido")
expect(form.departmentLabel).toBe("Departamento")
expect(form.departmentPlaceholder).toBe("Selecciona un departamento")
expect(form.phoneLabel).toBe("Teléfono")
expect(form.phonePlaceholder).toBe("Teléfono")
})
it("maintains structural parity for admin.users.form between English and Spanish after Person keys", () => {
const enKeys = extractKeyPaths(dictionaries.en.admin.users.form)
const esKeys = extractKeyPaths(dictionaries.es.admin.users.form)
expect(esKeys).toEqual(enKeys)
})
})
function extractKeyPaths(value: unknown, prefix = ""): string[] {
if (!isPlainObject(value)) return [prefix]
return Object.keys(value)
.sort()
.flatMap((key) =>
extractKeyPaths(value[key], prefix ? `${prefix}.${key}` : key),
)
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
+7 -5
View File
@@ -108,13 +108,15 @@ describe("core schemas", () => {
) )
expect( expect(
signInSchema.safeParse({ email: "admin@test.com", password: "abc" }).success, signInSchema.safeParse({ email: "admin@test.com", password: "abc" })
.success,
).toBe(true) ).toBe(true)
expect(signInSchema.safeParse({ email: "", password: "abc" }).success).toBe(
false,
)
expect( expect(
signInSchema.safeParse({ email: "", password: "abc" }).success, signInSchema.safeParse({ email: "admin@test.com", password: "ab" })
).toBe(false) .success,
expect(
signInSchema.safeParse({ email: "admin@test.com", password: "ab" }).success,
).toBe(false) ).toBe(false)
}) })
@@ -2,8 +2,8 @@ import { describe, expect, it } from "vitest"
import { import {
buildUnifiedCreateSchema, buildUnifiedCreateSchema,
unifiedFormRoleSchema,
type UnifiedSchemaCopy, type UnifiedSchemaCopy,
unifiedFormRoleSchema,
} from "@/schemas/user.schema" } from "@/schemas/user.schema"
const enCopy: UnifiedSchemaCopy = { const enCopy: UnifiedSchemaCopy = {