feat(i18n): localize recipient validation messages

This commit is contained in:
2026-06-14 22:41:20 +02:00
parent c0ae7a034a
commit 9b713c42e2
13 changed files with 525 additions and 51 deletions
+31 -10
View File
@@ -2,19 +2,26 @@
import { revalidatePath } from "next/cache"
import { getI18n } from "@/i18n/server"
import {
buildCreateRecipientSchema,
buildUpdateRecipientSchema,
type CreateRecipientFormType,
createRecipientSchema,
type UpdateRecipientFormType,
updateRecipientSchema,
} from "@/schemas/recipient.schema"
import {
createRecipientUseCase,
updateRecipientUseCase,
} from "@/use-cases/recipient.use-cases"
import { localizeRecipientFieldErrors } from "./recipient.messages"
export async function createNewRecipient(formData: CreateRecipientFormType) {
const validatedFields = createRecipientSchema.safeParse(formData)
const { dictionary } = await getI18n()
const copy = dictionary.inventory.recipients
const validatedFields = buildCreateRecipientSchema(copy.schema).safeParse(
formData,
)
if (!validatedFields.success) {
return {
@@ -27,25 +34,34 @@ export async function createNewRecipient(formData: CreateRecipientFormType) {
const result = await createRecipientUseCase(validatedFields.data)
if (!result.success) {
return result
return {
...result,
errors: localizeRecipientFieldErrors(result.errors, copy.actions),
message: copy.actions.createFailure,
}
}
revalidatePath("/recipients")
return {
success: true,
message: "Recipient created successfully",
message: copy.actions.createSuccess,
}
} catch (error) {
console.error("Database error:", error)
return {
message: "Failed to create recipient",
success: false,
message: copy.actions.createFailure,
}
}
}
export async function updateRecipient(formData: UpdateRecipientFormType) {
const validatedFields = updateRecipientSchema.safeParse(formData)
const { dictionary } = await getI18n()
const copy = dictionary.inventory.recipients
const validatedFields = buildUpdateRecipientSchema(copy.schema).safeParse(
formData,
)
if (!validatedFields.success) {
return {
@@ -58,19 +74,24 @@ export async function updateRecipient(formData: UpdateRecipientFormType) {
const result = await updateRecipientUseCase(validatedFields.data)
if (!result.success) {
return result
return {
...result,
errors: localizeRecipientFieldErrors(result.errors, copy.actions),
message: copy.actions.updateFailure,
}
}
revalidatePath("/recipients")
return {
success: true,
message: "Recipient updated successfully",
message: copy.actions.updateSuccess,
}
} catch (error) {
console.error("Database error:", error)
return {
message: "Failed to update recipient",
success: false,
message: copy.actions.updateFailure,
}
}
}
+39
View File
@@ -0,0 +1,39 @@
import type { Dictionary } from "@/i18n/dictionaries"
type RecipientActionCopy = Dictionary["inventory"]["recipients"]["actions"]
type FieldErrors = Record<string, string[]>
const recipientErrorMessageKeys = {
"Username already exists": "duplicateUsername",
"Email already exists": "duplicateEmail",
} as const satisfies Record<string, keyof RecipientActionCopy>
function isRecipientErrorMessage(
message: string,
): message is keyof typeof recipientErrorMessageKeys {
return message in recipientErrorMessageKeys
}
function localizeRecipientMessage(
message: string,
copy: RecipientActionCopy,
): string {
if (!isRecipientErrorMessage(message)) return message
return copy[recipientErrorMessageKeys[message]]
}
export function localizeRecipientFieldErrors(
errors: FieldErrors | undefined,
copy: RecipientActionCopy,
): FieldErrors | undefined {
if (!errors) return undefined
return Object.fromEntries(
Object.entries(errors).map(([field, messages]) => [
field,
messages.map((message) => localizeRecipientMessage(message, copy)),
]),
)
}
@@ -26,6 +26,7 @@ export default async function RecipientEditPage({
initialData={recipient}
mode="edit"
formCopy={copy.form}
schemaCopy={copy.schema}
departmentCopy={copy.departments}
fallbackCopy={copy.fallback}
submitButtonCopy={dictionary.common.submitButton}
@@ -2,6 +2,7 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { useRouter } from "next/navigation"
import { useMemo } from "react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import {
@@ -14,8 +15,10 @@ import {
} from "@/components/forms/submitButton"
import { RECIPIENT_DEPARTMENTS } from "@/lib/constants"
import {
buildCreateRecipientSchema,
buildUpdateRecipientSchema,
type CreateRecipientFormType,
recipientSchema,
type RecipientSchemaCopy,
type UpdateRecipientFormType,
} from "@/schemas/recipient.schema"
import type { Recipient } from "@/types"
@@ -31,6 +34,7 @@ interface RecipientFormProps {
initialData?: Recipient
mode?: "create" | "edit"
formCopy: RecipientFormCopy
schemaCopy: RecipientSchemaCopy
departmentCopy: RecipientDepartmentCopy
fallbackCopy: RecipientFallbackCopy
submitButtonCopy: SubmitButtonCopy
@@ -40,11 +44,19 @@ export default function RecipientForm({
initialData,
mode = "create",
formCopy,
schemaCopy,
departmentCopy,
fallbackCopy,
submitButtonCopy,
}: RecipientFormProps) {
const router = useRouter()
const schema = useMemo(
() =>
mode === "create"
? buildCreateRecipientSchema(schemaCopy)
: buildUpdateRecipientSchema(schemaCopy),
[mode, schemaCopy],
)
const {
register,
@@ -52,7 +64,7 @@ export default function RecipientForm({
setError,
formState: { errors, isSubmitting, isSubmitSuccessful },
} = useForm<CreateRecipientFormType>({
resolver: zodResolver(recipientSchema),
resolver: zodResolver(schema),
defaultValues: {
id: initialData?.id || "",
username: initialData?.username || "",
@@ -14,6 +14,7 @@ export default async function NewRecipientPage() {
<RecipientForm
mode="create"
formCopy={copy.form}
schemaCopy={copy.schema}
departmentCopy={copy.departments}
fallbackCopy={copy.fallback}
submitButtonCopy={dictionary.common.submitButton}
+16
View File
@@ -318,6 +318,22 @@ export const en = {
SALES: "Sales",
OTHER: "Other",
},
actions: {
createSuccess: "Recipient created successfully",
createFailure: "Failed to create recipient",
updateSuccess: "Recipient updated successfully",
updateFailure: "Failed to update recipient",
duplicateUsername: "Username already exists",
duplicateEmail: "Email already exists",
},
schema: {
usernameRequired: "Username is required",
firstNameRequired: "First name is required",
lastNameRequired: "Last name is required",
departmentRequired: "Department is required",
emailInvalid: "Email format is invalid",
idRequired: "ID is required",
},
},
movements: {
list: {
+16
View File
@@ -322,6 +322,22 @@ export const es = {
SALES: "Ventas",
OTHER: "Otro",
},
actions: {
createSuccess: "Destinatario creado correctamente",
createFailure: "Error al crear el destinatario",
updateSuccess: "Destinatario actualizado correctamente",
updateFailure: "Error al actualizar el destinatario",
duplicateUsername: "El nombre de usuario ya existe",
duplicateEmail: "El correo electrónico ya existe",
},
schema: {
usernameRequired: "El usuario es obligatorio",
firstNameRequired: "El nombre es obligatorio",
lastNameRequired: "El apellido es obligatorio",
departmentRequired: "El departamento es obligatorio",
emailInvalid: "El correo electrónico no es válido",
idRequired: "El ID es obligatorio",
},
},
movements: {
list: {
+65 -39
View File
@@ -1,54 +1,80 @@
import { z } from "zod"
export const recipientSchema = z.object({
id: z.string().optional(),
username: z
.string()
.min(1, {
error: "Username is required",
})
.nonempty("Username is required"),
firstName: z.string().min(1, {
error: "First name is required",
}),
lastName: z.string().min(1, {
error: "Last name is required",
}),
department: z.enum(
[
"IT",
"ENGINEERING",
"TRAFFIC",
"DRIVER",
"LOGISTICS",
"ADMINISTRATION",
"SALES",
"OTHER",
],
{
error: "Department is required",
},
),
email: z.string().optional().nullable(),
phone: z.string().optional().nullable(),
})
import type { Dictionary } from "@/i18n/dictionaries"
export const createRecipientSchema = recipientSchema.superRefine(
(data, ctx) => {
export type RecipientSchemaCopy =
Dictionary["inventory"]["recipients"]["schema"]
const defaultRecipientSchemaCopy: RecipientSchemaCopy = {
usernameRequired: "Username is required",
firstNameRequired: "First name is required",
lastNameRequired: "Last name is required",
departmentRequired: "Department is required",
emailInvalid: "Email format is invalid",
idRequired: "ID is required",
}
const recipientDepartments = [
"IT",
"ENGINEERING",
"TRAFFIC",
"DRIVER",
"LOGISTICS",
"ADMINISTRATION",
"SALES",
"OTHER",
] as const
function buildRecipientBaseSchema(copy: RecipientSchemaCopy) {
return z.object({
id: z.string().optional(),
username: z.string().min(1, {
error: copy.usernameRequired,
}),
firstName: z.string().min(1, {
error: copy.firstNameRequired,
}),
lastName: z.string().min(1, {
error: copy.lastNameRequired,
}),
department: z.enum(recipientDepartments, {
error: copy.departmentRequired,
}),
email: z.string().optional().nullable(),
phone: z.string().optional().nullable(),
})
}
export const recipientSchema = buildRecipientBaseSchema(
defaultRecipientSchemaCopy,
)
export function buildCreateRecipientSchema(copy: RecipientSchemaCopy) {
return buildRecipientBaseSchema(copy).superRefine((data, ctx) => {
if (data.email && !z.string().email().safeParse(data.email).success) {
ctx.addIssue({
code: "custom",
message: "Email format is invalid",
message: copy.emailInvalid,
path: ["email"],
})
}
},
})
}
export const createRecipientSchema = buildCreateRecipientSchema(
defaultRecipientSchemaCopy,
)
export type CreateRecipientFormType = z.infer<typeof createRecipientSchema>
export const updateRecipientSchema = recipientSchema.extend({
id: z.string().nonempty("ID is required"),
})
export function buildUpdateRecipientSchema(copy: RecipientSchemaCopy) {
return buildRecipientBaseSchema(copy).extend({
id: z.string().nonempty(copy.idRequired),
})
}
export const updateRecipientSchema = buildUpdateRecipientSchema(
defaultRecipientSchemaCopy,
)
export type UpdateRecipientFormType = z.infer<typeof updateRecipientSchema>