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 | 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 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x | import { ForbiddenException, Logger, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { runOnTransactionCommit, Transactional } from 'typeorm-transactional';
import { AssignmentDates } from '@amalia/assignments/common/shared';
import { Company, Plan, 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 { IntlService } from '@amalia/kernel/intl/module';
import { UpsertPlanAssignmentsRequest } 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 UpsertPlanAssignmentsUseCase {
private readonly logger = new Logger(UpsertPlanAssignmentsUseCase.name);
public constructor(
private readonly intl: IntlService,
private readonly eventBus: EventBus,
@InjectRepository(Plan) private readonly plansRepository: Repository<Plan>,
@InjectRepository(PlanAssignment) private readonly planAssignmentsRepository: Repository<PlanAssignment>,
@InjectRepository(TeamAssignment) private readonly teamAssignmentsRepository: Repository<TeamAssignment>,
@InjectRepository(User) private readonly usersRepository: Repository<User>,
) {}
@Transactional()
public async execute({
authenticatedContext,
upsertPlanAssignmentsRequest,
}: {
authenticatedContext: AuthenticatedContext;
upsertPlanAssignmentsRequest: UpsertPlanAssignmentsRequest;
}): Promise<PlanAssignment[]> {
this.assertCanExecute(authenticatedContext);
return promiseAllSettledAutoThrow(
upsertPlanAssignmentsRequest.planAssignments.map(async (upsertPlanAssignmentRequest) => {
// Make sure that start date is before end date, and that the timestamps are valid start and end of UTC days.
this.assertDateRangeIsValid({
effectiveAsOf: upsertPlanAssignmentRequest.effectiveAsOf,
effectiveUntil: upsertPlanAssignmentRequest.effectiveUntil,
});
const [plan, user, existingPlanAssignment] = await Promise.all([
// Make sure than user and plan exist.
this.getPlanOrThrow(authenticatedContext.user.company, upsertPlanAssignmentRequest.planId),
this.getUserOrThrow(authenticatedContext.user.company, upsertPlanAssignmentRequest.userId),
// Make sure that user is not already assigned to the plan.
this.getPlanAssignmentIfExists(
authenticatedContext.user.company,
upsertPlanAssignmentRequest.userId,
upsertPlanAssignmentRequest.planId,
),
// If a main team is defined, make sure that the user is part of it.
upsertPlanAssignmentRequest.mainTeamId &&
this.assertUserIsInTeam(
authenticatedContext.user.company,
upsertPlanAssignmentRequest.mainTeamId,
upsertPlanAssignmentRequest.userId,
),
]);
// Create the plan assignment and publish a log.
const planAssignment = await this.planAssignmentsRepository.save({
id: existingPlanAssignment?.id,
company: { id: authenticatedContext.user.company.id },
planId: plan.id,
userId: user.id,
effectiveAsOf: upsertPlanAssignmentRequest.effectiveAsOf,
effectiveUntil: upsertPlanAssignmentRequest.effectiveUntil,
mainTeamId: upsertPlanAssignmentRequest.mainTeamId,
});
runOnTransactionCommit(() => {
this.publishLog({
authenticatedContext,
user,
plan,
previousPlanAssignment: existingPlanAssignment,
planAssignment,
}).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,
});
});
});
return planAssignment;
}),
true,
);
}
private async publishLog({
authenticatedContext,
user,
plan,
previousPlanAssignment,
planAssignment,
}: {
authenticatedContext: AuthenticatedContext;
user: User;
plan: Plan;
previousPlanAssignment: Pick<PlanAssignment, 'effectiveAsOf' | 'effectiveUntil' | 'mainTeamId'> | null;
planAssignment: Pick<PlanAssignment, 'effectiveAsOf' | 'effectiveUntil' | 'mainTeamId'>;
}) {
await this.eventBus.publish(
new PlanAssignmentCreatedEvent(
authenticatedContext.user.company,
authenticatedContext.user,
user,
plan,
planAssignment.effectiveAsOf ? formatUnixTimestamp(planAssignment.effectiveAsOf) : null,
planAssignment.effectiveAsOf ? formatUnixTimestamp(planAssignment.effectiveAsOf) : null,
{
authenticatedContext,
object: RecordObject.PLAN_ASSIGNMENT,
type: previousPlanAssignment ? RecordType.EDIT : RecordType.CREATE,
values: {
target: {
id: user.id,
name: formatUserFullName(user),
},
oldValues: previousPlanAssignment
? {
plan: plan.name,
user: formatUserFullName(user),
startDate: previousPlanAssignment.effectiveAsOf
? formatUnixTimestamp(previousPlanAssignment.effectiveAsOf)
: null,
endDate: previousPlanAssignment.effectiveUntil
? formatUnixTimestamp(previousPlanAssignment.effectiveUntil)
: null,
mainTeamId: previousPlanAssignment.mainTeamId,
}
: undefined,
newValues: {
plan: plan.name,
user: formatUserFullName(user),
startDate: planAssignment.effectiveAsOf ? formatUnixTimestamp(planAssignment.effectiveAsOf) : null,
endDate: planAssignment.effectiveAsOf ? formatUnixTimestamp(planAssignment.effectiveAsOf) : null,
mainTeamId: planAssignment.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(
this.intl.formatMessage(
{ defaultMessage: 'User {userId} is not part of team {teamId}', id: '44b+Mp' },
{ userId, teamId },
),
),
);
}
private async getPlanOrThrow(company: Company, planId: Plan['id']) {
const plan = await this.plansRepository.findOne({
where: {
company: { id: company.id },
id: planId,
},
});
assert(
plan,
new NotFoundException(
this.intl.formatMessage({ defaultMessage: 'Plan {planId} not found', id: '+wRe2p' }, { planId }),
),
);
return plan;
}
private async getUserOrThrow(company: Company, userId: User['id']) {
const user = await this.usersRepository.findOne({
where: {
company: { id: company.id },
id: userId,
},
});
assert(
user,
new NotFoundException(
this.intl.formatMessage({ defaultMessage: 'User {userId} not found', id: 'v0T5a9' }, { userId }),
),
);
assert(
!user.clearedAt,
new UnprocessableEntityException(
this.intl.formatMessage({ defaultMessage: 'User {userId} is deactivated', id: 'Ot8o3w' }, { userId }),
),
);
return user;
}
private async getPlanAssignmentIfExists(company: Company, userId: User['id'], planId: Plan['id']) {
return this.planAssignmentsRepository.findOne({
where: {
company: { id: company.id },
userId,
planId,
},
});
}
private assertDateRangeIsValid({ effectiveAsOf, effectiveUntil }: AssignmentDates) {
assert(
isDateRangeValid(effectiveAsOf, effectiveUntil),
new UnprocessableEntityException(
this.intl.formatMessage({ defaultMessage: 'Start date should be before end date', id: '+VsvsR' }),
),
);
assert(
effectiveAsOf === null || isValidDateBoundary(effectiveAsOf, 'START'),
new UnprocessableEntityException(
this.intl.formatMessage({
defaultMessage: 'If defined, start date must be a timestamp at the beginning of a day in UTC',
id: '7cXlIt',
}),
),
);
assert(
effectiveUntil === null || isValidDateBoundary(effectiveUntil, 'END'),
new UnprocessableEntityException(
this.intl.formatMessage({
defaultMessage: 'If defined, end date must be a timestamp at the end of a day in UTC',
id: 'quxFDC',
}),
),
);
}
private assertCanExecute(authenticatedContext: AuthenticatedContext) {
assert(
canModifyPlanAssignments(defineAbilityFor(authenticatedContext)),
new ForbiddenException(
this.intl.formatMessage({
defaultMessage: 'You do not have the permission to assign users to plans',
id: '2flHsA',
}),
),
);
}
}
|