All files / src/features/babies/api babies.schemas.ts

95% Statements 19/20
93.75% Branches 15/16
100% Functions 3/3
95% Lines 19/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108                          28x     28x       28x   28x               28x                                 28x       28x         21x 21x                               21x 42x 42x       21x 10x 8x           28x     28x                 28x   28x            
import { z } from 'zod'
 
import { parseDateString, todayDateString } from '@/lib/date'
import { parseDecimalInput } from '@/shared/utils/measurements'
 
/**
 * Sexo ao nascer — variável clínica, não identidade de gênero, e por isso este nome.
 *
 * Ausente significa "não informado", e é resposta legítima: o campo não é lido por nada no app e
 * exigir dado sensível de uma criança sem uso é coleta que não se justifica. Não existe um terceiro
 * valor de enum para isso — ausência já é a forma de dizer, e duas formas de dizer a mesma coisa no
 * mesmo campo é o começo de uma consulta errada.
 */
export const sexAtBirthSchema = z.enum(['MALE', 'FEMALE'])
export type SexAtBirth = z.infer<typeof sexAtBirthSchema>
 
export const bloodTypeSchema = z.enum(['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'])
export type BloodType = z.infer<typeof bloodTypeSchema>
 
// Matches the backend's validation for `avatarColor` — a hex color used as the avatar's border.
export const avatarColorHexRegex = /^#[0-9A-Fa-f]{6}$/
 
export const babyMeasurementSchema = z.object({
  id: z.string().uuid(),
  measuredOn: z.string().date(),
  weightGrams: z.number().int().nullable(),
  heightMillimeters: z.number().int().nullable(),
})
export type BabyMeasurement = z.infer<typeof babyMeasurementSchema>
 
export const babySchema = z.object({
  measurements: z.array(babyMeasurementSchema).default([]),
  id: z.string().uuid(),
  userId: z.string().uuid(),
  name: z.string(),
  birthDate: z.string(),
  sexAtBirth: sexAtBirthSchema.nullable(),
  bloodType: bloodTypeSchema.nullable(),
  allergies: z.array(z.string()),
  healthPlanName: z.string().nullable(),
  healthPlanNumber: z.string().nullable(),
  avatarUrl: z.string().nullable(),
  avatarColor: z.string().nullable(),
  createdAt: z.string(),
})
export type Baby = z.infer<typeof babySchema>
 
export const babyListSchema = z.array(babySchema)
 
// Shared by both the create and edit flows — the form always collects the
// same fields; only the API call (POST vs PATCH) differs.
export const babyFormSchema = z.object({
  name: z.string().trim().min(1),
  birthDate: z
    .string()
    .regex(/^\d{4}-\d{2}-\d{2}$/)
    .refine((value) => !!parseDateString(value))
    .refine((value) => value <= todayDateString(), { message: 'babies.form.birthDateFuture' }),
  sexAtBirth: sexAtBirthSchema.optional(),
  bloodType: bloodTypeSchema.optional(),
  allergies: z.array(z.string().min(1)).optional(),
  // Free text, both of them: a plan's name is whatever is printed on the card, and the member
  // number carries letters, dashes and leading zeros depending on the operator. Anything narrower
  // would reject valid cards, which is the one thing this field cannot afford to do.
  healthPlanName: z.string().optional(),
  healthPlanNumber: z.string().optional(),
  // A native <input> always yields "" (never undefined) when left blank.
  avatarUrl: z.union([z.string().url(), z.literal('')]).optional(),
  avatarColor: z.union([z.string().regex(avatarColorHexRegex), z.literal('')]).optional(),
  weightKg: z.string().optional(),
  heightCm: z.string().optional(),
  measuredOn: z.string().optional(),
}).superRefine((values, ctx) => {
  for (const [path, min, max] of [['weightKg', 0.1, 150], ['heightCm', 10, 250]] as const) {
    const number = parseDecimalInput(values[path])
    Iif (number !== null && (!Number.isFinite(number) || number < min || number > max)) {
      ctx.addIssue({ code: 'custom', path: [path], message: `babies.editor.${path}Error` })
    }
  }
  if (values.weightKg?.trim() || values.heightCm?.trim()) {
    if (!values.measuredOn || !parseDateString(values.measuredOn) || values.measuredOn < values.birthDate || values.measuredOn > todayDateString()) {
      ctx.addIssue({ code: 'custom', path: ['measuredOn'], message: 'babies.editor.dateError' })
    }
  }
})
export type BabyFormInput = z.infer<typeof babyFormSchema>
 
export const guardianRoleSchema = z.enum(['OWNER', 'GUARDIAN'])
export type GuardianRole = z.infer<typeof guardianRoleSchema>
 
export const guardianSchema = z.object({
  userId: z.string().uuid(),
  name: z.string(),
  email: z.string().email(),
  role: guardianRoleSchema,
  joinedAt: z.string(),
})
export type Guardian = z.infer<typeof guardianSchema>
 
export const guardianListSchema = z.array(guardianSchema)
 
export const createInviteResponseSchema = z.object({
  code: z.string(),
  expiresAt: z.string(),
})
export type CreateInviteResponse = z.infer<typeof createInviteResponseSchema>