import type { ContactPoint, Patient } from "fhir/r4"; /** The first two values of one kind, primary then secondary, blank where absent. */ export const telecomSlots = (telecom: ContactPoint[] | undefined, system: "phone" | "email"): [string, string] => { const values = (telecom ?? []).filter((point) => point.system === system).map((point) => point.value ?? ""); return [values[0] ?? "", values[1] ?? ""]; }; /** The use (mobile, home, work...) of the same two entries, blank where none is recorded. */ export const telecomUseSlots = (telecom: ContactPoint[] | undefined, system: "phone" | "email"): [string, string] => { const uses = (telecom ?? []).filter((point) => point.system === system).map((point) => point.use ?? ""); return [uses[0] ?? "", uses[1] ?? ""]; }; /** * Write primary and secondary values for one kind. Existing entries keep their other fields (use, * rank), entries past the second are left alone, other kinds are untouched, and a cleared slot is * removed rather than stored empty. A use given for a slot replaces that entry's use; a blank one * clears it. */ export const setTelecomSlots = ( draft: Patient, system: "phone" | "email", values: [string, string], uses?: [string, string], ): void => { const all = draft.telecom ?? []; const same = all.filter((point) => point.system === system); const others = all.filter((point) => point.system !== system); const slots: ContactPoint[] = []; values.forEach((raw, index) => { const value = raw.trim(); if (!value) return; const slot: ContactPoint = same[index] ? { ...same[index], value } : { system, value, rank: index + 1 }; if (uses) { const use = uses[index] as ContactPoint["use"] | ""; if (use) slot.use = use; else delete slot.use; } slots.push(slot); }); const telecom = [...others, ...slots, ...same.slice(2)]; draft.telecom = telecom.length ? telecom : undefined; };