All files / libs/payout-definition/variables/core/src/lib/use-cases get-fields-variables-by-objectId.use-case.ts

100% Statements 46/46
66.66% Branches 2/3
100% Functions 2/2
100% Lines 46/46

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 471x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x  
import { ForbiddenException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
 
import { VariableType, VariableWithPlan } from '@amalia/amalia-lang/tokens/types';
import { Company, Variable } from '@amalia/core/models';
import { assert } from '@amalia/ext/typescript';
import { canViewPlanTokens, defineAbilityFor } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
 
type GetFieldsVariablesByObjectIdUseCaseParams = {
  authenticatedContext: AuthenticatedContext;
  companyId: Company['id'];
  customDefinitionObjectId: string;
};
 
@Injectable()
export class GetFieldsVariablesByObjectIdUseCase {
  public constructor(
    @InjectRepository(Variable)
    private readonly variableRepository: Repository<Variable>,
  ) {}
 
  public async execute({
    authenticatedContext,
    companyId,
    customDefinitionObjectId,
  }: GetFieldsVariablesByObjectIdUseCaseParams): Promise<VariableWithPlan[]> {
    const ability = defineAbilityFor(authenticatedContext);
    assert(
      canViewPlanTokens(ability),
      new ForbiddenException('You are not allowed to get fields related to this object.'),
    );
 
    return this.variableRepository.find({
      where: {
        objectId: customDefinitionObjectId,
        type: VariableType.object,
        company: { id: companyId },
      },
      relations: ['plan'],
      select: ['machineName', 'name', 'format', 'id'],
      order: { machineName: 'ASC' },
    }) as unknown as Promise<VariableWithPlan[]>;
  }
}