All files / src/features/vaccines/components ApplyVaccineDialog.tsx

85.18% Statements 23/27
83.33% Branches 20/24
80% Functions 4/5
92% Lines 23/25

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 109 110 111 112 113 114 115 116 117 118 119 120 121                                                          88x 88x 88x 88x 88x 88x                   88x             88x 14x 6x 6x           88x 6x 6x       6x 6x 4x 4x 6x           88x 88x 88x                         89x                                                          
import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
 
import { Button } from '@/components/ui/button'
import { VaccineDialogLayout } from './VaccineDialogLayout'
import { useBabies } from '@/features/babies/api/babies.hooks'
import { formatDateDisplay, todayDateString } from '@/lib/date'
 
import { useApplyVaccine } from '../api/vaccines.hooks'
import {
  applyVaccineSchema,
  vaccineApplicationDateSchema,
  type ApplyVaccineInput,
  type VaccineItem,
} from '../api/vaccines.schemas'
import { VaccineApplicationDetailsFields } from './VaccineApplicationDetailsFields'
 
interface ApplyVaccineDialogProps {
  babyId: string
  item: VaccineItem | null
  onOpenChange: (open: boolean) => void
  /** Called with the saved dose, before the dialog closes, so the list can show it where it was. */
  onApplied?: (applied: VaccineItem) => void
}
 
export function ApplyVaccineDialog({ babyId, item, onOpenChange, onApplied }: ApplyVaccineDialogProps) {
  const { t, i18n } = useTranslation()
  const babies = useBabies()
  const baby = babies.data?.find((value) => value.id === babyId)
  const [processing, setProcessing] = useState(false)
  const applyVaccine = useApplyVaccine(babyId)
  const resetMutation = applyVaccine.reset
 
  const {
    register,
    control,
    handleSubmit,
    reset,
    watch,
    setError,
    formState: { errors, isDirty, isSubmitting },
  } = useForm<ApplyVaccineInput>({
    resolver: zodResolver(
      applyVaccineSchema.extend({ applicationDate: vaccineApplicationDateSchema.optional() }),
    ),
    defaultValues: { applicationDate: todayDateString(), notes: '' },
  })
 
  useEffect(() => {
    if (item) {
      resetMutation()
      reset({ applicationDate: todayDateString(), notes: '' })
    }
    // A calendar refresh must not replace an in-progress form.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [item?.vaccineId, reset, resetMutation])
 
  const onSubmit = handleSubmit(async (values) => {
    Iif (!item || processing) return
    Iif (!values.applicationDate || (baby && values.applicationDate < baby.birthDate)) {
      setError('applicationDate', { type: 'custom', message: 'vaccines.editor.dateError' })
      return
    }
    try {
      const applied = await applyVaccine.mutateAsync({ vaccineId: item.vaccineId, input: values })
      toast.success(t('vaccines.apply.successToast'))
      onApplied?.(applied)
      onOpenChange(false)
    } catch {
      // surfaced below via applyVaccine.error
    }
  })
 
  const busy = applyVaccine.isPending || processing || isSubmitting
  const date = watch('applicationDate')
  return (
    <VaccineDialogLayout
      open={!!item}
      onOpenChange={onOpenChange}
      title={t('vaccines.apply.title')}
      baby={baby}
      vaccine={item?.name}
      dose={item ? t('vaccines.doseLabel', { count: item.doseNumber }) : undefined}
      date={date ? formatDateDisplay(date, i18n.language) : undefined}
      stage="details"
      dirty={isDirty}
      busy={busy}
      footer={(close) => (
        <>
          <Button type="button" variant="ghost" disabled={busy} onClick={close}>
            {t('common.cancel')}
          </Button>
          <Button type="submit" form="apply-vaccine-form" disabled={busy}>
            {t(busy ? 'common.saving' : 'vaccines.apply.submit')}
          </Button>
        </>
      )}
    >
      {item && (
        <form id="apply-vaccine-form" onSubmit={onSubmit} className="space-y-4" noValidate>
          <VaccineApplicationDetailsFields
            register={register}
            control={control}
            errors={errors}
            onProcessingChange={setProcessing}
          />
 
          {applyVaccine.isError && (
            <p role="alert" className="text-destructive text-sm">
              {t('vaccines.apply.genericError')}
            </p>
          )}
        </form>
      )}
    </VaccineDialogLayout>
  )
}