All files / src/features/appointments/components AppointmentDetailDialog.tsx

85.1% Statements 40/47
87.5% Branches 49/56
92.85% Functions 13/14
93.02% Lines 40/43

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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338                                                                                                  193x 193x               77x 77x 77x 77x 77x 77x         77x   77x     77x   77x 12x 10x 10x 10x         2x         2x 2x                                 2x       2x 2x 2x   1x 1x   1x 1x       2x 2x 2x             2x         2x     77x                                                           222x   222x                                   40x                               7x                         4x                                                                                                           1x                   1x                                                                                                            
import { useEffect, useState } from 'react'
import type { Baby } from '@/features/babies/api/babies.schemas'
import { formatDateTimeDisplay } from '@/lib/date'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
 
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
  HEIGHT_CM_MAX,
  HEIGHT_CM_MIN,
  WEIGHT_KG_MAX,
  WEIGHT_KG_MIN,
  centimetersInputToMillimeters,
  gramsToKilogramsInput,
  kilogramsInputToGrams,
  millimetersToCentimetersInput,
  parseDecimalInput,
} from '@/shared/utils/measurements'
 
import { useDeleteAppointment, useUpdateAppointment } from '../api/appointments.hooks'
import type { Appointment } from '../api/appointments.schemas'
import { AppointmentStatusBadge } from './AppointmentStatusBadge'
 
interface AppointmentDetailDialogProps {
  baby?: Baby
  appointment: Appointment | null
  onOpenChange: (open: boolean) => void
}
 
/**
 * Vazio é resposta válida — a maioria das visitas não mede nada. Só um valor presente e fora da
 * faixa é erro.
 */
function outOfRange(value: string, min: number, max: number): boolean {
  const parsed = parseDecimalInput(value)
  return parsed !== null && (!Number.isFinite(parsed) || parsed < min || parsed > max)
}
 
