import type { Encounter, Reference } from 'fhir/r4'; /** * Add a diagnosis to a visit, or say there is nothing to add. * * WHY THIS IS A FUNCTION AND NOT FOUR LINES INSIDE THE SERVICE. The service call around it is a * read-modify-write against a live Encounter, so exercising it needs the whole provider stack and a * mocked transport. The decision it makes - what the encounter should look like afterwards - is pure, * and it is the half that can be wrong in a way nobody sees. * * IT PRESERVES EVERY OTHER ENTRY, and that is the point rather than a nicety. `Encounter.diagnosis` is * an array of everything found in the visit; a second diagnosis that replaced the array instead of * appending would delete the first, and the screen would look right because the newest one is the one * being read back. * * NULL MEANS "ALREADY THERE", NOT "FAILED". Returning the encounter unchanged would send a PUT that * writes nothing, and a write that does nothing still makes a new version of the resource and still * costs the history a row that says a change happened when none did. */ export const encounterWithDiagnosis = ( encounter: Encounter, conditionRef: Reference, ): Encounter | null => { const target = conditionRef.reference; if (!target) return null; const existing = encounter.diagnosis ?? []; if (existing.some((entry) => entry.condition?.reference === target)) return null; return { ...encounter, diagnosis: [...existing, { condition: conditionRef }] }; };