import type { Patient } from "fhir/r4"; // A profile section saves from a fresh read, but its form was filled from the record as it stood when // editing began. If what the section edits changed in between (a contact added from another screen, // say), writing the form would silently delete that change, so the save is refused instead. /** Key order carries no meaning in a FHIR resource, so it must not count as a change. */ const stable = (value: unknown): unknown => { if (Array.isArray(value)) return value.map(stable); if (value && typeof value === "object") { return Object.keys(value as Record) .sort() .reduce>((out, key) => { const entry = (value as Record)[key]; if (entry !== undefined) out[key] = stable(entry); return out; }, {}); } return value; }; export const sectionChangedSince = ( baseline: Patient | undefined, latest: Patient, pick: (patient: Patient) => unknown, ): boolean => { if (!baseline) return false; // Equal values on another patient are not this patient's section. if (baseline.id !== latest.id) return true; return JSON.stringify(stable(pick(baseline))) !== JSON.stringify(stable(pick(latest))); };