Skip to contentVibraUI
Dashboards

Clinic desk actions

The clinic desk's server actions — check a patient in, cancel a visit, move one to another slot and change a patient's contact — shared by every Clinic page that changes a visit or a patient.

A "use server" module the Clinic overview and the Appointments page both import. Each action looks the visit up by id and trusts only the stored row: only a visit that is still booked can be cancelled, and only one still booked for REFERENCE_DATE's own day can be checked in — a visit on a later day is "not due until" it; one under way, done or already cancelled is refused with a sentence that names the patient. rescheduleAppointment moves a visit still booked to a day and a time the caller names, "YYYY-MM-DD" and "HH:mm" in UTC, read with calendarDay and with time-picker/time's parseTime, so a time is one only when it reads back as itself; the new start is after REFERENCE_DATE, on a day at most 180 days after today's — "The book is open 180 days ahead, to Wed, Mar 3." — on a weekday, from 08:00 and over by 18:00 for the visit's stored length, on a quarter hour, all from hours-clinic's CLINIC_HOURS, which the reschedule dialog offers from too, and in time the doctor gives no other patient booked or already checked in — "Dr. Amara Osei is with Ana Baker then." names who. What comes back is the visit trimmed to what a page prints — its status and its time, no email — because a server action's return value travels to the browser; a refusal carries the visit as the store holds it too. updatePatientContact writes an address and a number to every visit under a patient's name — a patient is a name in the book — after trimming the address and asking isEmail, and asking isValidPhone from phone-input/phone of the number, which reads the same metadata the field typed with: a whole, valid number in E.164, or "Check the number — it doesn't look complete."; a refusal names the field.

Install

npx shadcn@latest add @vibra/actions-clinic

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

Props

PropTypeDefaultDescription
checkInAppointment(id: string) => Promise<VisitAnswer>—Marks a visit booked for today as arrived; refuses another day, and any other status.
cancelAppointment(id: string) => Promise<VisitAnswer>—Takes a booked visit out of the book; refuses one under way, done or already cancelled.
rescheduleAppointment(id: string, day: string, time: string) => Promise<VisitAnswer>—Moves a booked visit to day (YYYY-MM-DD) at time (HH:mm), UTC; refuses a visit not booked, a malformed day or time (invalid_input), a start not after now, a day more than 180 days after today's, a weekend, before 08:00, off the quarter hour, ending after 18:00, and the doctor's time with another patient.
updatePatientContact(name: string, email: string, phone: string) => Promise<Result<PatientContact>>—Writes the address and the E.164 number to every visit under the name; refuses an unknown patient (not_found), an address that is not one and a number that is not whole (invalid_input, with the field).
VisitChange{ id, patient, doctor, status, at }—The visit after the action: where it stands and when.
PatientContact{ name, email, phone }—A patient's contact after a save, as every visit of theirs now holds it.
VisitAnswer{ ok: true, data: VisitChange } | { ok: false, error, current?: VisitChange }—A Result whose refusal also carries the visit as it stands — absent only when no appointment has the id.

Dependencies

Source

lib/dashboards/clinic/actions.ts
"use server"

import { CLINIC_HOURS } from "@/lib/dashboards/clinic/hours"
import { REFERENCE_DATE, calendarDay, db, type Appointment, type Result } from "@/lib/sample-data"
import { isEmail } from "@/lib/validation"
import { isValidPhone } from "@/components/ui/phone-input/phone"
import { formatTime, parseTime, timeToMinutes } from "@/components/ui/time-picker/time"

/**
 * The clinic desk's verbs, shared by every Clinic page that changes a visit:
 * the overview's upcoming book and the appointments table both call these,
 * so a check-in means the same thing wherever it is pressed.
 *
 * Each action looks the visit up by id and trusts only that row. What comes
 * back is the visit trimmed to what a page prints — a server action's return
 * value is serialised to the browser, so it carries no email and nothing the
 * page did not ask for. A refusal carries the visit as the store now holds
 * it as well, so the page that asked can stop showing the state the desk
 * just found out was wrong.
 */

/** A visit after a desk action: enough to name the patient, and where the visit now stands and when. */
export type VisitChange = {
  id: string
  patient: string
  doctor: string
  status: Appointment["status"]
  at: Date
}

