80 lines
2.0 KiB
TypeScript
80 lines
2.0 KiB
TypeScript
import { z } from "zod"
|
|
|
|
import type { Dictionary } from "@/i18n/dictionaries"
|
|
|
|
export type PersonSchemaCopy = Dictionary["inventory"]["people"]["schema"]
|
|
|
|
const defaultPersonSchemaCopy: PersonSchemaCopy = {
|
|
firstNameRequired: "First name is required",
|
|
lastNameRequired: "Last name is required",
|
|
departmentRequired: "Department is required",
|
|
emailInvalid: "Email format is invalid",
|
|
idRequired: "ID is required",
|
|
userIdInvalid: "User ID must be a valid UUID",
|
|
}
|
|
|
|
export const personDepartments = [
|
|
"IT",
|
|
"ENGINEERING",
|
|
"TRAFFIC",
|
|
"DRIVER",
|
|
"LOGISTICS",
|
|
"ADMINISTRATION",
|
|
"SALES",
|
|
"OTHER",
|
|
] as const
|
|
|
|
function buildPersonBaseSchema(copy: PersonSchemaCopy) {
|
|
return z.object({
|
|
id: z.string().optional(),
|
|
firstName: z.string().min(1, {
|
|
error: copy.firstNameRequired,
|
|
}),
|
|
lastName: z.string().min(1, {
|
|
error: copy.lastNameRequired,
|
|
}),
|
|
department: z.enum(personDepartments, {
|
|
error: copy.departmentRequired,
|
|
}),
|
|
email: z.string().optional().nullable(),
|
|
phone: z.string().optional().nullable(),
|
|
userId: z
|
|
.string()
|
|
.uuid({ error: copy.userIdInvalid })
|
|
.optional()
|
|
.nullable(),
|
|
})
|
|
}
|
|
|
|
export const personSchema = buildPersonBaseSchema(defaultPersonSchemaCopy)
|
|
|
|
export function buildCreatePersonSchema(copy: PersonSchemaCopy) {
|
|
return buildPersonBaseSchema(copy).superRefine((data, ctx) => {
|
|
if (data.email && !z.string().email().safeParse(data.email).success) {
|
|
ctx.addIssue({
|
|
code: "custom",
|
|
message: copy.emailInvalid,
|
|
path: ["email"],
|
|
})
|
|
}
|
|
})
|
|
}
|
|
|
|
export const createPersonSchema = buildCreatePersonSchema(
|
|
defaultPersonSchemaCopy,
|
|
)
|
|
|
|
export type CreatePersonFormType = z.infer<typeof createPersonSchema>
|
|
|
|
export function buildUpdatePersonSchema(copy: PersonSchemaCopy) {
|
|
return buildPersonBaseSchema(copy).extend({
|
|
id: z.string().nonempty(copy.idRequired),
|
|
})
|
|
}
|
|
|
|
export const updatePersonSchema = buildUpdatePersonSchema(
|
|
defaultPersonSchemaCopy,
|
|
)
|
|
|
|
export type UpdatePersonFormType = z.infer<typeof updatePersonSchema>
|