All files / libs/assignments/quotas/core/src/lib/use-cases delete-quota-assignments.use-case.ts

94.36% Statements 134/142
71.42% Branches 10/14
100% Functions 5/5
94.36% Lines 134/142

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 1431x 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 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 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 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x  
import { ForbiddenException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { runOnTransactionCommit, Transactional } from 'typeorm-transactional';
 
import { DeleteQuotaAssignmentsRequest, QuotaAssignment } from '@amalia/assignments/quotas/types';
import { Company, VariableValue } from '@amalia/core/models';
import { dayjs } from '@amalia/ext/dayjs';
import { assert, promiseAllSettledAutoThrow, toError } from '@amalia/ext/typescript';
import { canAssignValuesToThisQuota, defineAbilityFor } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { formatPeriodName } from '@amalia/payout-definition/periods/shared';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { formatUserFullName } from '@amalia/tenants/users/types';
 
import { QuotaAssignmentEvent } from '../events/quota-assignment.event';
 
@Injectable()
export class DeleteQuotaAssignmentsUseCase {
  private readonly logger = new Logger(DeleteQuotaAssignmentsUseCase.name);
 
  public constructor(
    private readonly eventBus: EventBus,
    @InjectRepository(VariableValue)
    private readonly variableValueRepository: Repository<VariableValue>,
  ) {}
 
  @Transactional()
  public async execute({
    company,
    authenticatedContext,
    deleteQuotaAssignmentsRequest,
  }: {
    company: Company;
    authenticatedContext: AuthenticatedContext;
    deleteQuotaAssignmentsRequest: DeleteQuotaAssignmentsRequest;
  }) {
    return promiseAllSettledAutoThrow(
      deleteQuotaAssignmentsRequest.quotaAssignmentIds.map(async (quotaAssignmentId) => {
        const variableValue = await this.getAndValidateQuotaAssignment(company, quotaAssignmentId);
        this.assertCanExecute(authenticatedContext, variableValue);
 
        await this.variableValueRepository.delete({
          id: quotaAssignmentId,
          company: { id: company.id },
        });
 
        runOnTransactionCommit(() => {
          this.publishAuditLog({
            authenticatedContext,
            variableValue,
          }).catch((error) => {
            this.logger.error({
              message: 'Failed to publish QuotaAssignmentEvent',
              quotaAssignmentId,
              error: toError(error),
            });
          });
        });
      }),
      true,
    );
  }
 
  private async publishAuditLog({
    authenticatedContext,
    variableValue,
  }: {
    authenticatedContext: AuthenticatedContext;
    variableValue: VariableValue;
  }) {
    assert(variableValue.variable, new NotFoundException('The variable of the quota value does not exist'));
 
    const formattedPeriod = variableValue.startDate
      ? formatPeriodName(variableValue.variable.frequency, dayjs.unix(variableValue.startDate).toDate())
      : '';
 
    await this.eventBus.publish(
      new QuotaAssignmentEvent({
        authenticatedContext,
        object: RecordObject.QUOTA_VALUES,
        type: RecordType.DELETE,
        values: {
          what: formattedPeriod,
          oldValues: {
            period: formattedPeriod,
            value: variableValue.value,
          },
          newValues: undefined,
          target: variableValue.user
            ? { id: variableValue.user.id, name: formatUserFullName(variableValue.user) }
            : variableValue.team
              ? { id: variableValue.team.id, name: variableValue.team.name }
              : variableValue.plan
                ? { id: variableValue.plan.id, name: variableValue.plan.name }
                : { id: variableValue.variable.id, name: variableValue.variable.name },
        },
      }),
    );
  }
 
  private async getAndValidateQuotaAssignment(company: Company, quotaAssignmentId: QuotaAssignment['id']) {
    const quotaAssignment = await this.variableValueRepository.findOne({
      where: {
        id: quotaAssignmentId,
        company: { id: company.id },
      },
      relations: ['variable', 'user', 'team', 'plan'],
    });
 
    assert(quotaAssignment, new NotFoundException('The quota assignment you are trying to delete does not exist'));
    return quotaAssignment;
  }
 
  private assertCanExecute(authenticatedContext: AuthenticatedContext, variableValue: VariableValue) {
    const ability = defineAbilityFor(authenticatedContext);
 
    assert(variableValue.variable, new NotFoundException('The variable of the quota value does not exist'));
 
    assert(
      !variableValue.userId ||
        canAssignValuesToThisQuota(ability, {
          quotaId: variableValue.variable.id,
          quotaType: variableValue.variable.type,
          userId: variableValue.userId,
          teamId: variableValue.teamId,
          planId: variableValue.planId,
          date: variableValue.startDate,
        }) ||
        canAssignValuesToThisQuota(ability, {
          quotaId: variableValue.variable.id,
          quotaType: variableValue.variable.type,
          userId: variableValue.userId,
          teamId: variableValue.teamId,
          planId: variableValue.planId,
          date: variableValue.endDate,
        }),
      new ForbiddenException('You do not have the permission to unset a quota value for this user'),
    );
  }
}