Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 5x 15x 15x 15x 15x 5x 26x 26x 26x 5x 5x 15x 5x 15x 15x 15x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 7x 7x 3x 3x 3x 7x 2x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 3x 3x 3x 3x 3x 3x 12x 12x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 16x 19x 3x 3x 3x 19x 19x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 15x 9x 9x 6x 10x 10x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 21x 21x 21x 21x 21x 20x 20x 20x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x | import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isEmpty, omit, partition, uniq, uniqBy } from 'lodash-es';
import { type SetOptional, type SetRequired } from 'type-fest';
import { DataSource, In, IsNull, LessThanOrEqual, MoreThanOrEqual, Or, Repository } from 'typeorm';
import {
KEYV_NAMESPACE,
KeyvRepository,
Team,
TeamAssignment,
User,
type Company,
type Period,
} from '@amalia/core/models';
import { dateIsInAssignmentRange, toTimestamp, UnixTimestampInSeconds } from '@amalia/ext/dates';
import { assert } from '@amalia/ext/typescript';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { TeamRole } from '@amalia/tenants/assignments/teams/types';
import { HierarchyContext } from '@amalia/tenants/teams/hierarchy/shared';
import { HierarchyContextDehydrated } from '@amalia/tenants/teams/hierarchy/types';
import { getTeamAncestors, makeTeamsTree } from '@amalia/tenants/teams/shared/tree';
import { TeamTreeNode } from '@amalia/tenants/teams/types';
import { UserRole } from '@amalia/tenants/users/types';
@Injectable()
export class HierarchyContextService {
public constructor(
@InjectRepository(TeamAssignment)
private readonly teamAssignmentRepository: Repository<TeamAssignment>,
@InjectRepository(Team)
private readonly teamRepository: Repository<Team>,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
private readonly datasource: DataSource,
private readonly keyvRepository: KeyvRepository,
) {}
public async forceClearHierarchyContextCache() {
await this.keyvRepository.clearByNamespace(KEYV_NAMESPACE.HIERARCHY_CONTEXT);
}
public filterUsersUsingHierarchy<T extends User | string>(
authenticatedContext: AuthenticatedContext,
date: Date | UnixTimestampInSeconds,
users: T[],
): T[] {
const { user: currentUser, hierarchy, adminScopesContainer } = authenticatedContext;
switch (currentUser.role) {
case UserRole.ADMIN:
case UserRole.READ_ONLY_ADMIN:
case UserRole.FINANCE:
return users;
case UserRole.SCOPED_ADMIN:
case UserRole.SCOPED_READ_ONLY_ADMIN: {
assert(adminScopesContainer, 'adminScopesContainer is not defined');
return users.filter((user) => {
const userId = typeof user === 'string' ? user : user.id;
return adminScopesContainer.userIsInScope(userId, date) || currentUser.id === userId;
});
}
case UserRole.MANAGER:
case UserRole.READ_ONLY_MANAGER: {
return users.filter((user) => {
const userId = typeof user === 'string' ? user : user.id;
return hierarchy.isManagerOf(userId, date) || currentUser.id === userId;
});
}
case UserRole.EMPLOYEE:
return users.filter((user) => (typeof user === 'string' ? user : user.id) === currentUser.id);
default:
throw new Error(`Role ${currentUser.role} not found`);
}
}
public async isManagerOf<T extends User | string>(
company: Company,
currentUser: User,
date: Date | UnixTimestampInSeconds,
user: T,
): Promise<boolean> {
switch (currentUser.role) {
case UserRole.ADMIN:
case UserRole.READ_ONLY_ADMIN:
case UserRole.FINANCE:
return true;
case UserRole.MANAGER:
case UserRole.READ_ONLY_MANAGER: {
const hierarchyContext = await this.getHierarchyContext(company, currentUser);
return hierarchyContext.isManagerOf(typeof user === 'string' ? user : user.id, date);
}
case UserRole.EMPLOYEE:
return false;
default:
throw new Error(`Role ${currentUser.role} not found`);
}
}
/**
* Get all users on which the current user have authority.
*
* For admin it's the whole company (you can filter what you want to see
* using the filters). For managers it's their scope. For employees it's
* themselves.
*
* @param company
* @param authenticatedContext
* @param date
* @param filters
* @param period
*/
public async getSubordinates(
company: Company,
authenticatedContext: AuthenticatedContext,
date: Date | UnixTimestampInSeconds,
filters?: { planIds?: string[] | null; teamIds?: string[] | null; userIds?: string[] | null },
period?: Period | null,
): Promise<User[]> {
const planIds = filters?.planIds;
const teamIds = filters?.teamIds;
const userIds = filters?.userIds;
// If you want to filter on plans but pass an empty array, it means that you'd like
// to get assignments of zero plans, same for teams and users.
// Return an empty array immediately.
if ((planIds && !planIds.length) || (teamIds && !teamIds.length) || (userIds && !userIds.length)) {
return [];
}
const queryBuilder = this.userRepository.createQueryBuilder('user');
queryBuilder.where('user.company = :companyId', { companyId: company.id });
if (planIds?.length) {
queryBuilder.leftJoinAndSelect('user.planAssignements', 'planAssignement');
queryBuilder.andWhere('planAssignement.planId IN (:...planIds)', {
planIds,
});
}
if (teamIds?.length) {
queryBuilder.leftJoinAndSelect('user.teamAssignments', 'teamAssignment');
queryBuilder.andWhere('teamAssignment.teamId IN (:...teamIds)', {
teamIds,
});
if (period) {
const { endDate, startDate } = period;
queryBuilder.andWhere('COALESCE(teamAssignment.effectiveAsOf, :endDate) <= :endDate', {
endDate,
});
queryBuilder.andWhere('COALESCE(teamAssignment.effectiveUntil, :startDate) >= :startDate', {
startDate,
});
}
}
if (userIds?.length) {
queryBuilder.andWhere('user.id IN (:...userIds)', {
userIds,
});
}
const retrievedUsers = await queryBuilder.getMany();
return this.filterUsersUsingHierarchy(authenticatedContext, date, retrievedUsers);
}
/**
* Get the hierarchy context.
*
* It'll try to get it from the kv cache. If it's not there or
* expired, it'll return a new one and return it.
*
* @param company
* @param currentUser
*/
public async getHierarchyContext(company: Company, currentUser: User): Promise<HierarchyContext> {
const hierarchyContextDehydratedInCache = await this.keyvRepository.get<HierarchyContextDehydrated>(
KEYV_NAMESPACE.HIERARCHY_CONTEXT,
company.id,
currentUser.id,
);
let hc: HierarchyContext;
if (hierarchyContextDehydratedInCache) {
hc = HierarchyContext.hydrate(currentUser, hierarchyContextDehydratedInCache);
} else {
hc = await this.buildHierarchyContext(company, currentUser);
await this.keyvRepository.set(KEYV_NAMESPACE.HIERARCHY_CONTEXT, company.id, currentUser.id, hc.dehydrate());
}
return hc;
}
private async buildHierarchyContext(company: Company, currentUser: User): Promise<HierarchyContext> {
// Get all team assignments of the manager. We don't care about dates, we'll take everything.
const currentUserAssignments = (await this.teamAssignmentRepository.find({
where: {
company: { id: company.id },
userId: currentUser.id,
},
relations: ['team', 'user'],
})) as SetRequired<TeamAssignment, 'team' | 'user'>[];
// Get the hierarchy of all teams where the manager has or had authority on.
const { teamsTree, teamIds } = await this.getTeamsIdsWhereUserIsManager(
currentUserAssignments.filter((ta) => ta.teamRole === TeamRole.TEAM_MANAGER),
);
// Get all team assignments of those teams.
const subordinatesAssignments = teamIds.length
? ((await this.teamAssignmentRepository.find({
where: {
company: { id: company.id },
teamId: In(teamIds),
},
relations: ['user'],
})) as SetRequired<TeamAssignment, 'user'>[])
: [];
// Build the scope.
return new HierarchyContext(
currentUser,
// Uniquing to avoid having the manager assignment twice.
uniqBy([...currentUserAssignments, ...subordinatesAssignments], (ta) => ta.id),
teamsTree,
);
}
/**
* List all teams that the current user can see at a given date.
* @param company
* @param currentUser
* @param date
*/
public async listTeamsCurrentUserCanSee(
company: Company,
currentUser: User,
date: Date | UnixTimestampInSeconds,
): Promise<Omit<Team, 'childrenTeams'>[]> {
// TODO: has RBAC "list all" right
if ([UserRole.ADMIN, UserRole.FINANCE, UserRole.READ_ONLY_ADMIN].includes(currentUser.role)) {
return this.datasource.getRepository(Team).find({ where: { company: { id: company.id } } });
}
const allAssignments = await this.teamAssignmentRepository.find({
where: {
company: { id: company.id },
userId: currentUser.id,
},
relations: ['team'],
});
const dateTimestamp = toTimestamp(date);
const allAssignmentsAtDate = allAssignments.filter((a) => dateIsInAssignmentRange(dateTimestamp, a));
// Get the hierarchy of all teams where the manager has authority on at the given date.
const { teams } = await this.getTeamsIdsWhereUserIsManager(
allAssignmentsAtDate.filter((a) => a.teamRole === TeamRole.TEAM_MANAGER),
);
// Finally, we can say that I can see all teams that I'm directly assigned, and those I manage at the current date.
return uniqBy([...allAssignments.map((a) => a.team).filter(Boolean), ...teams], (team) => team.id);
}
/**
* List all teams where the current user is or have been manager.
*
* @param managerAssignments
* @private
*/
private async getTeamsIdsWhereUserIsManager(managerAssignments: TeamAssignment[]) {
// Get teams and their descendants.
const firstLevelTeams = uniqBy(managerAssignments.map((ma) => ma.team).filter(Boolean), (team) => team.id);
const teamsTree = await Promise.all(
firstLevelTeams.map((team) => this.datasource.getTreeRepository(Team).findDescendantsTree(team)),
);
const teams = uniqBy(HierarchyContextService.flattenTeamTree(teamsTree), (team) => team.id);
return {
teamsTree,
teams,
teamIds: teams.map((t) => t.id),
};
}
/**
* Helper function to transform a tree of teams into a list of teams.
*
* @param teamTree
* @private
*/
private static flattenTeamTree(teamTree: SetOptional<Team, 'childrenTeams'>[]): Omit<Team, 'childrenTeams'>[] {
if (!teamTree.length) {
return [];
}
return teamTree.flatMap((team) => [
omit(team, ['childrenTeams']),
...this.flattenTeamTree(team.childrenTeams ?? []),
]);
}
/**
* Generates a tree structure of teams for a given company.
*
* @param company
* @private
* @returns A tree structure of teams.
*/
private async generateTeamTree(company: Company) {
const teams = await this.teamRepository.find({
where: { company: { id: company.id } },
});
return makeTeamsTree(teams);
}
/**
* Get the list of team ids where the user is assigned.
*
* @param company
* @param userId
* @param period
* @returns Team ids where the user is assigned
* @private
*/
private async getTeamsWhereUserIsAssigned(
company: Company,
userId: User['id'],
period: Pick<Period, 'endDate' | 'startDate'>,
): Promise<{ employeeRolesTeams: Team[]; managerRolesTeams: Team[] }> {
const teamsAssignments = await this.teamAssignmentRepository.find({
where: {
company: { id: company.id },
userId,
effectiveAsOf: Or(IsNull(), LessThanOrEqual(period.startDate)),
effectiveUntil: Or(IsNull(), MoreThanOrEqual(period.endDate)),
},
relations: ['team'],
});
const [employeeRoles, managerRoles] = partition(teamsAssignments, (ta) => ta.teamRole === TeamRole.TEAM_EMPLOYEE);
return {
employeeRolesTeams: uniqBy(employeeRoles.map((ta) => ta.team).filter(Boolean), 'id'),
managerRolesTeams: uniqBy(managerRoles.map((ta) => ta.team).filter(Boolean), 'id'),
};
}
/**
* Get the list of all parent team ids for a given list of teams.
*
* @param teamsToGetParentsFrom
* @param teamTree
* @returns
*/
private getAllParentTeamIds(teamsToGetParentsFrom: Team[], teamTree: TeamTreeNode<Team>[]) {
const parentsTeamIds: Team['id'][] = [];
for (const team of teamsToGetParentsFrom) {
const teamNode = teamTree.find((t) => t.team.id === team.id);
if (!teamNode) {
continue;
}
const teamAncestors = getTeamAncestors(teamNode);
parentsTeamIds.push(...teamAncestors.map((t) => t.id));
}
return uniq(parentsTeamIds);
}
/**
* Get the list of managers for a user within a specified period.
*/
public async getUserManagers(
company: Company,
userId: User['id'],
period: Pick<Period, 'endDate' | 'startDate'>,
filterByUserRoles?: UserRole[],
lookupInParentTeams: boolean = true,
) {
const { employeeRolesTeams, managerRolesTeams } = await this.getTeamsWhereUserIsAssigned(company, userId, period);
const parentsTeamsIds = lookupInParentTeams
? this.getAllParentTeamIds(
uniqBy([...employeeRolesTeams, ...managerRolesTeams], 'id'),
await this.generateTeamTree(company),
)
: [];
const teamIdsToRetrieveManagers = uniq([...employeeRolesTeams.map((t) => t.id), ...parentsTeamsIds]);
const managerTeamsAssignments = await this.teamAssignmentRepository.find({
where: {
company: { id: company.id },
teamRole: TeamRole.TEAM_MANAGER,
effectiveAsOf: Or(IsNull(), LessThanOrEqual(period.startDate)),
effectiveUntil: Or(IsNull(), MoreThanOrEqual(period.endDate)),
teamId: In(teamIdsToRetrieveManagers),
...(filterByUserRoles && !isEmpty(filterByUserRoles)
? { user: { role: In(filterByUserRoles), clearedAt: IsNull() } }
: { user: { clearedAt: IsNull() } }),
},
relations: ['user'],
});
return uniqBy(managerTeamsAssignments.map((assignment) => assignment.user).filter(Boolean), 'id').filter(
(user) => user.id !== userId,
);
}
}
|