import type { Provenance } from 'fhir/r4'; import type { MyHistoryEvent } from '../history/collapseHistory'; import type { ResourceHistoryFetchResult } from './useFieldHistoryFetch'; export interface RecordCreation { who?: string; whenIso?: string; /** The attribution could not be read, so who created the record is not known here. */ unreadable: boolean; } const isCreate = (provenance: Provenance): boolean => provenance.activity?.text === 'CREATE' || (provenance.activity?.coding ?? []).some((coding) => coding.code === 'CREATE'); /** * Who created a resource, from its stored CREATE Provenance, or from the caller's own activity feed * when they may not read Provenance. Never the current user and never a field on the resource, and * never from a read that did not cover the whole attribution. */ export function readRecordCreation( result: ResourceHistoryFetchResult, activity: MyHistoryEvent[], resourceType: string, resourceId: string, ): RecordCreation { if (result.provenanceRefused) { const event = activity.find((row) => row.action === 'C' && row.resourceType === resourceType && row.resourceId === resourceId && Boolean(row.actorName)); if (event) return { who: event.actorName, whenIso: event.recorded, unreadable: false }; return { unreadable: true }; } if (result.provenanceUnreadable || result.attribution !== 'complete') { return { unreadable: true }; } const created = result.provenances.find(isCreate); const agent = created?.agent?.[0]?.who; const who = agent?.display ?? agent?.reference; return who ? { who, whenIso: created?.recorded, unreadable: false } : { unreadable: false }; }