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 | 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 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 9x 9x 1x 1x 1x 1x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 54x 54x 54x 54x 54x 54x 1x 1x 1x 1x 1x 1x 1x 9x 9x 1x 1x 1x 1x 1x 1x 1x 15x 15x 6x 6x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 1x 15x 15x 2x 2x 13x 13x 13x 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 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 21x 21x 7x 7x 7x 7x 21x 21x 21x 14x 14x 14x 21x 21x 21x 21x 21x 22x 22x 22x 22x 7x 7x 1x 1x 1x 1x 7x 7x 7x 6x 6x 6x 7x 7x 7x 7x 7x 22x 22x 22x 22x 22x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x | import {
BadRequestException,
forwardRef as CircularDependency,
Inject,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { intersection, pick } from 'lodash-es';
import { match } from 'ts-pattern';
import { IsNull, Repository } from 'typeorm';
import { QUOTA_TYPES, VariableType } from '@amalia/amalia-lang/tokens/types';
import { Variable, type Company, type Plan } from '@amalia/core/models';
import { toError } from '@amalia/ext/typescript';
import { canViewPlanTokens, defineAbilityFor } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { search } from '../common/search';
import { PlansService } from '../plans/plans.service';
import { VariableGenericEvent } from './events/VariableGenericEvent';
@Injectable()
export class VariablesService {
private readonly logger = new Logger(VariablesService.name);
public constructor(
private readonly eventBus: EventBus,
@InjectRepository(Variable)
private readonly variableRepository: Repository<Variable>,
@Inject(CircularDependency(() => PlansService))
private readonly planService: PlansService,
) {}
/**
* Find all variables attached to a company
* @param company company
* @param types - Set null for all types.
* @param usedInPlanIds
*/
public async findAll(company: Company, types: VariableType[] | null, usedInPlanIds?: string[]): Promise<Variable[]> {
const queryBuilder = this.variableRepository.createQueryBuilder('variable');
// Filter by company.
queryBuilder.where('variable.company = :companyId', {
companyId: company.id,
});
// Join on object definition.
queryBuilder.leftJoinAndSelect('variable.object', 'object');
// Eventually filter by type.
if (types) {
if (types.length === 0) {
return [];
}
queryBuilder.andWhere('variable.type IN (:...types)', { types });
}
if (usedInPlanIds) {
const usages = await this.planService.getIdsOfItemsUsedInPlanTemplates(company, usedInPlanIds);
if (usages.length === 0) {
return [];
}
queryBuilder.andWhere('variable.id IN (:...usages)', { usages });
}
try {
return await queryBuilder.getMany();
} catch (err) {
const error = toError(err);
this.logger.error({
message: 'Error on findAll variables',
error,
company: pick(company, ['id', 'name']),
});
throw new InternalServerErrorException(err);
}
}
/**
* Returns all variables linked to a definition, or with the machineName provided
*
* @param company
* @param definitionId
* @param machineName
*/
public async findByDefinition(company: Company, definitionId: string, machineName?: string): Promise<Variable[]> {
return this.variableRepository.findBy({
company: { id: company.id },
object: { id: definitionId },
...(machineName && { machineName }),
});
}
/**
* Use in calculation engine only, this doesn't verify access rights.
*
* @param company
*/
public async findAllForCompany(company: Company): Promise<Variable[]> {
return this.variableRepository.find({
where: {
company: { id: company.id },
},
});
}
/**
* Find all variables attached to a company with a searchKey present in the formula
* @param company company
* @param searchKey searchKey
*/
public async findUsages(company: Company, searchKey: string): Promise<Variable[]> {
return this.variableRepository.find(search(company, 'formula', searchKey));
}
/**
* Find variable by id.
* @id id of the variable
* @throws {NotFoundException}
*/
public async findById(company: Company, id: string, populateObject: boolean = false): Promise<Variable | null> {
const relations = [];
if (populateObject) {
relations.push('object');
}
return this.variableRepository.findOne({
where: { company: { id: company.id }, id },
relations,
});
}
/**
* Find variable by id or throw.
* @id id of the variable
* @throws {NotFoundException}
*/
public async findByIdOrFail(company: Company, id: string, populateObject: boolean = false): Promise<Variable> {
const variable = await this.findById(company, id, populateObject);
if (!variable) {
throw new NotFoundException('Variable not found');
}
return variable;
}
/**
* Find variable by machineName.
* @param company company
* @param machineName machineName
* @param plan
* @throws {NotFoundException}
*/
public async findByMachineName(
company: Pick<Company, 'id'>,
machineName: string,
plan?: Plan,
): Promise<Variable | null> {
if (!machineName) {
throw new BadRequestException('No machineName');
}
// If we have a plan, search if we have plan scope variable.
if (plan) {
const planVariable = await this.variableRepository.findOneBy({
company: { id: company.id },
machineName,
plan: { id: plan.id },
});
if (planVariable) {
return planVariable;
}
}
// If no scope variable found, we search global variable.
return this.variableRepository.findOneBy({
company: { id: company.id },
machineName,
planId: IsNull(),
});
}
/**
* Audit record.
* @param authenticatedContext
* @param actionType type of action
* @param target
* @param newValues new values
* @param oldValues old values
*/
public async auditRecord(
authenticatedContext: AuthenticatedContext,
actionType: RecordType,
target: Variable,
newValues?: Variable,
oldValues?: Variable,
) {
await this.eventBus.publish(
new VariableGenericEvent({
authenticatedContext,
object: RecordObject.DESIGNER,
type: actionType,
values: {
target: pick(target, ['id', 'name']),
what: match(target.type)
.with(VariableType.statement, () => 'Variable')
.with(VariableType.object, () => 'Field')
.with(VariableType.user, () => 'Quota')
.otherwise(() => ''),
newValues: newValues
? match(target.type)
// designer / variable
.with(VariableType.statement, () => ({
name: newValues.name,
context: newValues.plan?.name ?? 'Global',
format: newValues.format,
formula: newValues.formula,
}))
// designer / fields
.with(VariableType.object, () => ({
name: newValues.name,
context: newValues.plan?.name ?? 'Global',
formula: newValues.formula,
}))
// designer / quota
.with(VariableType.user, VariableType.team, () => ({
name: newValues.name,
type: newValues.type,
format: newValues.format,
frequency: newValues.frequency,
}))
.otherwise(() => undefined)
: undefined,
oldValues: oldValues
? match(target.type)
// designer / variable
.with(VariableType.statement, () => ({
name: oldValues.name,
context: oldValues.plan?.name ?? 'Global',
format: oldValues.format,
formula: oldValues.formula,
}))
// designer / fields
.with(VariableType.object, () => ({
name: oldValues.name,
context: oldValues.plan?.name ?? 'Global',
formula: oldValues.formula,
}))
// designer / quota
.with(VariableType.user, VariableType.team, () => ({
name: oldValues.name,
type: oldValues.type,
format: oldValues.format,
frequency: oldValues.frequency,
}))
.otherwise(() => undefined)
: undefined,
},
}),
);
}
public async getVariablesFromUsers(
authenticatedContext: AuthenticatedContext,
userIds: string[] | null,
planIds: string[] | null,
typesRaw: VariableType[] | null,
company: Company,
canSeeAllVariables: boolean = false,
): Promise<Variable[]> {
// If the user doesn't have the "view plan" right, he can only fetch quotas.
// They will be later filtered with the rule "do I have at least an employee who is assigned to this quota?".
const types = canViewPlanTokens(defineAbilityFor(authenticatedContext))
? typesRaw
: // If not null, make an intersection between what was asked and what can be returned.
// Else prefilter with authorized types.
typesRaw
? intersection(QUOTA_TYPES, typesRaw)
: [...QUOTA_TYPES];
// Only get plans I can see.
const planIdsAuthorized = (
await this.planService.findAllWhereUserAuthorized({
company,
authenticatedContext,
// Only ask users that were passed in the query (or all if undefined).
userIds,
})
).map((p) => p.id);
// Filter them if needed.
const finalPlanIds = planIds?.length ? intersection(planIdsAuthorized, planIds) : planIdsAuthorized;
// And now fetch variables that are used in those plans.
return this.findAll(company, types, canSeeAllVariables ? undefined : finalPlanIds);
}
}
|