export function AppointmentDetailDialog({
  appointment,
  baby,
  onOpenChange,
}: AppointmentDetailDialogProps) {
  const { t, i18n } = useTranslation()
  const updateAppointment = useUpdateAppointment(appointment?.babyId ?? '')
  const deleteAppointment = useDeleteAppointment(appointment?.babyId ?? '')
  const [notes, setNotes] = useState('')
  const [weightKg, setWeightKg] = useState('')
  const [heightCm, setHeightCm] = useState('')
 
  // Uma visita ainda por acontecer não tem o que medir, e a API recusa o valor — mostrar os campos
  // aqui seria oferecer o que o servidor devolve como 400. O caminho é marcar como realizada
  // primeiro, que é um clique já existente logo abaixo.
  const visitHasHappened = appointment !== null && appointment.status === 'COMPLETED'
  const measurementError =
    visitHasHappened &&
    (outOfRange(weightKg, WEIGHT_KG_MIN, WEIGHT_KG_MAX) ||
      outOfRange(heightCm, HEIGHT_CM_MIN, HEIGHT_CM_MAX))
  const busy = updateAppointment.isPending || deleteAppointment.isPending
 
  useEffect(() => {
    if (appointment) {
      setNotes(appointment.notes ?? '')
      setWeightKg(gramsToKilogramsInput(appointment.weightGrams))
      setHeightCm(millimetersToCentimetersInput(appointment.heightMillimeters))
    }
  }, [appointment])
 
  async function handleSaveNotes() {
    Iif (!appointment || measurementError || busy) return
    // A mensagem de erro já é renderizada acima a partir de updateAppointment
    // .isError; o que faltava era o catch. Sem ele a rejeição sobe como
    // unhandled rejection e vira evento de crash no Sentry para uma falha que
    // a tela já está tratando.
    try {
      await updateAppointment.mutateAsync({
        appointmentId: appointment.id,
        input: {
          notes: notes || null,
          // Só para visita que aconteceu, e `null` quando o campo foi esvaziado: apagar uma medida
          // é uma correção legítima, e omitir o campo significaria "não mexi", que é outra coisa.
          ...(visitHasHappened
            ? {
                weightGrams: kilogramsInputToGrams(weightKg),
                heightMillimeters: centimetersInputToMillimeters(heightCm),
              }
            : {}),
        },
      })
    } catch {
      return
    }
    toast.success(t('appointments.detail.notesSavedToast'))
  }
 
  async function handleDelete() {
    Iif (!appointment || busy) return
    try {
      await deleteAppointment.mutateAsync(appointment.id)
    } catch {
      toast.error(t('appointments.detail.deleteError'))
      return
    }
    toast.success(t('appointments.detail.deleteSuccessToast'))
    onOpenChange(false)
  }
 
  async function handleSetStatus(status: 'COMPLETED' | 'CANCELLED') {
    Iif (!appointment || busy) return
    try {
      await updateAppointment.mutateAsync({
        appointmentId: appointment.id,
        input: { status, notes: notes || null },
      })
    } catch {
      return
    }
    toast.success(
      status === 'CANCELLED'
        ? t('appointments.detail.cancelSuccessToast')
        : t('appointments.detail.completeSuccessToast'),
    )
    onOpenChange(false)
  }
 
  return (
    <Dialog
      open={!!appointment}
      onOpenChange={(open) => {
        if (!busy) onOpenChange(open)
      }}
    >
      <DialogContent className="max-h-[90dvh] overflow-y-auto rounded-3xl sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>{t('appointments.detail.title')}</DialogTitle>
        </DialogHeader>
 
        {appointment && (
          <div className="space-y-4">
            <section className="rounded-2xl border border-violet-200 bg-violet-50/60 p-4 dark:border-violet-900 dark:bg-violet-950/30">
              <div className="flex flex-wrap items-start justify-between gap-2">
                <div>
                  <p className="font-bold text-ink">{appointment.doctorName}</p>
                  <p className="mt-1 text-sm text-ink-muted">
                    {[baby?.name, appointment.specialty].filter(Boolean).join(' · ')}
                  </p>
                </div>
                <AppointmentStatusBadge status={appointment.status} />
              </div>
              <dl className="mt-4 grid gap-3 text-sm sm:grid-cols-2">
                {[
                  ['date', formatDateTimeDisplay(appointment.scheduledAt, i18n.language)],
                  ['location', appointment.location],
                  ['reason', appointment.reason],
                ]
                  .filter(([, value]) => value)
                  .map(([key, value]) => (
                    <div key={key} className="min-w-0">
                      <dt className="text-xs font-semibold text-ink-muted">
                        {t(`appointments.page.${key}`)}
                      </dt>
                      <dd className="mt-1 break-words text-ink">{value}</dd>
                    </div>
                  ))}
              </dl>
            </section>
 
            <div>
              <Label htmlFor="detail-notes">{t('appointments.detail.notesLabel')}</Label>
              <Textarea
                id="detail-notes"
                rows={4}
                className="mt-2"
                disabled={busy}
                value={notes}
                onChange={(event) => setNotes(event.target.value)}
              />
            </div>
 
            {visitHasHappened && (
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="detail-weight">{t('appointments.form.weightLabel')}</Label>
                  <Input
                    id="detail-weight"
                    inputMode="decimal"
                    placeholder={t('appointments.form.weightPlaceholder')}
                    aria-invalid={outOfRange(weightKg, WEIGHT_KG_MIN, WEIGHT_KG_MAX)}
                    className="mt-2 font-sans tabular-nums"
                    disabled={busy}
                    value={weightKg}
                    onChange={(event) => setWeightKg(event.target.value)}
                  />
                </div>
                <div>
                  <Label htmlFor="detail-height">{t('appointments.form.heightLabel')}</Label>
                  <Input
                    id="detail-height"
                    inputMode="decimal"
                    placeholder={t('appointments.form.heightPlaceholder')}
                    aria-invalid={outOfRange(heightCm, HEIGHT_CM_MIN, HEIGHT_CM_MAX)}
                    className="mt-2 font-sans tabular-nums"
                    disabled={busy}
                    value={heightCm}
                    onChange={(event) => setHeightCm(event.target.value)}
                  />
                </div>
              </div>
            )}
 
            {measurementError && (
              <p role="alert" className="text-destructive text-sm">
                {outOfRange(weightKg, WEIGHT_KG_MIN, WEIGHT_KG_MAX)
                  ? t('appointments.form.weightInvalid')
                  : t('appointments.form.heightInvalid')}
              </p>
            )}
 
            {updateAppointment.isError && (
              <p role="alert" className="text-destructive text-sm">
                {t('appointments.detail.genericError')}
              </p>
            )}
 
            <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={handleSaveNotes}
                disabled={busy || measurementError}
              >
                {t('appointments.detail.saveNotes')}
              </Button>
 
              {appointment.status === 'SCHEDULED' && (
                <div className="flex flex-wrap gap-2">
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button type="button" variant="outline" disabled={busy}>
                        {t('appointments.detail.cancelAppointment')}
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>
                          {t('appointments.detail.cancelConfirmTitle')}
                        </AlertDialogTitle>
                        <AlertDialogDescription>
                          {t('appointments.detail.cancelConfirmDescription', {
                            doctorName: appointment.doctorName,
                          })}
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>
                          {t('appointments.detail.cancelConfirmDismiss')}
                        </AlertDialogCancel>
                        <AlertDialogAction
                          onClick={() => handleSetStatus('CANCELLED')}
                          disabled={busy}
                        >
                          {t('appointments.detail.cancelConfirmAction')}
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                  <Button
                    type="button"
                    onClick={() => handleSetStatus('COMPLETED')}
                    disabled={busy}
                  >
                    {t('appointments.detail.markCompleted')}
                  </Button>
                </div>
              )}
            </div>
 
            {/* Excluir fica fora do bloco de `SCHEDULED` de propósito: cancelar
                só faz sentido para o que está marcado, mas errar de digitação
                acontece em qualquer estado — e desde que dá para registrar
                consulta passada, "cancelar" um fato já ocorrido não quer dizer
                nada. É a única saída para um registro que não deveria existir. */}
            <div className="flex justify-start border-t border-border pt-4">
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button
                    type="button"
                    variant="ghost"
                    className="text-destructive"
                    disabled={busy}
                  >
                    {t('appointments.detail.deleteAppointment')}
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>
                      {t('appointments.detail.deleteConfirmTitle')}
                    </AlertDialogTitle>
                    <AlertDialogDescription>
                      {t('appointments.detail.deleteConfirmDescription', {
                        doctorName: appointment.doctorName,
                      })}
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>
                      {t('appointments.detail.deleteConfirmDismiss')}
                    </AlertDialogCancel>
                    <AlertDialogAction variant="destructive" onClick={handleDelete} disabled={busy}>
                      {t('appointments.detail.deleteConfirmAction')}
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}