// Whose team it is: the patient's own, or somebody else's that the patient is a member of. // Pure, so it is importable under the plain-node test environment. import type { CollaborationTeam, TeamMembership } from '../services/collaborationTeam'; export type TeamWithMembers = CollaborationTeam & { members: TeamMembership[] }; /** The patient's own link to somebody else, as the my-proxies list reports it. */ export interface ProxyLink { relatedPersonId: string; subjectPatientId: string; subjectName?: string; } export interface OtherTeam { team: TeamWithMembers; /** The patient's own row on that team. */ mine: TeamMembership; ownerName: string; } export interface TeamSides { mine: TeamWithMembers[]; /** Teams the patient belongs to. */ others: OtherTeam[]; /** Teams the patient has been asked to join and has not answered. */ invitations: OtherTeam[]; } // A team with no patientId is read as the caller's own: the patient branch of the list only ever returns its own. export const splitTeamsByOwner = ( teams: TeamWithMembers[], patientId: string | undefined, proxies: ProxyLink[], ): TeamSides => { const sides: TeamSides = { mine: [], others: [], invitations: [] }; for (const team of teams) { if (!team.patientId || team.patientId === patientId) { sides.mine.push(team); continue; } // The patient sits on somebody else's team as that person's related person, and only there. const link = proxies.find((proxy) => proxy.subjectPatientId === team.patientId); const mine = link && team.members.find((member) => member.memberRef === `RelatedPerson/${link.relatedPersonId}`); if (!link || !mine) continue; const other: OtherTeam = { team, mine, ownerName: team.patientDisplay?.trim() || link.subjectName?.trim() || 'Someone', }; if (mine.state === 'invited') { if (team.status !== 'dissolved') sides.invitations.push(other); } else if (mine.state === 'active') { sides.others.push(other); } } return sides; };