Skip to contentVibraUI
Part of the Clinic dashboardinstalls at /clinic/appointments

Appointment book

Every visit in the clinic's book: the patient with a face, the doctor, the department, when and for how long, the procedure and where it stands — from today, the past or all of it, with a facet on department, doctor and status, four figures, and a check-in, a reschedule or a cancellation on every visit still booked.

Open the live page

Installs at /clinic/appointments. The page is a server component: it reads every visit through db.appointments and hands the rows, with REFERENCE_DATE as now, to the island — the book is small enough to search, filter, sort and page in the browser. The windows split it at today's UTC midnight: from today, soonest first; the past, latest first; or all of it. The table's own facets narrow it by department, doctor and status, and the four figures — today's visits, what is booked from now on in hours of clinic time, the month's visits and new patients, and the month's cancellations — are counted off the same rows, so they move with them. A visit still booked carries a menu with the Clinic dashboard's own verbs from actions-clinic, the ones the overview calls too: check in on the visit's own day, cancel on any, behind a confirmation, and Reschedule while the visit is still ahead of now; every other visit carries none. Reschedule opens a dialog on the visit's own day and time: a DatePicker that offers the weekdays after today up to the last day the book is open, 180 days on, where pressing the chosen day keeps it, and a TimePicker whose slots are timeSlots({ start: "08:00", end: "18:00", step: 15 }) less those that would run past 18:00 for the visit's length, with a line under them saying so — every one of those numbers read from hours-clinic, which rescheduleAppointment refuses by, so the dialog never offers a slot the server would refuse; Move visit calls rescheduleAppointment, and a refusal — the doctor's time with another patient, a slot that has passed — lands in an alert inside the dialog, which stays open to pick again. An accepted action rewrites its row, and so does a refused one, to the status and the time the store reports, so a moved visit takes its new place in the order; a success is said in the status line — "Ana Baker's visit with Dr. Amara Osei is now Mon, Sep 7 at 9:00 AM." — and a desk refusal in its own alert above the rows. After a move the focus goes to the visit's menu in its new place, or to the search that finds it. The words come from vocabulary-clinic. Composes AppShell, PageHeader, StatCardGroup, StatCard, QuickFilters, DataTable, DataTableColumnHeader, DataTableRowActions, UserCell, StatusBadge, Callout, ConfirmDialog, Dialog, DatePicker, TimePicker, AsyncButton, Button and RescheduleDialog (block-local).

Preview

Install

npx shadcn@latest add @vibra/clinic-appointments

Needs the @vibra registry in your components.json — set it up once.

Source

app/clinic/appointments/page.tsx
import { NAV, ROUTES } from "@/lib/dashboards/clinic/nav"
import { REFERENCE_DATE } from "@/lib/sample-data"
import { AppShell } from "@/components/ui/app-shell"
import { PageHeader } from "@/components/ui/page-header"

import { signOut } from "./actions"
import { AppointmentsBook } from "./components/appointments-book"
import { currentUser, lastUpdated, shellNotifications, visitRows } from "./data"

/**
 * The clinic's book. The page is a server component: it reads every visit
 * through `db.appointments` and hands the rows, and "now", to the island that
 * searches, filters and acts on them.
 */
export default function AppointmentsPage() {
  return (
    <AppShell
      nav={NAV}
      activeHref={ROUTES.appointments}
      user={currentUser()}
      notifications={shellNotifications()}
      now={REFERENCE_DATE}
      onSignOut={signOut}
    >
      <PageHeader
        titleId="clinic-appointments-title"
        title="Appointments"
        description="Every visit in the book: who, with whom, when, and where it stands."
        meta={lastUpdated()}
      />

      <AppointmentsBook titleId="clinic-appointments-title" rows={visitRows()} now={REFERENCE_DATE} />
    </AppShell>
  )
}
app/clinic/appointments/data.ts
/**
 * What this page reads: every visit in `db.appointments`, as the rows the
 * book prints. The book is small enough to hand to the table whole, so the
 * table searches, filters, sorts and pages it in the browser, and the figures
 * above are counted off the same rows there — a check-in or a cancellation
 * moves them in the one render. "Now" is `REFERENCE_DATE`, handed to the
 * island rather than read off the browser's clock.
 *
 * The client islands import only the types below; `db` never crosses into
 * the browser.
 */
