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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 13x 13x 13x 13x 13x 9x 9x 9x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 13x 13x 12x 12x 12x 12x 12x 13x 13x 4x 13x 3x 3x 3x 3x 3x 3x 3x 13x 9x 9x 9x 9x 9x 9x 9x 9x 10x 10x 9x 9x 9x 13x 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 1x 1x 3x 2x 2x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 3x 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 1x 1x 12x 12x 12x 12x 12x 12x 12x 2x 2x 2x 2x 2x 12x 12x 12x 12x 2x 2x 2x 2x 2x 12x 12x 12x 1x 1x 12x 12x 12x 12x 12x 4x 4x 8x 8x 8x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x | import { BadRequestException, ForbiddenException, Injectable, UnprocessableEntityException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { pick } from 'lodash-es';
import { Repository } from 'typeorm';
import { AssignmentDates } from '@amalia/assignments/common/shared';
import { Company, Plan, PlanAssignment, Team, User } from '@amalia/core/models';
import { convertDateToUtcTimestamp, isDateRangeValid } from '@amalia/ext/dates';
import { assert, 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 {
CsvPlanAssignmentRow,
PlanAssignmentInDryRunResponse,
UpsertPlanAssignmentsDryRunResponse,
ValidatePlanAssignmentsCsvRequest,
} from '@amalia/payout-definition/plans/types';
@Injectable()
export class ValidatePlanAssignmentsCsvUseCase {
public constructor(
private readonly intl: IntlService,
@InjectRepository(Plan) private readonly plansRepository: Repository<Plan>,
@InjectRepository(PlanAssignment) private readonly planAssignmentsRepository: Repository<PlanAssignment>,
@InjectRepository(Team) private readonly teamsRepository: Repository<Team>,
@InjectRepository(User) private readonly usersRepository: Repository<User>,
) {}
public async execute({
authenticatedContext,
request: { csvRows },
}: {
authenticatedContext: AuthenticatedContext;
request: ValidatePlanAssignmentsCsvRequest;
}): Promise<UpsertPlanAssignmentsDryRunResponse> {
this.assertCanExecute(authenticatedContext);
const dryRunResponse: UpsertPlanAssignmentsDryRunResponse = {
errors: [],
insertedPlanAssignments: [],
updatedPlanAssignments: [],
unchangedPlanAssignments: [],
};
const csvRowsSanitized = csvRows.map((row) => ({
userEmail: row.userEmail?.trim(),
planName: row.planName?.trim(),
primaryTeam: row.primaryTeam?.trim(),
assignmentStartDate: row.assignmentStartDate?.trim(),
assignmentEndDate: row.assignmentEndDate?.trim(),
}));
for (const [index, row] of csvRowsSanitized.entries()) {
// Ignore empty rows (we can't use .filter here because we need the index).
if (!row.userEmail && !row.planName && !row.primaryTeam && !row.assignmentEndDate && !row.assignmentStartDate) {
continue;
}
// In case of duplicate row, we abort the validation.
if (
index !==
csvRowsSanitized.findIndex(
({ userEmail, planName }) => userEmail === row.userEmail && planName === row.planName,
)
) {
dryRunResponse.errors.push({
rowIndex: index,
error: this.intl.formatMessage(
{ defaultMessage: 'Duplicate row for user {userEmail} on plan {planName}', id: 'JnefgU' },
{ userEmail: row.userEmail, planName: row.planName },
),
});
continue;
}
// We want to return all validation errors to the user so we try everything,
// and then we either push the row in the dry run response or we push all validation errors from failed promises.
const [dateRangePromise, userPromise, planPromise, mainTeamPromise] = await Promise.allSettled([
Promise.resolve().then(() => this.getDateRangeOrThrow(row)),
this.getUserOrThrow(authenticatedContext.user.company, row.userEmail),
this.getPlanOrThrow(authenticatedContext.user.company, row.planName),
row.primaryTeam ? this.getTeamOrThrow(authenticatedContext.user.company, row.primaryTeam) : null,
]);
// If everything was loaded successfully, push the row in the dry run response.
// Otherwise, push all validation errors in the dry run response.
if (
dateRangePromise.status === 'fulfilled' &&
userPromise.status === 'fulfilled' &&
planPromise.status === 'fulfilled' &&
mainTeamPromise.status === 'fulfilled'
) {
await this.pushRowInDryRunResponse(dryRunResponse, {
company: authenticatedContext.user.company,
plan: planPromise.value,
user: userPromise.value,
mainTeam: mainTeamPromise.value,
assignmentDates: dateRangePromise.value,
});
} else {
dryRunResponse.errors.push(
...[dateRangePromise, userPromise, planPromise, mainTeamPromise]
.filter((result) => result.status === 'rejected')
.flatMap(({ reason }) =>
// If a promise rejected multiple errors it's wrapped in a AggregateError so we unwind nested errors here.
reason instanceof AggregateError ? reason.errors.map((error) => toError(error)) : [toError(reason)],
)
.map((error) => ({
rowIndex: index,
error: error.message,
})),
);
}
}
return dryRunResponse;
}
/** Push the plan assignment in dry run response based on the state of an existing plan agreement for the same user / plan. */
private async pushRowInDryRunResponse(
dryRunResponse: UpsertPlanAssignmentsDryRunResponse,
{
company,
plan,
user,
mainTeam,
assignmentDates: { effectiveAsOf, effectiveUntil },
}: {
company: Company;
plan: Plan;
user: User;
mainTeam: Team | null;
assignmentDates: AssignmentDates;
},
) {
const existingPlanAssignment = await this.findPlanAssignment(company, plan.id, user.id);
const mappedExtractedPlanAssignment = ValidatePlanAssignmentsCsvUseCase.mapPlanAssignmentToResponse(
{ effectiveAsOf, effectiveUntil },
plan,
user,
mainTeam,
);
if (!existingPlanAssignment) {
// No existing assignment, so this is a new assignment.
dryRunResponse.insertedPlanAssignments.push(mappedExtractedPlanAssignment);
} else if (
existingPlanAssignment.effectiveAsOf === effectiveAsOf &&
existingPlanAssignment.effectiveUntil === effectiveUntil &&
existingPlanAssignment.mainTeamId === (mainTeam?.id ?? null)
) {
// Existing assignment is unchanged.
dryRunResponse.unchangedPlanAssignments.push(mappedExtractedPlanAssignment);
} else {
// Existing assignment is updated.
dryRunResponse.updatedPlanAssignments.push({
previous: ValidatePlanAssignmentsCsvUseCase.mapPlanAssignmentToResponse(
existingPlanAssignment,
plan,
user,
mainTeam,
),
next: mappedExtractedPlanAssignment,
});
}
}
private static mapPlanAssignmentToResponse(
planAssignment: Pick<PlanAssignment, 'effectiveAsOf' | 'effectiveUntil'>,
plan: Plan,
user: User,
team: Team | null,
): PlanAssignmentInDryRunResponse {
return {
...pick(planAssignment, 'effectiveAsOf', 'effectiveUntil'),
plan: pick(plan, 'id', 'name'),
user: pick(user, 'id', 'firstName', 'lastName', 'pictureURL'),
mainTeam: team ? pick(team, 'id', 'name') : null,
};
}
private async getUserOrThrow(company: Company, userEmail: User['email'] | null | undefined) {
assert(
userEmail,
new BadRequestException(this.intl.formatMessage({ defaultMessage: 'User email is required', id: 'BiIwcS' })),
);
const user = await this.usersRepository.findOne({
where: {
company: { id: company.id },
email: userEmail,
},
});
assert(
user,
new Error(
this.intl.formatMessage(
{ defaultMessage: 'User with email {userEmail} not found', id: '2N/SZQ' },
{ userEmail },
),
),
);
return user;
}
private async getPlanOrThrow(company: Company, planName: Plan['name'] | null | undefined) {
assert(
planName,
new BadRequestException(this.intl.formatMessage({ defaultMessage: 'Plan name is required', id: 'RUj/kG' })),
);
const plan = await this.plansRepository.findOne({
where: {
company: { id: company.id },
name: planName,
},
});
assert(
plan,
new Error(
this.intl.formatMessage({ defaultMessage: 'Plan with name {planName} not found', id: 'Mq1Kk8' }, { planName }),
),
);
return plan;
}
private async getTeamOrThrow(company: Company, teamName: Team['name']) {
const team = await this.teamsRepository.findOne({
where: {
company: { id: company.id },
name: teamName,
},
});
assert(
team,
new Error(
this.intl.formatMessage({ defaultMessage: 'Team with name {teamName} not found', id: '2Ot+sO' }, { teamName }),
),
);
return team;
}
private async findPlanAssignment(company: Company, planId: Plan['id'], userId: User['id']) {
return this.planAssignmentsRepository.findOne({
where: {
company: { id: company.id },
userId,
planId,
},
});
}
private getDateRangeOrThrow({ assignmentStartDate, assignmentEndDate }: CsvPlanAssignmentRow) {
const effectiveAsOf = convertDateToUtcTimestamp(assignmentStartDate ?? null, 'start');
const effectiveUntil = convertDateToUtcTimestamp(assignmentEndDate ?? null, 'end');
// There can be multiple validation errors so we can't use assert here.
const errors = [
assignmentStartDate &&
!effectiveAsOf &&
new BadRequestException(
this.intl.formatMessage({
defaultMessage: 'Assignment start date should be in YYYY-MM-DD format',
id: '4VunrF',
}),
),
assignmentEndDate &&
!effectiveUntil &&
new BadRequestException(
this.intl.formatMessage({
defaultMessage: 'Assignment end date should be in YYYY-MM-DD format',
id: '8sj/dm',
}),
),
!isDateRangeValid(effectiveAsOf, effectiveUntil) &&
new UnprocessableEntityException(
this.intl.formatMessage({ defaultMessage: 'Start date should be before end date', id: '+VsvsR' }),
),
].filter(Boolean);
// If there were errors, wrap in a AggregateError so the execute method can unwind them.
if (errors.length > 0) {
throw new AggregateError(errors, 'Invalid assignment dates');
}
return { effectiveAsOf, effectiveUntil };
}
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',
}),
),
);
}
}
|