From 7a907d73d53799b53611ca3021926eafbaccf4ab Mon Sep 17 00:00:00 2001 From: Ana Garcia Date: Thu, 7 Nov 2024 12:28:16 +0100 Subject: [PATCH] Do not allow to delete teamRoles if it's parent and all children are not selected --- .../useIMTeamBuilder.ts | 61 ++++++++++++++++--- 1 file changed, 51 insertions(+), 10 deletions(-) diff --git a/src/webapp/pages/incident-management-team-builder/useIMTeamBuilder.ts b/src/webapp/pages/incident-management-team-builder/useIMTeamBuilder.ts index fbc7aa1..09e046f 100644 --- a/src/webapp/pages/incident-management-team-builder/useIMTeamBuilder.ts +++ b/src/webapp/pages/incident-management-team-builder/useIMTeamBuilder.ts @@ -88,19 +88,15 @@ export function useIMTeamBuilder(diseaseOutbreakEventId: Id): State { } ); - const selectedItemsUsernames = incidentManagementTeamItemsSelected?.map( - ({ username }) => username - ); - - const hasSomeParentReporting = !!incidentManagementTeam?.teamHierarchy.some( - teamMember => - teamMember.teamRoles?.some(teamRole => - selectedItemsUsernames?.includes(teamRole.reportsToUsername || "") - ) + const areAllParentsAndAllChildrenSelected = checkIfParentsAndAllChildrenSelected( + newSelection, + incidentManagementTeam?.teamHierarchy ); setSelectedHierarchyItemIds(newSelection); - setDisableDeletion(isIncidentManagerRoleSelected || hasSomeParentReporting); + setDisableDeletion( + isIncidentManagerRoleSelected || !areAllParentsAndAllChildrenSelected + ); }, [ incidentManagementTeam?.teamHierarchy, @@ -198,3 +194,48 @@ export function useIMTeamBuilder(diseaseOutbreakEventId: Id): State { constactTableRows, }; } + +function checkIfParentsAndAllChildrenSelected( + teamRoleSelection: Id[], + incidentManagementTeamHierarchy: Maybe +): boolean { + if (!incidentManagementTeamHierarchy) return true; + + const selectedItemsInTeamHierarchy = incidentManagementTeamHierarchy + .map(teamMember => ({ + ...teamMember, + teamRoles: teamMember.teamRoles?.filter(teamRole => + teamRoleSelection.includes(teamRole.id) + ), + })) + .filter(teamMember => teamMember.teamRoles?.length); + + const allTeamRoleChildrenIdsByParentId = getAllTeamRoleChildrenIdsByParentTeamRoleId( + incidentManagementTeamHierarchy + ); + + return selectedItemsInTeamHierarchy.every(teamMember => { + const teamRoleChildrenIds = allTeamRoleChildrenIdsByParentId.get(teamMember.username); + return ( + !teamRoleChildrenIds || + teamRoleChildrenIds.every(childId => { + return teamRoleSelection.includes(childId); + }) + ); + }); +} + +function getAllTeamRoleChildrenIdsByParentTeamRoleId(teamMembers: TeamMember[]): Map { + return teamMembers.reduce((acc, teamMember) => { + return ( + teamMember.teamRoles?.reduce((innerAcc, teamRole) => { + const parentTeamRoleId = teamRole.reportsToUsername; + if (parentTeamRoleId) { + const existingChildren = innerAcc.get(parentTeamRoleId) || []; + innerAcc.set(parentTeamRoleId, [...existingChildren, teamRole.id]); + } + return innerAcc; + }, acc) || acc + ); + }, new Map()); +}