import { formatDate, getInitials } from "@/lib/format"
import { REFERENCE_DATE, db, type Appointment, type Member } from "@/lib/sample-data"

/** One visit as the book prints it. */
export type VisitRow = {
  id: string
  patient: string
  avatarUrl?: string
  email: string
  doctor: string
  department: Appointment["department"]
  at: Date
  durationMin: number
  status: Appointment["status"]
  procedure?: string
  isNewPatient: boolean
}

function toRow(row: Appointment): VisitRow {
  return {
    id: row.id,
    patient: row.patient,
    avatarUrl: row.avatarUrl,
    email: row.email,
    doctor: row.doctor,
    department: row.department,
    at: row.at,
    durationMin: row.durationMin,
    status: row.status,
    procedure: row.procedure,
    isNewPatient: row.isNewPatient,
  }
}

/** Every visit in the book, oldest first. */
export function visitRows(): VisitRow[] {
  return db.appointments
    .all()
    .sort((a, b) => a.at.getTime() - b.at.getTime())
    .map(toRow)
}

/** The freshness line under the title, measured against REFERENCE_DATE. */
export function lastUpdated(): string {
  return `Synced ${formatDate(REFERENCE_DATE, "medium", { timeZone: "UTC" })}`
}

/** The bell's contents: the newest notifications, unread first in the panel. */
export function shellNotifications() {
  return db.notifications
    .all()
    .sort((a, b) => b.at.getTime() - a.at.getTime())
    .slice(0, 6)
    .map(({ id, title, description, at, read, href }) => ({ id, title, description, at, read, href }))
}

function ownerRow(): Member {
  return db.members.all().find((member) => member.role === "owner") ?? db.members.all()[0]
}

/** The person looking at the page: whoever owns this workspace. */
export function currentUser() {
  const owner = ownerRow()
  return { name: owner.name, email: owner.email, initials: getInitials(owner.name), avatarUrl: owner.avatarUrl }
}
app/clinic/appointments/actions.ts
"use server"

import { mockAuthAdapter } from "@/lib/auth-adapter"
import { type Result } from "@/lib/sample-data"

/**
 * What this page changes on its own: the session. The check-in and the
 * cancellation on every row are the Clinic dashboard's own actions, shared
 * with the overview, and live in `@/lib/dashboards/clinic/actions`.
 */

export async function signOut(): Promise<Result<{ signedOut: true }>> {
  await mockAuthAdapter.signOut()
  return { ok: true, data: { signedOut: true } }
}
app/clinic/appointments/components/appointments-book.tsx
"use client"

import * as React from "react"
import type { SortingState } from "@tanstack/react-table"

import {
  cancelAppointment,
  checkInAppointment,
  type VisitAnswer,
  type VisitChange,
} from "@/lib/dashboards/clinic/actions"
import {
  DEPARTMENTS,
  VISIT_DAY,
  VISIT_STATUS_LABELS,
  VISIT_STATUS_ORDER,
  VISIT_TIME,
} from "@/lib/dashboards/clinic/vocabulary"
import { Callout } from "@/components/ui/callout"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { DataTable } from "@/components/ui/data-table"
import { QuickFilters } from "@/components/ui/quick-filters"

import { type VisitRow } from "../data"

import { RescheduleDialog } from "./reschedule-dialog"
import { visitColumns } from "./visit-columns"
import { VisitFigures } from "./visit-figures"
import { WINDOWS, inWindow, type VisitWindow } from "./visit-vocabulary"

// A window brings its own order: the book ahead soonest first, the past latest first.
const WINDOW_SORT: Record<VisitWindow, SortingState> = {
  ahead: [{ id: "at", desc: false }],
  past: [{ id: "at", desc: true }],
  all: [{ id: "at", desc: false }],
}

export type AppointmentsBookProps = {
  /** The page's h1 id, which names the table. */
  titleId: string
  rows: VisitRow[]
  /** REFERENCE_DATE, from the page: the island never reads the browser's clock. */
  now: Date
}

/**
 * The book. The rows arrive whole from the server page and this island owns
 * them from then on: the window, the search, the three facets, the sort and
 * the pager are the table's, and a check-in, a cancellation or a reschedule
 * the server accepts rewrites the row it moved — its pill, its time and so
 * its place in the order, and the figures above, follow in the same render.
 * A refusal rewrites it too, to the status and the time the store says it
 * has, so the book never keeps offering a visit the desk was just told has
 * moved on. A success is said in the status line and a refusal in its own
 * alert — the reschedule's inside its dialog; the two never share a slot.
 */
