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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 | 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 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 18x 18x 18x 3x 3x 18x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 6x 6x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 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 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 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x | import {
BadRequestException,
ConflictException,
HttpException,
HttpStatus,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { CommandBus, EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { pick, uniq } from 'lodash-es';
import { SetRequired } from 'type-fest';
import { Brackets, DataSource, FindOptionsSelect, In, Repository } from 'typeorm';
import { ComputePlanTemplateCommand, Plan, PlanAssignment, type Company } from '@amalia/core/models';
import { getSupportedPlanFrequencies } from '@amalia/core/types';
import { endOfDayTimestamp } from '@amalia/ext/dates';
import { isForeignKeyViolationError } from '@amalia/ext/typeorm';
import { assert, toError } from '@amalia/ext/typescript';
import { canViewThisPlan, defineAbilityFor, getViewPlansSubset, SubsetsAccessHelper } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { PeriodsService } from '@amalia/payout-definition/periods/core';
import { PlanCreatedEvent, PlanDeletedEvent, PlanUpdatedEvent } from '@amalia/payout-definition/plans/core';
import {
PlanIsHiddenQueryChoices,
PlanVisibility,
type PlanTemplateError,
} from '@amalia/payout-definition/plans/types';
import { CreateDefaultPlanDashboardUseCase } from '@amalia/reporting/plan-dashboards/core';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { PlanForecastsService } from '../forecasts/planForecasts.service';
import { type CreatePlanDto } from './dto/createPlan.dto';
/**
* Service plan.
*/
@Injectable()
export class PlansService {
private readonly logger = new Logger(PlansService.name);
public constructor(
private readonly commandBus: CommandBus,
private readonly dataSource: DataSource,
private readonly eventBus: EventBus,
@InjectRepository(Plan)
private readonly planRepository: Repository<Plan>,
private readonly planForecastService: PlanForecastsService,
private readonly periodsService: PeriodsService,
private readonly createDefaultPlanDashboardUseCase: CreateDefaultPlanDashboardUseCase,
) {}
/**
* Fin all plans attached to a company
* @param company company to search plans for
* @param searchOptions
*/
public async findAll(
company: Company,
searchOptions: {
relations?: string[];
ids?: string[];
isHiddenStatus?: PlanIsHiddenQueryChoices;
select?: FindOptionsSelect<Plan>;
archived?: boolean;
} = {},
): Promise<Plan[]> {
const { relations, ids, select, archived } = searchOptions;
const isHiddenStatus = searchOptions.isHiddenStatus || PlanIsHiddenQueryChoices.LIVE;
return this.planRepository.find({
where: {
company: { id: company.id },
...(ids && { id: In(ids) }),
...(isHiddenStatus !== PlanIsHiddenQueryChoices.BOTH && {
isHidden: isHiddenStatus === PlanIsHiddenQueryChoices.HIDDEN,
}),
...(archived !== undefined && { archived }),
},
relations,
select,
});
}
public async findViaVariableInConfiguration(company: Company, variableId: string): Promise<Plan[]> {
const plans = await this.planRepository.find({
where: {
company: { id: company.id },
},
relations: ['highlightedKpis'],
});
return plans.filter(
(p) =>
p.totalVariableId === variableId ||
(p.highlightedKpis ?? []).some(
(kpi) =>
kpi.maximumVariableId === variableId ||
kpi.minimumVariableId === variableId ||
kpi.variableId === variableId,
),
);
}
/**
* Find all plans where the user is assigned
* @param company
* @param authenticatedContext
* @param userIds - Filter teams with a list of userIds that should be assigned.
* @param periodId
*/
public async findAllWhereUserAuthorized({
company,
authenticatedContext,
userIds,
periodId,
search,
planStatus,
showArchived,
}: {
company: Company;
authenticatedContext: AuthenticatedContext;
userIds?: string[] | null;
periodId?: string | null;
search?: string | null;
planStatus?: PlanVisibility | null;
showArchived?: boolean;
}): Promise<SetRequired<Plan, 'planAssignements'>[]> {
const queryBuilder = this.dataSource.manager.createQueryBuilder(Plan, 'plan');
queryBuilder.where('plan.company = :companyId', { companyId: company.id });
queryBuilder.leftJoin('plan.planAssignements', 'planAssignment');
queryBuilder.leftJoin('planAssignment.user', 'planAssignmentUser');
SubsetsAccessHelper.addConditionForQueryBuilder(
authenticatedContext,
getViewPlansSubset,
'planAssignment.user',
queryBuilder,
);
if (userIds) {
if (userIds.length === 0) {
return [];
}
queryBuilder.andWhere('planAssignment.userId IN (:...userIds)', {
userIds,
});
}
// we need to search for plan name or users assigned to the plan
if (search) {
queryBuilder.andWhere(
new Brackets((qb) =>
qb.where(
'plan.name ILIKE :search OR planAssignmentUser.lastName ILIKE :search OR planAssignmentUser.firstName ILIKE :search',
{ search: `%${search}%` },
),
),
);
}
if (planStatus) {
queryBuilder.andWhere('plan.isHidden = :isHidden', {
isHidden: planStatus === PlanVisibility.HIDDEN,
});
}
if (showArchived === false) {
queryBuilder.andWhere('plan.archived = :archived', { archived: false });
}
if (periodId) {
const period = periodId ? await this.periodsService.findOne(company, periodId) : null;
if (period) {
// Period StartDate <= EffectiveUntil + Period EndDate >= EffectiveAsOf
const { startDate, endDate } = period;
queryBuilder.andWhere('COALESCE(planAssignment.effectiveAsOf, :endDate) <= :endDate', {
endDate,
});
queryBuilder.andWhere('COALESCE(planAssignment.effectiveUntil, :startDate) >= :startDate', {
startDate,
});
}
}
queryBuilder.select([
'plan.id',
'plan.name',
'plan.company',
'plan.archived',
'plan.categoriesV2',
'plan.forecastId',
'plan.frequency',
'plan.indexedPlanTemplate',
'plan.indexedWeight',
'plan.isForecasted',
'plan.isHidden',
'plan.linkToPlanDocumentation',
'plan.manualWeight',
'plan.totalVariableId',
'plan.useVariableInsteadOfTotal',
'plan.workflowId',
'planAssignment',
]);
queryBuilder.orderBy('name');
const plans = (await queryBuilder.getMany()) as SetRequired<Plan, 'planAssignements'>[];
const ability = defineAbilityFor(authenticatedContext);
return plans.filter((plan) => canViewThisPlan(ability, plan));
}
/**
* Find plan by id.
* @param company
* @param id of the plan
* @param relations
* @param withPlanTemplate
* @throws {NotFoundException}
*/
public async findById(company: Company, id: string, relations?: string[], withPlanTemplate?: boolean): Promise<Plan> {
const select = [
'id',
'name',
'frequency',
'company',
'workflowId',
'linkToPlanDocumentation',
'useVariableInsteadOfTotal',
'totalVariableId',
'indexedWeight',
'indexedPlanTemplate',
'iolSchemeId',
'manualWeight',
'maxRecursionLevel',
'planTemplateError',
'calculationBatchSize',
'calculationMaxParallel',
...(withPlanTemplate ? ['planTemplate'] : []),
'categoriesV2',
'archived',
'forecastId',
'isHidden',
'isForecasted',
'calculateBothStatements',
'isSimulationEnabled',
'isSimulationAddRecordEnabled',
'metricsFromPlanIds',
'nbForwardRollingPeriods',
] as (keyof Plan)[];
const plan = await this.planRepository.findOne({
select,
where: {
id,
company: { id: company.id },
},
relations: ['company', ...(relations ?? [])],
});
assert(plan, new NotFoundException(`Plan with id ${id} was not found`));
return plan;
}
/**
* Search for a keyword in company's plan templates
* @param company
* @param keyword
* @param relations
*/
public async searchForKeyword(company: Company, keyword: string, relations?: string[]): Promise<Plan[]> {
const queryBuilder = this.planRepository.createQueryBuilder('plan');
queryBuilder.where('plan.companyId = :companyId', {
companyId: company.id,
});
queryBuilder.andWhere('plan."indexedPlanTemplate"::text ilike :search', {
search: `%${keyword}%`,
});
if ((relations ?? []).includes('plan_assignements')) {
queryBuilder.leftJoinAndSelect('plan.planAssignements', 'planAssignements');
}
return queryBuilder.getMany();
}
/**
* Create new plan.
* @param company company of the new plan
* @param authenticatedContext
* @param plan plan to create
* @throws {HttpException}
*/
public async create(
company: Company,
authenticatedContext: AuthenticatedContext,
plan: CreatePlanDto,
): Promise<Plan> {
const planNameAlreadyExist = await this.planRepository.findOne({
where: {
company: { id: company.id },
name: plan.name,
},
});
if (planNameAlreadyExist) {
throw new ConflictException('plan with the same name already exist');
}
const planToCreate: Plan = new Plan();
planToCreate.company = company;
planToCreate.name = plan.name;
planToCreate.metricsFromPlanIds = [];
if (plan.frequency && !getSupportedPlanFrequencies(company).includes(plan.frequency)) {
throw new BadRequestException(
`${plan.frequency} plans are not allowed for ${company.statementFrequency} companies.`,
);
}
planToCreate.frequency = plan.frequency || company.statementFrequency;
let createdPlan: Plan;
try {
createdPlan = await this.planRepository.save(planToCreate);
await this.createDefaultPlanDashboardUseCase.execute({
planId: createdPlan.id,
companyId: company.id,
planFrequency: createdPlan.frequency,
});
await this.eventBus.publish(
new PlanCreatedEvent({
authenticatedContext,
object: RecordObject.PLAN,
type: RecordType.CREATE,
values: {
target: {
id: createdPlan.id,
name: createdPlan.name,
},
newValues: {
name: createdPlan.name,
},
},
}),
);
} catch (err) {
const error = toError(err);
this.logger.error({ message: 'Error on create Plan', error, company: pick(company, ['id', 'name']) });
throw new InternalServerErrorException('Error during Plan creation, please contact admin');
}
await this.commandBus.execute(new ComputePlanTemplateCommand(company.id, [createdPlan.id]));
return createdPlan;
}
/**
* Delete plan.
* @param company company of the plan to delete
* @param planId id of the plan to delete
* @param authenticatedContext
* @throws {HttpException}
*/
public async delete(company: Company, planId: string, authenticatedContext: AuthenticatedContext): Promise<void> {
const planFound = await this.findById(company, planId);
try {
await this.planRepository.delete({ id: planId });
await this.planForecastService.delete(company, planFound.forecastId);
await this.eventBus.publish(
new PlanDeletedEvent({
authenticatedContext,
object: RecordObject.PLAN,
type: RecordType.DELETE,
values: {
target: pick(planFound, 'id', 'name'),
oldValues: pick(planFound, 'id', 'name'),
},
}),
);
} catch (err) {
if (isForeignKeyViolationError(err)) {
throw new ConflictException('Cannot delete a plan that is used in a statement');
} else {
const error = toError(err);
this.logger.error({ message: 'Error on delete plan', error, company: pick(company, ['id', 'name']) });
throw new HttpException('Error during plan deletion, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
public async savePlanTemplateErrorInPlan(company: Company, plan: Plan, planTemplateError: PlanTemplateError) {
try {
await this.dataSource.getRepository<Plan>(Plan).save({
...plan,
planTemplateError: {
...planTemplateError,
},
});
} catch (err) {
const error = toError(err);
this.logger.error({
message: 'Error on update Plan (save plan template error)',
error,
company: pick(company, ['id', 'name']),
});
throw new InternalServerErrorException('Error during Plan update, please contact admin');
}
}
public async getIndexedPlanTemplates(
company: Company,
planIds: string[],
): Promise<Pick<Plan, 'id' | 'indexedPlanTemplate'>[]> {
return this.planRepository.find({
where: { company: { id: company.id }, id: In(planIds) },
select: ['id', 'indexedPlanTemplate'],
});
}
public async getIdsOfItemsUsedInPlanTemplates(company: Company, planIds: string[]): Promise<string[]> {
const indexedPlanTemplates = await this.getIndexedPlanTemplates(company, planIds);
return uniq(indexedPlanTemplates.flatMap((p) => p.indexedPlanTemplate?.dependencyIds).filter(Boolean));
}
public async archivePlan(
company: Company,
planId: string,
authenticatedContext: AuthenticatedContext,
): Promise<Plan> {
const plan = await this.findById(company, planId, [
'badgeConfigurations',
'planRules',
'planRules.rule',
'planAssignements',
]);
if (plan.archived) {
return plan;
}
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
assert(plan.planAssignements, 'Relation planAssignements not populated');
const assignments = plan.planAssignements;
const endOfToday = endOfDayTimestamp(new Date());
const ongoingAssignments = assignments.filter((pa) => !pa.effectiveUntil || pa.effectiveUntil > endOfToday);
try {
await queryRunner.connection.getRepository<Plan>(Plan).save({ ...plan, archived: true });
// Edit the ongoing assignments to end them at the end of today
await Promise.all(
ongoingAssignments.map((pa) =>
queryRunner.connection
.getRepository<PlanAssignment>(PlanAssignment)
.save({ ...pa, effectiveUntil: endOfToday }),
),
);
await queryRunner.commitTransaction();
await this.eventBus.publish(
new PlanUpdatedEvent({
authenticatedContext,
object: RecordObject.PLAN,
type: RecordType.EDIT,
values: {
target: {
id: plan.id,
name: plan.name,
},
oldValues: {
archived: plan.archived,
},
newValues: {
archived: true,
},
},
}),
);
return await this.findById(company, planId, [
'badgeConfigurations',
'planRules',
'planRules.rule',
'planAssignements',
]);
} catch (err) {
await queryRunner.rollbackTransaction();
if (err instanceof NotFoundException) {
throw err;
}
const error = toError(err);
this.logger.error({ message: 'Error on archive Plan', error, company: pick(company, ['id', 'name']) });
throw new InternalServerErrorException('Error during Plan archive, please contact admin');
} finally {
await queryRunner.release();
}
}
public async unarchivePlan(
company: Company,
planId: string,
authenticatedContext: AuthenticatedContext,
): Promise<Plan> {
const plan = await this.findById(company, planId, [
'badgeConfigurations',
'planRules',
'planRules.rule',
'planAssignements',
]);
if (!plan.archived) {
return plan;
}
try {
await this.planRepository.save({ ...plan, archived: false });
await this.eventBus.publish(
new PlanUpdatedEvent({
authenticatedContext,
object: RecordObject.PLAN,
type: RecordType.EDIT,
values: {
target: {
id: plan.id,
name: plan.name,
},
oldValues: {
archived: plan.archived,
},
newValues: {
archived: false,
},
},
}),
);
await this.commandBus.execute(new ComputePlanTemplateCommand(company.id, [planId]));
return await this.findById(company, planId, [
'badgeConfigurations',
'planRules',
'planRules.rule',
'planAssignements',
]);
} catch (err) {
if (err instanceof NotFoundException) {
throw err;
}
const error = toError(err);
this.logger.error({ message: 'Error on archive Plan', error, company: pick(company, ['id', 'name']) });
throw new InternalServerErrorException('Error during Plan archive, please contact admin');
}
}
public async getPlanIdsWhereTokenIsUsed(company: Company, tokenId: string) {
const planList = await this.findAll(company, {
select: { id: true, indexedPlanTemplate: { dependencyIds: true } },
isHiddenStatus: PlanIsHiddenQueryChoices.BOTH,
});
return planList
.filter((plan) => (plan.indexedPlanTemplate?.dependencyIds ?? []).includes(tokenId))
.map((plan) => plan.id);
}
}
|