/** What a desk action answers: the visit it moved, or why it would not — with the visit as it stands, when there is one. */
export type VisitAnswer =
  | { ok: true; data: VisitChange }
  | { ok: false; error: { code: string; message: string }; current?: VisitChange }

const DUE = new Intl.DateTimeFormat("en-US", { weekday: "short", month: "short", day: "numeric", timeZone: "UTC" })

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

const change = ({ id, patient, doctor, status, at }: Appointment): VisitChange => ({ id, patient, doctor, status, at })

const refuse = (appointment: Appointment, message: string, code = "conflict"): VisitAnswer => ({
  ok: false,
  error: { code, message },
  current: change(appointment),
})

const missing = (id: string): VisitAnswer => ({
  ok: false,
  error: { code: "not_found", message: `No appointment with id "${id}".` },
})

async function move(appointment: Appointment, status: Appointment["status"]): Promise<VisitAnswer> {
  const updated = await db.appointments.update(appointment.id, { status })
  if (!updated.ok) return updated
  return { ok: true, data: change(updated.data) }
}

/**
 * Marks a patient as arrived. Only a visit still booked, on today's own day,
 * can be checked in: a patient is not seen a week early, and a visit whose
 * day has gone by is not an arrival.
 */
export async function checkInAppointment(id: string): Promise<VisitAnswer> {
  const appointment = await db.appointments.get(id)
  if (!appointment) return missing(id)

  if (appointment.status !== "scheduled") {
    const state = {
      checked_in: "already checked in",
      done: "already done",
      cancelled: "cancelled",
    }[appointment.status]
    return refuse(appointment, `${appointment.patient}'s visit is ${state}.`)
  }
  const day = utcDay(appointment.at)
  const today = utcDay(REFERENCE_DATE)
  if (day > today) return refuse(appointment, `${appointment.patient}'s visit is not due until ${DUE.format(appointment.at)}.`)
  if (day < today) return refuse(appointment, `${appointment.patient}'s visit was due on ${DUE.format(appointment.at)}.`)

  return move(appointment, "checked_in")
}

/**
 * Takes a visit out of the book. Only a visit that is still booked can be
 * cancelled: a patient who has arrived is being seen, and a visit that is
 * done is history.
 */
export async function cancelAppointment(id: string): Promise<VisitAnswer> {
  const appointment = await db.appointments.get(id)
  if (!appointment) return missing(id)

  switch (appointment.status) {
    case "checked_in":
      return refuse(appointment, `${appointment.patient} is already checked in — the visit is under way.`)
    case "done":
      return refuse(appointment, `${appointment.patient}'s visit is already done.`)
    case "cancelled":
      return refuse(appointment, `${appointment.patient}'s visit is already cancelled.`)
  }

  return move(appointment, "cancelled")
}

/** The clinic's day in minutes, from its hours: the first start, and the time every visit is over by. */
const OPENS = timeToMinutes(CLINIC_HOURS.opens)
const CLOSES = timeToMinutes(CLINIC_HOURS.closes)
const DAY_MS = 86_400_000

const CLOCK = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", timeZone: "UTC" })
/** One of the clinic's hours, "8:00 AM": formatTime writes its own colon and space. */
const hour = (time: string) => formatTime(time, { hourCycle: "h12" })

/** Whether `other` keeps its doctor busy at any minute from `start` to `end`: a visit still to come, or under way. */
const holds = (other: Appointment, start: number, end: number) =>
  (other.status === "scheduled" || other.status === "checked_in") &&
  other.at.getTime() < end &&
  start < other.at.getTime() + other.durationMin * 60_000

/**
 * Moves a visit still booked to another day and time: `day` as "YYYY-MM-DD"
 * and `time` as "HH:mm" on the 24-hour clock, both in UTC, as the clinic
 * keeps it. The new start has to be after now, on a day the book is open —
 * at most 180 days after today's — on a weekday, inside the clinic's hours —
 * from 08:00, and over by 18:00 for the visit's own length — on a quarter
 * hour, and in time the doctor gives no other patient booked or already
 * checked in. The hours are CLINIC_HOURS, which the dialog offers from too.
 * The visit's length, its doctor and its patient are the stored row's; the
 * day and the time are the only things the caller chooses.
 */
