All files / src/features/babies/routes DashboardRoute.tsx

86.15% Statements 56/65
72.91% Branches 35/48
80% Functions 20/25
87.5% Lines 49/56

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                                                          8x 8x           12x 12x 36x 40x 12x   12x 12x 12x 12x   12x                     12x 4x         12x               8x                             8x 1x             7x                 12x 4x   12x 28x   12x 12x 12x 12x   12x       12x 17x       17x 12x                     12x 28x 76x   28x 40x 48x     12x 12x 12x 12x 12x 19x     12x         12x                         12x                         3x                                                                                   12x                                                                                                      
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
 
import { useAllBabiesAppointments } from '@/features/appointments/api/appointments.hooks'
import { growthSeries } from '@/features/growth/api/growth.selectors'
import { AppointmentsOverviewCard } from '@/features/appointments/components/AppointmentsOverviewCard'
import { useAllBabiesMilestones } from '@/features/milestones/api/milestones.hooks'
import { useAllBabiesMedications } from '@/features/medications/api/medications.hooks'
import { MedicationsOverviewCard } from '@/features/medications/components/MedicationsOverviewCard'
import { MilestonesOverviewCard } from '@/features/milestones/components/MilestonesOverviewCard'
import { useAllBabiesVaccineCalendars } from '@/features/vaccines/api/vaccines.hooks'
import { VaccinesOverviewCard } from '@/features/vaccines/components/VaccinesOverviewCard'
import { formatDateDisplay, splitScheduledAt } from '@/lib/date'
import { GrowthIcon } from '@/shared/icons/growth-icon'
import { formatCentimeters, formatKilograms } from '@/shared/utils/measurements'
import { useAuthIdentityStore } from '@/shared/stores/authIdentity.store'
import { useSelectedBabyStore } from '@/shared/stores/selectedBaby.store'
 
import { useBabies } from '../api/babies.hooks'
import type { Baby } from '../api/babies.schemas'
import { EditBabyDialog } from '../components/EditBabyDialog'
import { BabyHeroCard } from '../components/BabyHeroCard'
import { WelcomeDashboard } from '../components/WelcomeDashboard'
 
function getGreetingKey():
  | 'babies.dashboard.greetingMorning'
  | 'babies.dashboard.greetingAfternoon'
  | 'babies.dashboard.greetingEvening' {
  const hour = new Date().getHours()
  Eif (hour < 12) return 'babies.dashboard.greetingMorning'
  if (hour < 18) return 'babies.dashboard.greetingAfternoon'
  return 'babies.dashboard.greetingEvening'
}
 