export function AppointmentsBook({ titleId, rows: initial, now }: AppointmentsBookProps) {
  const [rows, setRows] = React.useState(initial)
  const [range, setRange] = React.useState<VisitWindow>("ahead")
  const [sorting, setSorting] = React.useState<SortingState>(WINDOW_SORT.ahead)
  const [notice, setNotice] = React.useState("")
  const [refusal, setRefusal] = React.useState("")
  const [cancelling, setCancelling] = React.useState<VisitRow | null>(null)
  const [moving, setMoving] = React.useState<VisitRow | null>(null)
  const bookRef = React.useRef<HTMLDivElement>(null)
  // The visit the last accepted move put somewhere else, until the closing dialog has placed the focus.
  const landing = React.useRef<VisitChange | null>(null)

  /** Writes a visit back as the store holds it: its status and its time. */
  const settle = React.useCallback((visit: VisitChange) => {
    setRows((current) => current.map((entry) => (entry.id === visit.id ? { ...entry, status: visit.status, at: visit.at } : entry)))
  }, [])

  const run = React.useCallback(
    async (verb: (id: string) => Promise<VisitAnswer>, row: VisitRow, say: (visit: VisitChange) => string) => {
      setNotice("")
      setRefusal("")
      const result = await verb(row.id)
      const stored = result.ok ? result.data : result.current
      if (stored) settle(stored)
      if (!result.ok) return setRefusal(result.error.message)
      setNotice(say(result.data))
    },
    [settle]
  )

  function moved(visit: VisitChange) {
    landing.current = visit
    setMoving(null)
    settle(visit)
    setNotice(`${visit.patient}'s visit with ${visit.doctor} is now ${VISIT_DAY.format(visit.at)} at ${VISIT_TIME.format(visit.at)}.`)
  }

  /**
   * Where the focus goes as the dialog closes. After a move the row has a new
   * place in the book, maybe on another page: its menu button there, or the
   * search that finds it — never the top of the document. Otherwise the
   * dialog's default, the button that opened it.
   */
  function returnFocus(): HTMLElement | null {
    const visit = landing.current
    landing.current = null
    if (!visit) return null
    const book = bookRef.current
    const label = `Open menu for ${visit.patient} on ${VISIT_DAY.format(visit.at)}`
    const menu = [...(book?.querySelectorAll<HTMLElement>('[data-slot="data-table-row-actions"]') ?? [])].find((button) => button.getAttribute("aria-label") === label)
    return menu ?? book?.querySelector<HTMLElement>('[data-slot="data-table-toolbar"] input') ?? null
  }

  // Only setters and the stable `run` are closed over, so the columns are
  // built once rather than on every keystroke in the search box.
  const columns = React.useMemo(
    () =>
      visitColumns(
        {
          onCheckIn: (row) => run(checkInAppointment, row, (visit) => `${visit.patient} is checked in.`),
          onReschedule: (row) => {
            setNotice("")
            setRefusal("")
            setMoving(row)
          },
          onCancel: setCancelling,
        },
        now
      ),
    [run, now]
  )

  const shown = React.useMemo(() => rows.filter((row) => inWindow(row, range, now)), [rows, range, now])
  const doctors = React.useMemo(() => [...new Set(rows.map((row) => row.doctor))].sort(), [rows])

  return (
    <div ref={bookRef} data-slot="appointments-book" className="flex flex-col gap-4">
      <VisitFigures rows={rows} now={now} />

      <div className="flex flex-col gap-3">
        <QuickFilters
          aria-label="Appointments by window"
          options={WINDOWS.map((entry) => ({ ...entry, count: rows.filter((row) => inWindow(row, entry.value, now)).length }))}
          value={range}
          onValueChange={(value) => {
            setRange(value as VisitWindow)
            setSorting(WINDOW_SORT[value as VisitWindow])
          }}
        />

        {refusal ? (
          <Callout variant="danger" role="alert">
            {refusal}
          </Callout>
        ) : null}
        {/* A line held open even when empty, so a message arriving never pushes the rows down. */}
        <p role="status" aria-live="polite" className="-my-1 min-h-4 text-xs text-muted-foreground">
          {notice}
        </p>

        <DataTable
          aria-labelledby={titleId}
          columns={columns}
          data={shown}
          getRowId={(row) => row.id}
          searchKey="patient"
          searchPlaceholder="Search patients"
          enableRowSelection={false}
          state={{ sorting }}
          onSortingChange={setSorting}
          facets={[
            { columnId: "department", title: "Department", options: DEPARTMENTS.map((value) => ({ value, label: value })) },
            { columnId: "doctor", title: "Doctor", options: doctors.map((value) => ({ value, label: value })) },
            { columnId: "status", title: "Status", options: VISIT_STATUS_ORDER.map((value) => ({ value, label: VISIT_STATUS_LABELS[value] })) },
          ]}
          pageSize={10}
          pageSizeOptions={[10, 25, 50]}
          emptyMessage="No visit matches these filters."
        />
      </div>

      <RescheduleDialog
        visit={moving}
        now={now}
        onClose={() => setMoving(null)}
        onMoved={moved}
        onRefused={(current) => (current ? settle(current) : undefined)}
        returnFocus={returnFocus}
      />

      <ConfirmDialog
        variant="destructive"
        open={cancelling !== null}
        onOpenChange={(open) => {
          if (!open) setCancelling(null)
        }}
        title={cancelling ? `Cancel ${cancelling.patient}'s visit?` : "Cancel this visit?"}
        description={
          cancelling
            ? `${cancelling.doctor}, ${VISIT_DAY.format(cancelling.at)} at ${VISIT_TIME.format(cancelling.at)}. The slot goes back into the book; a cancelled visit cannot be restored.`
            : undefined
        }
        confirmText="Cancel appointment"
        cancelText="Keep appointment"
        onConfirm={() =>
          cancelling
            ? run(cancelAppointment, cancelling, (visit) => `${visit.patient}'s visit with ${visit.doctor} is cancelled.`)
            : undefined
        }
      />
    </div>
  )
}
app/clinic/appointments/components/reschedule-dialog.tsx
"use client"

