import type { CodeableConcept, Observation, Quantity } from 'fhir/r4'; import { UCUM_POUND } from './trackableMeasures'; import { toLocalDateTimeInput } from './dateUtils'; /** * The staff observation form shows and edits one coding. An edit that leaves that coding as it was keeps * every stored coding, so a patient's reading keeps its own measure code and its LOINC; only a changed * code replaces them. */ export const keepStoredCode = (stored: CodeableConcept | undefined, edited: CodeableConcept): CodeableConcept => { const shown = stored?.coding?.[0]; const now = edited.coding?.[0]; const unchanged = Boolean(shown) && (shown?.code ?? '') === (now?.code ?? '') && (shown?.display ?? '') === (now?.display ?? ''); return unchanged && stored ? stored : edited; }; /** The unit select's choice for a stored quantity: a pound shows as the UCUM pound whether or not it carries the code. */ export const unitChoice = (quantity: Quantity | undefined): string => (quantity?.code === UCUM_POUND || quantity?.unit === 'lb' ? UCUM_POUND : quantity?.unit ?? ''); /** * The quantity a save writes. Keeping the unit keeps the stored quantity's own unit and code and changes * only the value, so an older "lb" reading is not rewritten; a newly chosen pound is written as lb with * its UCUM code, as patient readings are. */ export const keepStoredQuantity = (stored: Quantity | undefined, value: number, choice: string): Quantity => { if (stored && unitChoice(stored) === choice) return { ...stored, value }; if (choice === UCUM_POUND) return { value, unit: 'lb', system: 'http://unitsofmeasure.org', code: UCUM_POUND }; return { value, unit: choice, system: 'http://unitsofmeasure.org', code: choice }; }; /** * The stored instant an edit keeps. The form's datetime-local field holds only the minute, so a field * still showing the stored minute keeps the stored instant with its seconds; anything else is the user's. */ export const keepStoredInstant = (stored: string | undefined, edited: string | undefined): string | undefined => (stored && edited && edited === toLocalDateTimeInput(new Date(stored)) ? stored : undefined); /** When a reading was taken. meta.lastUpdated is when it was last written, which any edit moves. */ export const readingTakenAt = (observation: Observation): string => observation.effectiveDateTime ?? observation.effectivePeriod?.start ?? observation.effectiveInstant ?? '';