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

97.85% Statements 319/326
80.7% Branches 46/57
100% Functions 12/12
97.85% Lines 319/326

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 3271x 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 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 18x 18x 18x 18x 18x 18x 18x 18x 18x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 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 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 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 1x 4x 4x 4x 4x 4x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 1x 10x 10x 10x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 1x 1x 17x 17x 17x 17x 17x 17x 10x 10x 8x 8x 8x 17x 17x 3x 3x 3x 1x 1x 17x 17x 3x 3x 3x 3x 1x 17x 17x 1x 17x 17x 1x 1x 10x 10x 10x 10x     10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 11x 11x 11x 11x 11x 11x 11x 18x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 1x  
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, Repository } from 'typeorm';
import { runOnTransactionCommit, Transactional } from 'typeorm-transactional';
 
import { VariableType } from '@amalia/amalia-lang/tokens/types';
import { UpsertQuotaAssignmentRequest, UpsertQuotasAssignmentsRequest } from '@amalia/assignments/quotas/types';
import { Company, Plan, Team, User, Variable, VariableValue } from '@amalia/core/models';
import { FormatsEnum } from '@amalia/data-capture/fields/types';
import { isValidDateBoundary } from '@amalia/ext/dates';
import { dayjs } from '@amalia/ext/dayjs';
import { assert, 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 { PeriodFrequencyEnum } from '@amalia/payout-definition/periods/types';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { AppUsersRepository } from '@amalia/tenants/users/core';
import { formatUserFullName } from '@amalia/tenants/users/types';
 
import { QuotaAssignmentEvent } from '../events/quota-assignment.event';
 
@Injectable()
export class UpsertQuotasAssignmentsUseCase {
  private readonly logger = new Logger(UpsertQuotasAssignmentsUseCase.name);
 
  public constructor(
    private readonly eventBus: EventBus,
    @InjectRepository(VariableValue)
    private readonly variableValueRepository: Repository<VariableValue>,
    @InjectRepository(Variable)
    private readonly variableRepository: Repository<Variable>,
    @InjectRepository(Team)
    private readonly teamRepository: Repository<Team>,
    @InjectRepository(Plan)
    private readonly planRepository: Repository<Plan>,
    private readonly appUsersRepository: AppUsersRepository,
  ) {}
 
  @Transactional()
  public async execute({
    company,
    authenticatedContext,
    upsertQuotasAssignmentsRequest,
  }: {
    company: Company;
    authenticatedContext: AuthenticatedContext;
    upsertQuotasAssignmentsRequest: UpsertQuotasAssignmentsRequest;
  }) {
    // We are iterating sequentially because in case of duplicates, the upsert does not work correctly because of a race condition.
    for (const upsertQuotaAssignmentRequest of upsertQuotasAssignmentsRequest.quotas) {
      // Get the target variable and asserts that it's a user, team, or plan variable.
      const variable = await this.getAndValidateVariable(company, upsertQuotaAssignmentRequest.variableId);
 
      this.assertCanExecute(authenticatedContext, upsertQuotaAssignmentRequest, variable);
 
      // Get either the user, team or plan depending on the variable type. This asserts that the related id is given and that the target entity exists.
      const { user, team, plan } = await this.getAndValidateLinkedEntity(
        company,
        variable.type,
        upsertQuotaAssignmentRequest,
      );
 
      // Validate the date boundaries based on the variable frequency.
      this.validateDateBoundaries(variable.frequency, upsertQuotaAssignmentRequest);
      // Make sure that currency is defined for currency variables.
      this.validateCurrency(variable.format, upsertQuotaAssignmentRequest);
 
      // Upsert the variable value.
      const { existingVariableValue, upsertedVariableValue } = await this.upsertVariableValue({
        company,
        upsertQuotaAssignmentRequest,
        variable,
        user,
        team,
        plan,
      });
 
      runOnTransactionCommit(() => {
        // Add audit log.
        this.publishAuditLog({
          authenticatedContext,
          existingVariableValue,
          upsertedVariableValue,
        }).catch((error) => {
          this.logger.error({
            message: 'Failed to publish QuotaAssignmentEvent',
            error: toError(error),
            upsertQuotaAssignmentRequest,
          });
        });
      });
    }
  }
 
  private async upsertVariableValue({
    company,
    upsertQuotaAssignmentRequest,
    variable,
    team,
    plan,
    user,
  }: {
    company: Company;
    upsertQuotaAssignmentRequest: UpsertQuotaAssignmentRequest;
    variable: Variable;
    team?: Team;
    plan?: Plan;
    user?: User;
  }) {
    const existingVariableValue =
      (await this.variableValueRepository.findOne({
        where: {
          company: { id: company.id },
          variable: { id: variable.id },
          user: user ? { id: user.id } : undefined,
          team: team ? { id: team.id } : undefined,
          plan: plan ? { id: plan.id } : undefined,
          startDate: upsertQuotaAssignmentRequest.startDate ?? undefined,
          endDate: upsertQuotaAssignmentRequest.endDate ?? undefined,
        },
      })) ?? undefined;
 
    return {
      existingVariableValue,
      upsertedVariableValue: await this.variableValueRepository.save({
        id: existingVariableValue?.id,
        company,
        variable,
        user,
        team,
        plan,
        startDate: upsertQuotaAssignmentRequest.startDate,
        endDate: upsertQuotaAssignmentRequest.endDate,
        value: upsertQuotaAssignmentRequest.value,
        currency: upsertQuotaAssignmentRequest.currency,
      } satisfies DeepPartial<VariableValue>),
    };
  }
 
  private async publishAuditLog({
    authenticatedContext,
    existingVariableValue,
    upsertedVariableValue,
  }: {
    authenticatedContext: AuthenticatedContext;
    existingVariableValue?: VariableValue;
    upsertedVariableValue: VariableValue;
  }) {
    assert(upsertedVariableValue.variable, new NotFoundException('The variable of the quota value does not exist'));
 
    const formattedPeriod = upsertedVariableValue.startDate
      ? formatPeriodName(upsertedVariableValue.variable.frequency, dayjs.unix(upsertedVariableValue.startDate).toDate())
      : '';
 
    await this.eventBus.publish(
      new QuotaAssignmentEvent({
        authenticatedContext,
        object: RecordObject.QUOTA_VALUES,
        type: existingVariableValue ? RecordType.EDIT : RecordType.CREATE,
        values: {
          what: formattedPeriod,
          oldValues: existingVariableValue?.value
            ? {
                period: formattedPeriod,
                value: existingVariableValue.value,
              }
            : undefined,
          newValues: {
            period: formattedPeriod,
            value: upsertedVariableValue.value,
          },
          target: upsertedVariableValue.user
            ? { id: upsertedVariableValue.user.id, name: formatUserFullName(upsertedVariableValue.user) }
            : upsertedVariableValue.team
              ? { id: upsertedVariableValue.team.id, name: upsertedVariableValue.team.name }
              : upsertedVariableValue.plan
                ? { id: upsertedVariableValue.plan.id, name: upsertedVariableValue.plan.name }
                : { id: upsertedVariableValue.variable.id, name: upsertedVariableValue.variable.name },
        },
      }),
    );
  }
 
  private async getAndValidateVariable(company: Company, variableId: UpsertQuotaAssignmentRequest['variableId']) {
    const variable = await this.variableRepository.findOne({
      where: {
        id: variableId,
        company: { id: company.id },
      },
    });
 
    assert(variable, new NotFoundException(`Variable ${variableId} not found`));
 
    return variable;
  }
 
  private getAndValidateUser(company: Company, userId: UpsertQuotaAssignmentRequest['userId']) {
    assert(userId, new BadRequestException('User id is required for user variables'));
    return this.appUsersRepository.findOne(company, userId);
  }
 
  private async getAndValidateTeam(company: Company, teamId: UpsertQuotaAssignmentRequest['teamId']) {
    assert(teamId, new BadRequestException('Team id is required for team variables'));
 
    const team = await this.teamRepository.findOne({
      where: {
        company: { id: company.id },
        id: teamId,
      },
    });
 
    assert(team, new NotFoundException(`Team ${teamId} not found`));
 
    return team;
  }
 
  private async getAndValidatePlan(company: Company, planId: UpsertQuotaAssignmentRequest['planId']) {
    assert(planId, new BadRequestException('Plan id is required for plan variables'));
 
    const plan = await this.planRepository.findOne({
      where: {
        company: { id: company.id },
        id: planId,
      },
    });
 
    assert(plan, new NotFoundException(`Plan ${planId} not found`));
 
    return plan;
  }
 
  private async getAndValidateLinkedEntity(
    company: Company,
    variableType: Variable['type'],
    { userId, teamId, planId }: Pick<UpsertQuotaAssignmentRequest, 'planId' | 'teamId' | 'userId'>,
  ) {
    switch (variableType) {
      case VariableType.user:
        return {
          user: await this.getAndValidateUser(company, userId),
          team: undefined,
          plan: undefined,
        };
 
      case VariableType.team:
        return {
          user: undefined,
          team: await this.getAndValidateTeam(company, teamId),
          plan: undefined,
        };
 
      case VariableType.plan:
        return {
          user: undefined,
          team: undefined,
          plan: await this.getAndValidatePlan(company, planId),
        };
 
      default:
        throw new BadRequestException(`You cannot set a value to a variable of type ${variableType}`);
    }
  }
 
  private validateDateBoundaries(
    variableFrequency: Variable['frequency'],
    { startDate, endDate }: Pick<UpsertQuotaAssignmentRequest, 'endDate' | 'startDate'>,
  ) {
    if (variableFrequency === PeriodFrequencyEnum.null) {
      return;
    }
 
    assert(startDate && endDate, new BadRequestException('Start and end date are required for period variables'));
    assert(startDate <= endDate, new BadRequestException('Start date must be before end date'));
 
    assert(
      isValidDateBoundary(startDate, 'START'),
      new BadRequestException('Start date is not a valid UTC timestamp or does not match the start of a period'),
    );
 
    assert(
      isValidDateBoundary(endDate, 'END'),
      new BadRequestException('End date is not a valid UTC timestamp or does not match the end of a period'),
    );
  }
 
  private validateCurrency(
    variableFormat: Variable['format'],
    { currency }: Pick<UpsertQuotaAssignmentRequest, 'currency'>,
  ) {
    assert(
      variableFormat !== FormatsEnum.currency || currency,
      new BadRequestException('Currency is required for currency variables'),
    );
  }
 
  private assertCanExecute(
    authenticatedContext: AuthenticatedContext,
    upsertQuotaAssignmentRequest: UpsertQuotaAssignmentRequest,
    variable: Variable,
  ) {
    const ability = defineAbilityFor(authenticatedContext);
 
    assert(
      !upsertQuotaAssignmentRequest.userId ||
        canAssignValuesToThisQuota(ability, {
          quotaId: variable.id,
          quotaType: variable.type,
          userId: upsertQuotaAssignmentRequest.userId,
          teamId: upsertQuotaAssignmentRequest.teamId,
          planId: upsertQuotaAssignmentRequest.planId,
          date: upsertQuotaAssignmentRequest.startDate,
        }) ||
        canAssignValuesToThisQuota(ability, {
          quotaId: variable.id,
          quotaType: variable.type,
          userId: upsertQuotaAssignmentRequest.userId,
          teamId: upsertQuotaAssignmentRequest.teamId,
          planId: upsertQuotaAssignmentRequest.planId,
          date: upsertQuotaAssignmentRequest.endDate,
        }),
      new ForbiddenException('You do not have the permission to set a quota value for this user'),
    );
  }
}