import * as React from "react"

import { rescheduleAppointment, type VisitChange } from "@/lib/dashboards/clinic/actions"
import { CLINIC_HOURS } from "@/lib/dashboards/clinic/hours"
import { VISIT_DAY, VISIT_TIME } from "@/lib/dashboards/clinic/vocabulary"
import { AsyncButton } from "@/components/ui/async-button"
import { Button } from "@/components/ui/button"
import { Callout } from "@/components/ui/callout"
import { DatePicker } from "@/components/ui/date-picker"
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { TimePicker, formatTime, timeSlots, timeToMinutes } from "@/components/ui/time-picker"

import { type VisitRow } from "../data"

import { utcDay } from "./visit-vocabulary"

const DAY_MS = 86_400_000

/** Every start a visit of `length` minutes can take and still be over by closing: the clinic's slots, from its hours. */
const startsFor = (length: number) =>
  timeSlots({ start: CLINIC_HOURS.opens, end: CLINIC_HOURS.closes, step: CLINIC_HOURS.step }).filter(
    (slot) => timeToMinutes(slot) + length <= timeToMinutes(CLINIC_HOURS.closes)
  )

/** A visit's time of day, "HH:mm" in UTC, as the time field holds it; and its day, "YYYY-MM-DD", as the server reads one. */
const timeOf = (at: Date) => at.toISOString().slice(11, 16)
const dayOf = (date: Date) => date.toISOString().slice(0, 10)
const clock = (time: string) => formatTime(time, { hourCycle: "h12" })

/** The chosen day, whole, for the field's name: "Monday, September 7, 2026". */
const SPOKEN_DAY = new Intl.DateTimeFormat("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric", timeZone: "UTC" })

export type RescheduleDialogProps = {
  /** The visit being moved; the dialog is open while there is one. */
  visit: VisitRow | null
  /** REFERENCE_DATE: the calendar offers weekdays after its day. */
  now: Date
  onClose: () => void
  onMoved: (visit: VisitChange) => void
  /** A refusal, with the visit as the store holds it — absent when it is gone from the book. */
  onRefused: (current: VisitChange | undefined) => void
  /** Where the focus goes as the dialog closes; null is the dialog's own default, the button that opened it. */
  returnFocus?: () => HTMLElement | null
}