export function DashboardRoute() {
  const { t, i18n } = useTranslation()
  const babies = useBabies()
  const identity = useAuthIdentityStore((state) => state.identity)
  const selectedBabyId = useSelectedBabyStore((state) => state.selectedBabyId)
  const [editTarget, setEditTarget] = useState<Baby | null>(null)
 
  const vaccines = useAllBabiesVaccineCalendars()
  const appointments = useAllBabiesAppointments()
  const milestones = useAllBabiesMilestones()
  const medications = useAllBabiesMedications()
 
  const babyList = babies.data ?? []
 
  // `data ?? []` is empty for three different reasons, and only one of them is
  // "this family has no children". While the request is in flight or after it
  // failed, falling through to WelcomeDashboard shows a parent of six the
  // onboarding screen — "Bem-vindo(a) ao Cygnus! Acompanhe vacinas…" — and
  // then swaps it for their real dashboard. Measured by delaying GET /babies by
  // 5s: the welcome copy rendered for the whole delay.
  //
  // The other widgets on this page already branch on their own pending/error;
  // this query is different because it decides which screen exists at all.
  if (babies.isPending) {
    return (
      <div className="animate-pulse space-y-6">
        <div className="h-10 w-64 rounded-xl bg-card shadow-sm" />
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[0, 1, 2].map((index) => (
            <div key={index} className="h-28 rounded-2xl bg-card shadow-sm" />
          ))}
        </div>
        <div className="h-24 rounded-2xl bg-card shadow-sm" />
      </div>
    )
  }
 
  Iif (babies.isError) {
    return (
      <div role="alert" className="rounded-2xl bg-card p-8 text-center">
        <p>{t('babies.dashboard.loadError')}</p>
        <button
          type="button"
          onClick={() => void babies.refetch()}
          className="mt-4 min-h-11 rounded-xl bg-primary px-5 text-primary-foreground"
        >
          {t('nav.shell.retry')}
        </button>
      </div>
    )
  }
 
  if (babyList.length === 0) {
    return (
      <div>
        <WelcomeDashboard greetingKey={getGreetingKey()} />
      </div>
    )
  }
 
  const parentName = identity?.name ?? identity?.email ?? ''
 
  // Narrowed to the child chosen in the menu, or the whole family when none is.
  // Applied once, here, so every number and every card below answers for the
  // same set — a page where the hero card is one child and the counters are six
  // is worse than either view on its own.
  //
  // The empty-state check above stays on the full list on purpose: a household
  // with children never sees the welcome screen because of a filter.
  const visibleBabies = selectedBabyId
    ? babyList.filter((baby) => baby.id === selectedBabyId)
    : babyList
  const forSelection = <T extends { babyId: string }>(items: T[]): T[] =>
    selectedBabyId ? items.filter((item) => item.babyId === selectedBabyId) : items
 
  const visibleVaccineItems = forSelection(vaccines.items)
  const visibleAppointments = forSelection(appointments.items)
  const visibleMilestones = forSelection(milestones.items)
  const visibleMedications = forSelection(medications.items)
 
  const delayedItems = visibleVaccineItems.filter((item) => item.status === 'DELAYED')
  // O estado vem de `perBaby`, não de `babyList`: cada criança tem sua própria
  // requisição de calendário, e uma pode falhar enquanto as outras respondem.
  // Derivar do agregado marcaria as seis como desconhecidas por causa de uma.
  const familyItems = visibleBabies.map((baby) => {
    const entry = vaccines.perBaby.find((candidate) => candidate.baby.id === baby.id)
    // As consultas já estão carregadas nesta tela para os cartões abaixo, então a última medida
    // sai daqui sem uma requisição a mais — que é o que torna barato mostrar peso e altura no
    // perfil sem duplicar o dado que mora na consulta.
    const appointmentEntry = appointments.perBaby.find((candidate) => candidate.baby.id === baby.id)
    return {
      baby,
      delayedVaccineCount: delayedItems.filter((item) => item.babyId === baby.id).length,
      // Sem entrada, o padrão é "não sei" — nunca "em dia".
      vaccineStatusKnown: entry ? !entry.isPending && !entry.isError : false,
      latestMeasuredVisit:
        growthSeries(appointmentEntry?.items ?? [], baby.birthDate, baby.measurements).at(-1) ??
        null,
    }
  })
 
  const stateFor = (entries: { baby: Baby; isPending: boolean; isError: boolean }[]) => {
    const selected = entries.filter((entry) =>
      visibleBabies.some((baby) => baby.id === entry.baby.id),
    )
    return {
      isPending: selected.some((entry) => entry.isPending),
      isError: selected.some((entry) => entry.isError),
    }
  }
  const vaccineState = stateFor(vaccines.perBaby)
  const appointmentState = stateFor(appointments.perBaby)
  const milestoneState = stateFor(milestones.perBaby)
  const medicationState = stateFor(medications.perBaby)
  const ready = [vaccineState, appointmentState, milestoneState, medicationState].every(
    (state) => !state.isPending && !state.isError,
  )
  const firstRecords =
    ready &&
    !visibleAppointments.length &&
    !visibleMilestones.length &&
    !visibleMedications.length &&
    !visibleVaccineItems.some((item) => item.status === 'APPLIED')
  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-3xl font-medium text-ink">
          {t('babies.dashboard.greetingLine', { greeting: t(getGreetingKey()), name: parentName })}
        </h1>
        <p className="text-sm text-ink-muted">
          {t('babies.dashboard.childCount', { count: visibleBabies.length })}
        </p>
      </div>
 
      <div className="mb-6 grid gap-3 lg:grid-cols-2">
        {familyItems.map((item) => (
          <BabyHeroCard key={item.baby.id} {...item} compact onEdit={setEditTarget} />
        ))}
      </div>
      {firstRecords && (
        <section className="mb-6 rounded-2xl border border-primary/20 bg-primary/5 p-5 sm:p-6">
          <h2 className="font-display text-xl font-medium text-ink">{t('babies.home.start')}</h2>
          <p className="mt-1 text-sm text-ink-muted">{t('babies.home.startBody')}</p>
          <div className="mt-4 flex flex-wrap gap-2">
            {[
              ['/vaccines', 'recordVaccines'],
              ['/appointments', 'schedule'],
              ['/milestones', 'memory'],
            ].map(([to, key]) => (
              <Link
                key={to}
                to={to!}
                className="inline-flex min-h-11 items-center rounded-xl border border-border bg-card px-4 py-2 text-sm font-semibold text-primary"
              >
                {t(`babies.home.${key}`)}
              </Link>
            ))}
          </div>
        </section>
      )}
      <div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1.45fr)_minmax(0,1fr)]">
        <div className="min-w-0 space-y-5">
          <h2 className="font-display text-xl font-medium text-ink">{t('babies.home.care')}</h2>
          <AppointmentsOverviewCard
            babies={visibleBabies}
            items={visibleAppointments}
            {...appointmentState}
          />
          <VaccinesOverviewCard
            babies={visibleBabies}
            items={visibleVaccineItems}
            {...vaccineState}
          />
          <MedicationsOverviewCard
            babies={visibleBabies}
            items={visibleMedications}
            {...medicationState}
          />
        </div>
        <div className="min-w-0 space-y-5">
          <h2 className="font-display text-xl font-medium text-ink">{t('babies.home.growing')}</h2>
          <section className="card-lift rounded-2xl border border-border bg-card p-5">
            {/* The area's colour lives in the icon, as on every other card. */}
            <div className="mb-4 flex items-center gap-2.5">
              <span className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300">
                <GrowthIcon className="h-[18px] w-[18px]" />
              </span>
              <h3 className="font-display text-lg font-medium text-ink">{t('nav.growth')}</h3>
            </div>
            <div className="space-y-4">
              {familyItems.map(({ baby, latestMeasuredVisit: measurement }) => (
                <div key={baby.id}>
                  <p className="text-sm font-semibold text-ink">{baby.name}</p>
                  {appointmentState.isError || appointmentState.isPending ? (
                    <p className="text-sm text-ink-muted">{t('babies.home.measureUnavailable')}</p>
                  ) : measurement ? (
                    <>
                      <p className="mt-1 font-sans tabular-nums text-sm text-ink">
                        {[
                          measurement.weightGrams !== null
                            ? formatKilograms(measurement.weightGrams, i18n.language)
                            : null,
                          measurement.heightMillimeters !== null
                            ? formatCentimeters(measurement.heightMillimeters, i18n.language)
                            : null,
                        ]
                          .filter(Boolean)
                          .join(' / ')}
                      </p>
                      <p className="mt-1 text-xs text-ink-muted">
                        {t('babies.hero.measuredOn')}{' '}
                        {formatDateDisplay(
                          splitScheduledAt(measurement.scheduledAt).date,
                          i18n.language,
                        )}
                      </p>
                    </>
                  ) : (
                    <p className="text-sm text-ink-muted">{t('babies.home.noMeasurement')}</p>
                  )}
                </div>
              ))}
            </div>
            <Link
              to="/growth"
              className="mt-4 inline-flex min-h-11 items-center text-sm font-semibold text-primary"
            >
              {t('babies.home.growthLink')}
            </Link>
          </section>
          <MilestonesOverviewCard
            babies={visibleBabies}
            items={visibleMilestones}
            {...milestoneState}
          />
        </div>
      </div>
 
      <EditBabyDialog baby={editTarget} onOpenChange={(open) => !open && setEditTarget(null)} />
    </div>
  )
}