import type { Appointment } from 'fhir/r4'; /** Whether a patient may still change answers they have sent. They lock once the visit uses them. */ export type SubmittedAnswersState = 'amendable' | 'locked'; // The lock starts at arrival rather than completion, so an answer cannot change while a clinician reads it. const VISIT_HAS_STARTED = new Set([ 'arrived', 'checked-in', 'fulfilled', ]); // Listed explicitly so a newly added appointment status cannot silently change the outcome. const VISIT_DID_NOT_HAPPEN = new Set([ 'cancelled', 'noshow', 'entered-in-error', ]); /** An undefined appointment means the answers are bound to no visit, so they stay amendable. */ export const submittedAnswersState = ( appointment?: Appointment, ): SubmittedAnswersState => { if (!appointment) return 'amendable'; if (VISIT_DID_NOT_HAPPEN.has(appointment.status)) return 'amendable'; return VISIT_HAS_STARTED.has(appointment.status) ? 'locked' : 'amendable'; }; /** * Whether the patient may amend now. Returns undefined while a bound appointment is still loading, so a * write guard can refuse until the answer is known. */ export const mayAmendNow = ( hasAppointmentBinding: boolean, appointment: Appointment | undefined, ): boolean | undefined => { if (hasAppointmentBinding && !appointment) return undefined; return submittedAnswersState(appointment) === 'amendable'; };