import type { Appointment, Organization, Task } from "fhir/r4"; import { isOutstandingTask, isPatientsOwnTask } from "../../../services/TaskService.tsx"; import { categorizePatientAppointments } from "../../../utils/patientAppointmentCategorization.ts"; import { getHostedPatientPortalUrl, getPatientPortalUrl } from "../../../utils/patientPortalUrl.ts"; const ORGANIZATION_TAG_SYSTEM = "https://akashichealthrecords.com/fhir/tags/organization"; export interface PracticeWaitingOnYou { organization: Organization; portalUrl?: string; tasks: Task[]; visits: Appointment[]; } const owningOrganizationTag = (resource: Task | Appointment): string | undefined => resource.meta?.tag?.find((tag) => tag.system === ORGANIZATION_TAG_SYSTEM)?.code; const taskOrganizationId = (task: Task): string | undefined => task.owner?.reference?.match(/^Organization\/(.+)$/)?.[1] ?? owningOrganizationTag(task); /** * The open work of each practice that is still waiting on the patient's agreements. Only the patient's * own reads go in, and each item is matched to its practice by owner or owning tag, never by guess. */ export const practicesWaitingOnYou = ( practices: Organization[], tasks: Task[], appointments: Appointment[], now: Date, ): PracticeWaitingOnYou[] => { const outstanding = tasks.filter((task) => isOutstandingTask(task) && isPatientsOwnTask(task)); const upcoming = categorizePatientAppointments(appointments, now).upcoming; return practices .filter((organization) => Boolean(organization.id)) .map((organization) => ({ organization, portalUrl: getPatientPortalUrl(organization) || getHostedPatientPortalUrl(organization), tasks: outstanding.filter((task) => taskOrganizationId(task) === organization.id), visits: upcoming.filter((appointment) => owningOrganizationTag(appointment) === organization.id), })); }; const PRACTICE_RELATIONSHIP_SYSTEM = "https://akashichealthrecords.com/fhir/CodeSystem/practice-relationship"; /** The server could not read this practice's agreement states, so what it is owed is unknown. */ export const agreementsUnknown = (organization: Organization): boolean => Boolean(organization.meta?.tag?.some( (tag) => tag.system === PRACTICE_RELATIONSHIP_SYSTEM && tag.code === "agreements-unknown", ));