import type { DocumentReference } from 'fhir/r4'; // An outside original filed from Records keeps the file it denotes and its binding to the source it was copied from. // The server enforces this; the client neither offers to replace or remove that file nor drops the binding on an edit. const AHR = 'https://akashichealthrecords.com/fhir'; export const RECORDS_INTAKE_SYSTEM = AHR + '/records-intake'; export const RECORDS_SOURCE_EXTENSION = AHR + '/StructureDefinition/records-intake-source'; /** Whether a stored document is a filed Records original: any trace of the filing makes it one. */ export const isFiledOriginal = (document: DocumentReference | undefined | null): boolean => Boolean(document) && ( (document!.identifier ?? []).some((identifier) => identifier?.system === RECORDS_INTAKE_SYSTEM) || (document!.extension ?? []).some((extension) => extension?.url === RECORDS_SOURCE_EXTENSION) || (typeof document!.id === 'string' && document!.id.startsWith('ri-')) ); /** An edit of a filed original, carrying its stored file and source binding over whatever the form rebuilt. */ export function keepFiledLineage(stored: DocumentReference | undefined | null, edit: DocumentReference): DocumentReference { if (!stored || !isFiledOriginal(stored)) return edit; const identifier = [ ...(edit.identifier ?? []).filter((item) => item?.system !== RECORDS_INTAKE_SYSTEM), ...(stored.identifier ?? []).filter((item) => item?.system === RECORDS_INTAKE_SYSTEM), ]; const extension = [ ...(edit.extension ?? []).filter((item) => item?.url !== RECORDS_SOURCE_EXTENSION), ...(stored.extension ?? []).filter((item) => item?.url === RECORDS_SOURCE_EXTENSION), ]; // Every Records marker comes from what is stored, including when nothing is: the form's own marker never survives. const { identifier: _sentIdentifiers, extension: _sentExtensions, ...rest } = edit; return { ...rest, content: stored.content, ...(identifier.length > 0 ? { identifier } : {}), ...(extension.length > 0 ? { extension } : {}), }; } export const FILED_ORIGINAL_FILE_NOTE = 'This is an outside original filed from Records, so its file is kept as received. To correct it, add a separate document.';