"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 } }
}