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 | 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 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 1x | import { ForbiddenException, Logger, UnprocessableEntityException } from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { SetRequired } from 'type-fest';
import { Repository } from 'typeorm';
import { runOnTransactionCommit, Transactional } from 'typeorm-transactional';
import { AssignmentDates } from '@amalia/assignments/common/shared';
import { Company, PlanAssignment, Team, TeamAssignment, User } from '@amalia/core/models';
import { formatUnixTimestamp, isDateRangeValid, isValidDateBoundary } from '@amalia/ext/dates';
import { assert, promiseAllSettledAutoThrow, toError } from '@amalia/ext/typescript';
import { canModifyPlanAssignments, defineAbilityFor } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { UpdatePlanAssignmentsRequest } from '@amalia/payout-definition/plans/types';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { formatUserFullName } from '@amalia/tenants/users/types';
import { PlanAssignmentCreatedEvent } from '../../legacy/events/plan-assignment-created.event';
export class UpdatePlanAssignmentsUseCase {
private readonly logger = new Logger(UpdatePlanAssignmentsUseCase.name);
public constructor(
private readonly eventBus: EventBus,
@InjectRepository(PlanAssignment) private readonly planAssignmentsRepository: Repository<PlanAssignment>,
@InjectRepository(TeamAssignment) private readonly teamAssignmentsRepository: Repository<TeamAssignment>,
) {}
@Transactional()
public async execute({
authenticatedContext,
updatePlanAssignmentsRequest,
}: {
authenticatedContext: AuthenticatedContext;
updatePlanAssignmentsRequest: UpdatePlanAssignmentsRequest;
}) {
this.assertCanExecute(authenticatedContext);
return promiseAllSettledAutoThrow(
updatePlanAssignmentsRequest.planAssignments.map(async (updatePlanAssignmentRequest) => {
// Make sure that the plan assignment exists.
const planAssignment = await this.getAndValidatePlanAssignment(
authenticatedContext.user.company,
updatePlanAssignmentRequest.id,
);
// Make sure that the user is part of the main team if it is defined.
if (updatePlanAssignmentRequest.mainTeamId) {
await this.assertUserIsInTeam(
authenticatedContext.user.company,
updatePlanAssignmentRequest.mainTeamId,
planAssignment.userId,
);
}
// To make sure that the range is valid, we need to replace the dates with the current ones if they are not defined.
const assignmentDates = {
effectiveAsOf:
updatePlanAssignmentRequest.effectiveAsOf === undefined
? planAssignment.effectiveAsOf
: updatePlanAssignmentRequest.effectiveAsOf,
effectiveUntil:
updatePlanAssignmentRequest.effectiveUntil === undefined
? planAssignment.effectiveUntil
: updatePlanAssignmentRequest.effectiveUntil,
};
this.assertDateRangeIsValid(assignmentDates);
const updatedPlanAssignment = await this.planAssignmentsRepository.save({
id: planAssignment.id,
mainTeamId:
updatePlanAssignmentRequest.mainTeamId === undefined
? planAssignment.mainTeamId
: updatePlanAssignmentRequest.mainTeamId,
...assignmentDates,
});
runOnTransactionCommit(() => {
this.publishLog({
authenticatedContext,
planAssignment,
updatedPlanAssignment,
}).catch((err) => {
this.logger.error({
message: 'Failed to publish PlanAssignmentCreatedEvent',
error: toError(err),
company: { id: authenticatedContext.user.company.id, name: authenticatedContext.user.company.name },
planAssignment,
updatedPlanAssignment,
});
});
});
return updatedPlanAssignment;
}),
true,
);
}
private async publishLog({
authenticatedContext,
planAssignment,
updatedPlanAssignment,
}: {
authenticatedContext: AuthenticatedContext;
planAssignment: SetRequired<PlanAssignment, 'plan' | 'user'>;
updatedPlanAssignment: Pick<PlanAssignment, 'effectiveAsOf' | 'effectiveUntil' | 'mainTeamId'>;
}) {
await this.eventBus.publish(
new PlanAssignmentCreatedEvent(
authenticatedContext.user.company,
authenticatedContext.user,
planAssignment.user,
planAssignment.plan,
updatedPlanAssignment.effectiveAsOf ? formatUnixTimestamp(updatedPlanAssignment.effectiveAsOf) : null,
updatedPlanAssignment.effectiveUntil ? formatUnixTimestamp(updatedPlanAssignment.effectiveUntil) : null,
{
authenticatedContext,
object: RecordObject.PLAN_ASSIGNMENT,
type: RecordType.EDIT,
values: {
target: {
id: planAssignment.user.id,
name: formatUserFullName(planAssignment.user),
},
oldValues: {
plan: planAssignment.plan.name,
user: formatUserFullName(planAssignment.user),
startDate: planAssignment.effectiveAsOf ? formatUnixTimestamp(planAssignment.effectiveAsOf) : null,
endDate: planAssignment.effectiveAsOf ? formatUnixTimestamp(planAssignment.effectiveAsOf) : null,
mainTeamId: planAssignment.mainTeamId,
},
newValues: {
plan: planAssignment.plan.name,
user: formatUserFullName(planAssignment.user),
startDate: updatedPlanAssignment.effectiveAsOf
? formatUnixTimestamp(updatedPlanAssignment.effectiveAsOf)
: null,
endDate: updatedPlanAssignment.effectiveUntil
? formatUnixTimestamp(updatedPlanAssignment.effectiveUntil)
: null,
mainTeamId: updatedPlanAssignment.mainTeamId,
},
},
},
),
);
}
private async assertUserIsInTeam(company: Company, teamId: Team['id'], userId: User['id']) {
const teamAssignmentExists = await this.teamAssignmentsRepository.exists({
where: {
company: { id: company.id },
teamId,
userId,
},
});
assert(teamAssignmentExists, new UnprocessableEntityException(`User ${userId} is not part of team ${teamId}`));
}
private async getAndValidatePlanAssignment(
company: Company,
planAssignmentId: PlanAssignment['id'],
): Promise<SetRequired<PlanAssignment, 'plan' | 'user'>> {
const planAssignment = await this.planAssignmentsRepository.findOne({
where: {
id: planAssignmentId,
company: { id: company.id },
},
relations: ['plan', 'user'],
});
assert(planAssignment, new UnprocessableEntityException('Plan assignment not found'));
return planAssignment;
}
private assertDateRangeIsValid({ effectiveAsOf, effectiveUntil }: AssignmentDates) {
assert(
isDateRangeValid(effectiveAsOf, effectiveUntil),
new UnprocessableEntityException('Start date should be before end date'),
);
assert(
effectiveAsOf === null || isValidDateBoundary(effectiveAsOf, 'START'),
new UnprocessableEntityException('If defined, start date must be a timestamp at the beginning of a day in UTC'),
);
assert(
effectiveUntil === null || isValidDateBoundary(effectiveUntil, 'END'),
new UnprocessableEntityException('If defined, end date must be a timestamp at the end of a day in UTC'),
);
}
private assertCanExecute(authenticatedContext: AuthenticatedContext) {
assert(
canModifyPlanAssignments(defineAbilityFor(authenticatedContext)),
new ForbiddenException('You do not have the permission to modify plan assignments'),
);
}
}
|