/**
 * Moves one booked visit: a DatePicker of the weekdays after today, up to the
 * last day the book is open, and a TimePicker whose slots are the clinic's
 * starts that leave room for the visit's length before closing — all from
 * CLINIC_HOURS, which the action refuses by. Both open on the visit as it
 * stands. The server decides — a refusal lands in an alert inside the dialog,
 * where the reader is looking, and the dialog stays open to pick again; a
 * move closes it.
 */
export function RescheduleDialog({ visit, now, onClose, onMoved, onRefused, returnFocus }: RescheduleDialogProps) {
  const [shown, setShown] = React.useState(visit)
  const [openedFor, setOpenedFor] = React.useState(visit)
  const [day, setDay] = React.useState<Date | undefined>(visit ? new Date(utcDay(visit.at)) : undefined)
  const [time, setTime] = React.useState<string | undefined>(visit ? timeOf(visit.at) : undefined)
  const [refusal, setRefusal] = React.useState("")
  const ids = React.useId()

  // Every opening starts from the visit's own day and time with nothing
  // refused. `shown` outlives the close, so the content holds still while the
  // dialog fades.
  if (visit !== openedFor) {
    setOpenedFor(visit)
    if (visit) {
      setShown(visit)
      setDay(new Date(utcDay(visit.at)))
      setTime(timeOf(visit.at))
      setRefusal("")
    }
  }

  async function move() {
    if (!shown) return
    setRefusal("")
    // A field left empty goes as it is: the server names what is missing.
    const result = await rescheduleAppointment(shown.id, day ? dayOf(day) : "", time ?? "")
    if (result.ok) return onMoved(result.data)
    setRefusal(result.error.message)
    onRefused(result.current)
  }

  const length = shown?.durationMin ?? 0
  const starts = startsFor(length)
  const last = starts.at(-1) ?? CLINIC_HOURS.opens
  const today = new Date(utcDay(now))
  const lastDay = new Date(today.getTime() + CLINIC_HOURS.horizonDays * DAY_MS)

  return (
    <Dialog
      open={visit !== null}
      onOpenChange={(open) => {
        if (!open) onClose()
      }}
    >
      <DialogContent className="sm:max-w-md" finalFocus={returnFocus ?? true}>
        <DialogHeader>
          <DialogTitle>{shown ? `Reschedule ${shown.patient}'s visit` : "Reschedule the visit"}</DialogTitle>
          <DialogDescription>
            {shown ? `${shown.doctor}, ${length} min — now ${VISIT_DAY.format(shown.at)} at ${VISIT_TIME.format(shown.at)}.` : null}
          </DialogDescription>
        </DialogHeader>

        {refusal ? (
          <Callout variant="danger" role="alert">
            {refusal}
          </Callout>
        ) : null}

        <div className="grid gap-3 sm:grid-cols-2">
          <div className="flex min-w-0 flex-col gap-2">
            <span id={`${ids}-day`} className="text-sm leading-none font-medium">
              Day
            </span>
            {/* The trigger's name is the label and the day it holds, whole. */}
            <span id={`${ids}-day-value`} hidden>
              {day ? SPOKEN_DAY.format(day) : "No day chosen"}
            </span>
            <DatePicker
              aria-labelledby={`${ids}-day ${ids}-day-value`}
              aria-describedby={`${ids}-hours`}
              value={day}
              // A move needs a day: pressing the one already chosen keeps it
              // rather than clearing it, as the calendar would.
              onValueChange={(next) => {
                if (next) setDay(next)
              }}
              min={new Date(today.getTime() + DAY_MS)}
              max={lastDay}
              format="EEE, MMM d, yyyy"
              calendar={{ today, disabled: { dayOfWeek: [0, 6] } }}
            />
          </div>
          <div className="flex min-w-0 flex-col gap-2">
            <span id={`${ids}-time`} className="text-sm leading-none font-medium">
              Time
            </span>
            <TimePicker
              aria-labelledby={`${ids}-time`}
              aria-describedby={`${ids}-hours`}
              value={time}
              onValueChange={setTime}
              step={CLINIC_HOURS.step}
              min={CLINIC_HOURS.opens}
              max={last}
              slots={starts}
            />
          </div>
        </div>
        <p id={`${ids}-hours`} className="text-xs text-muted-foreground">
          {`Weekdays until ${VISIT_DAY.format(lastDay)}, ${clock(CLINIC_HOURS.opens)} to ${clock(CLINIC_HOURS.closes)} UTC, every ${CLINIC_HOURS.step} minutes: a ${length}-minute visit starts by ${clock(last)}.`}
        </p>

        <DialogFooter>
          <DialogClose
            render={
              <Button variant="outline" size="sm" type="button">
                Keep the time
              </Button>
            }
          />
          <AsyncButton size="sm" onClick={move}>
            Move visit
          </AsyncButton>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
app/clinic/appointments/components/visit-columns.tsx
"use client"

import { CalendarClockIcon, LogInIcon, XCircleIcon } from "lucide-react"

import { VISIT_DAY, VISIT_STATUS_LABELS, VISIT_STATUS_MAP, VISIT_TIME } from "@/lib/dashboards/clinic/vocabulary"
import {
  DataTableColumnHeader,
  DataTableRowActions,
  type DataTableColumnDef,
} from "@/components/ui/data-table"
import { StatusBadge } from "@/components/ui/status-badge"
import { UserCell } from "@/components/ui/user-cell"

import { type VisitRow } from "../data"

import { utcDay } from "./visit-vocabulary"

export type VisitVerbs = {
  onCheckIn: (row: VisitRow) => void
  onReschedule: (row: VisitRow) => void
  onCancel: (row: VisitRow) => void
}

/**
 * The book's columns. Sorting and the three facets are the table's own, over
 * the rows the page handed it. A visit still booked carries a menu with the
 * desk's verbs the server would accept — cancel on any day, check in only on
 * the day itself, reschedule while it is still ahead of now — and any other
 * visit carries none.
 */
export function visitColumns(verbs: VisitVerbs, now: Date): DataTableColumnDef<VisitRow>[] {
  const today = utcDay(now)

  return [
    {
      accessorKey: "patient",
      header: ({ column }) => <DataTableColumnHeader column={column} title="Patient" />,
      cell: ({ row }) => (
        <UserCell
          size="sm"
          name={row.original.patient}
          src={row.original.avatarUrl}
          description={row.original.isNewPatient ? "New patient" : row.original.email}
        />
      ),
      meta: { label: "Patient" },
    },
    {
      accessorKey: "at",
      header: ({ column }) => <DataTableColumnHeader column={column} title="When" />,
      cell: ({ row }) => (
        <span className="flex flex-col whitespace-nowrap">
          <span className="tabular-nums">{VISIT_DAY.format(row.original.at)}</span>
          <span className="text-xs tabular-nums text-muted-foreground">{VISIT_TIME.format(row.original.at)}</span>
        </span>
      ),
      meta: { label: "When" },
    },
    {
      accessorKey: "durationMin",
      header: ({ column }) => <DataTableColumnHeader column={column} title="Length" />,
      cell: ({ row }) => <span className="whitespace-nowrap tabular-nums">{`${row.original.durationMin} min`}</span>,
      meta: { align: "right", label: "Length" },
    },
    {
      accessorKey: "doctor",
      header: ({ column }) => <DataTableColumnHeader column={column} title="Doctor" />,
      cell: ({ row }) => <span className="whitespace-nowrap">{row.original.doctor}</span>,
      meta: { label: "Doctor" },
    },
    {
      accessorKey: "department",
      header: ({ column }) => <DataTableColumnHeader column={column} title="Department" />,
      cell: ({ row }) => <span className="text-muted-foreground">{row.original.department}</span>,
      meta: { label: "Department" },
    },
    {
      id: "procedure",
      accessorFn: (row) => row.procedure ?? "Consultation",
      header: ({ column }) => <DataTableColumnHeader column={column} title="Procedure" />,
      cell: ({ row }) =>
        row.original.procedure ? (
          <span className="whitespace-nowrap">{row.original.procedure}</span>
        ) : (
          <span className="text-muted-foreground">Consultation</span>
        ),
      meta: { label: "Procedure" },
    },
    {
      accessorKey: "status",
      header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
      cell: ({ row }) => (
        <StatusBadge status={row.original.status} label={VISIT_STATUS_LABELS[row.original.status]} map={VISIT_STATUS_MAP} />
      ),
      meta: { label: "Status" },
    },
    {
      id: "actions",
      header: () => <span className="sr-only">Actions</span>,
      enableSorting: false,
      enableHiding: false,
      cell: ({ row }) =>
        row.original.status === "scheduled" ? (
          <DataTableRowActions
            label={`Open menu for ${row.original.patient} on ${VISIT_DAY.format(row.original.at)}`}
            actions={[
              ...(utcDay(row.original.at) === today
                ? [{ label: "Check in", icon: <LogInIcon />, onSelect: () => verbs.onCheckIn(row.original) }]
                : []),
              ...(row.original.at.getTime() > now.getTime()
                ? [{ label: "Reschedule", icon: <CalendarClockIcon />, onSelect: () => verbs.onReschedule(row.original) }]
                : []),
              {
                label: "Cancel appointment",
                icon: <XCircleIcon />,
                destructive: true,
                separatorBefore: true,
                onSelect: () => verbs.onCancel(row.original),
              },
            ]}
          />
        ) : null,
      meta: { align: "right", label: "Actions" },
    },
  ]
}
app/clinic/appointments/components/visit-figures.tsx
import { CalendarCheckIcon, CalendarClockIcon, CalendarDaysIcon, CalendarXIcon } from "lucide-react"

import { formatNumber, formatPercent } from "@/lib/format"
import { StatCard } from "@/components/ui/stat-card"
import { StatCardGroup } from "@/components/ui/stat-card-group"

import { type VisitRow } from "../data"

import { utcDay } from "./visit-vocabulary"

const inMonth = (at: Date, now: Date) => at.getUTCFullYear() === now.getUTCFullYear() && at.getUTCMonth() === now.getUTCMonth()

const hours = (minutes: number) => `${formatNumber(minutes / 60, { maximumFractionDigits: 1 })} h`

/**
 * The book in four numbers, counted off the rows the table holds: today's
 * visits, what is booked from now on, the month's visits and the month's
 * cancellations. The rows are the island's own, so a check-in or a
 * cancellation moves these in the same render as the row.
 */
export function VisitFigures({ rows, now }: { rows: VisitRow[]; now: Date }) {
  const today = rows.filter((row) => utcDay(row.at) === utcDay(now) && row.status !== "cancelled")
  const ahead = rows.filter((row) => row.status === "scheduled" && row.at.getTime() >= now.getTime())
  const month = rows.filter((row) => inMonth(row.at, now))
  const held = month.filter((row) => row.status !== "cancelled")
  const cancelled = month.length - held.length

  return (
    <StatCardGroup data-widget="widget-clinic-appointments-visit-figures" columns={4} role="region" aria-label="The book in figures">
      <StatCard
        label="Today"
        value={formatNumber(today.length)}
        description={`${today.filter((row) => row.status === "checked_in").length} checked in · ${today.filter((row) => row.status === "done").length} done`}
        icon={<CalendarCheckIcon />}
      />
      <StatCard
        label="Booked ahead"
        value={formatNumber(ahead.length)}
        description={`${hours(ahead.reduce((sum, row) => sum + row.durationMin, 0))} of clinic time`}
        icon={<CalendarClockIcon />}
      />
      <StatCard
        label="This month"
        value={formatNumber(held.length)}
        description={`${held.filter((row) => row.isNewPatient).length} new patients`}
        icon={<CalendarDaysIcon />}
      />
      <StatCard
        label="Cancelled"
        value={formatPercent(month.length === 0 ? 0 : cancelled / month.length, { maximumFractionDigits: 1 })}
        description={`${cancelled} of ${month.length} this month`}
        icon={<CalendarXIcon />}
      />
    </StatCardGroup>
  )
}
app/clinic/appointments/components/visit-vocabulary.ts
import { type VisitRow } from "../data"

/**
 * The windows this page cuts the book into, and the rule each one reads.
 * The words for a visit — its status, its day and time, the departments —
 * are the Clinic dashboard's, in `@/lib/dashboards/clinic/vocabulary`.
 */
export const WINDOWS = [
  { value: "ahead", label: "From today" },
  { value: "past", label: "Past" },
  { value: "all", label: "All" },
] as const

export type VisitWindow = (typeof WINDOWS)[number]["value"]

/** Midnight UTC on the day `date` falls on. */
export const utcDay = (date: Date) => Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())

/** Which visits a window holds: from today on, before today, or every one. */
export function inWindow(row: VisitRow, window: VisitWindow, now: Date): boolean {
  if (window === "all") return true
  return window === "ahead" ? utcDay(row.at) >= utcDay(now) : utcDay(row.at) < utcDay(now)
}