export async function rescheduleAppointment(id: string, day: string, time: string): Promise<VisitAnswer> {
  const appointment = await db.appointments.get(id)
  if (!appointment) return missing(id)

  if (appointment.status !== "scheduled") {
    const state = {
      checked_in: `${appointment.patient} has already checked in.`,
      done: `${appointment.patient}'s visit is already done.`,
      cancelled: `${appointment.patient}'s visit is cancelled.`,
    }[appointment.status]
    return refuse(appointment, state)
  }

  // The field writes "HH:mm"; parseTime reads anything a person types, so a
  // time is one only when it reads back as itself.
  const date = calendarDay(day)
  if (!date) return refuse(appointment, "That is not a day on the calendar.", "invalid_input")
  if (typeof time !== "string" || parseTime(time) !== time) return refuse(appointment, "That is not a time of day.", "invalid_input")

  const minutes = timeToMinutes(time)
  const start = date.getTime() + minutes * 60_000
  const end = start + appointment.durationMin * 60_000
  if (start <= REFERENCE_DATE.getTime()) {
    return refuse(appointment, `That time has passed: it is ${CLOCK.format(REFERENCE_DATE)} on ${DUE.format(REFERENCE_DATE)}.`)
  }
  const lastDay = utcDay(REFERENCE_DATE) + CLINIC_HOURS.horizonDays * DAY_MS
  if (date.getTime() > lastDay) {
    return refuse(appointment, `The book is open ${CLINIC_HOURS.horizonDays} days ahead, to ${DUE.format(new Date(lastDay))}.`)
  }
  if (date.getUTCDay() === 0 || date.getUTCDay() === 6) return refuse(appointment, "The clinic is closed at the weekend.")
  if (minutes < OPENS) return refuse(appointment, `The clinic opens at ${hour(CLINIC_HOURS.opens)}.`)
  if ((minutes - OPENS) % CLINIC_HOURS.step !== 0) {
    return refuse(appointment, `Visits start every ${CLINIC_HOURS.step} minutes from ${hour(CLINIC_HOURS.opens)}.`)
  }
  if (minutes + appointment.durationMin > CLOSES) {
    return refuse(
      appointment,
      `A ${appointment.durationMin}-minute visit at ${CLOCK.format(start)} would run past ${hour(CLINIC_HOURS.closes)}, when the clinic closes.`
    )
  }

  const clash = db.appointments
    .all()
    .find((other) => other.id !== appointment.id && other.doctor === appointment.doctor && holds(other, start, end))
  if (clash) return refuse(appointment, `${clash.doctor} is with ${clash.patient} then.`)

  const updated = await db.appointments.update(appointment.id, { at: new Date(start) })
  if (!updated.ok) return updated
  return { ok: true, data: change(updated.data) }
}

/** A patient's contact details after a save: the name the book has them under, and what every visit of theirs now holds. */
export type PatientContact = { name: string; email: string; phone: string }

/**
 * Writes a patient's address and number to every visit under their name — a
 * patient is a name in the book. The visits are the store's, found by the
 * name; the address is trimmed and has to be one (isEmail), and the number has
 * to be whole and valid in E.164, read with the same metadata the phone field
 * types against. A refusal names the field it is about.
 */
export async function updatePatientContact(name: string, email: string, phone: string): Promise<Result<PatientContact>> {
  const visits = typeof name === "string" ? db.appointments.all().filter((row) => row.patient === name) : []
  if (visits.length === 0) return { ok: false, error: { code: "not_found", message: "No patient by that name is in the book." } }

  const address = typeof email === "string" ? email.trim() : ""
  if (!isEmail(address)) return { ok: false, error: { code: "invalid_input", field: "email", message: "Enter a valid email address." } }
  if (!isValidPhone(phone)) {
    return { ok: false, error: { code: "invalid_input", field: "phone", message: "Check the number — it doesn't look complete." } }
  }

  for (const visit of visits) {
    const updated = await db.appointments.update(visit.id, { email: address, phone })
    if (!updated.ok) return updated
  }
  return { ok: true, data: { name: visits[0].patient, email: address, phone } }
}