import type { Communication } from 'fhir/r4'; import { hasReadReceiptForReference } from './readReceipts'; /** * Whom a read receipt names: the server's caller. A helper acting for someone is their link there, never the account * they signed in with; while that link is not known yet, nobody, so nothing is marked read in the wrong name. */ export const receiptReferenceOf = ( user: { resourceType?: string; id?: string } | undefined, actingAs: { relatedPersonId?: string } | null | undefined, ): string | null => { if (actingAs) return actingAs.relatedPersonId ? `RelatedPerson/${actingAs.relatedPersonId}` : null; return user?.resourceType && user.id ? `${user.resourceType}/${user.id}` : null; }; export const editionOf = (message: Communication): number | null => { const version = message.meta?.versionId; if (!version || !/^[0-9]+$/.test(version)) return null; const edition = Number(version); return Number.isSafeInteger(edition) ? edition : null; }; /** * A receipt is confirmed only by what the save returned: the same message, carrying `reader`'s receipt, as a newer * edition than the one it was written on. Anything else, a missing or non-numeric edition included, is not proof. */ export const receiptConfirmed = (reader: string) => (sent: Communication, returned: Communication): boolean => { const before = editionOf(sent); const after = editionOf(returned); return returned.id === sent.id && before !== null && after !== null && after > before && hasReadReceiptForReference(returned, reader); };