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 | 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 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 65x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 96x 31x 31x 31x 98x 98x 98x 1x 1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 67x 67x 67x 67x 67x 67x 67x 98x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 1x 1x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 95x 95x 98x 98x 98x 98x 77x 77x 77x 77x 77x 77x 1x 1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 1x 1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 67x 67x 67x 67x 67x 67x 67x 67x 67x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 67x 67x 98x 98x 98x 98x 98x 98x 98x 98x 98x 450x 450x 450x 450x 450x 450x 345x 129x 129x 129x 129x 129x 129x 129x 129x 320x 216x 216x 216x 216x 216x 213x 213x 342x 450x 105x 105x 105x 98x 95x 95x 98x 3x 3x 98x 98x 98x 98x 98x 98x 1x 1x 3x 3x 3x 3x 1x | import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { pick } from 'lodash-es';
import { CalculationParser } from '@amalia/amalia-lang/formula/evaluate/shared';
import {
type Company,
type Overwrite,
type Period,
type Plan,
type PlanAssignment,
type Statement,
type User,
} from '@amalia/core/models';
import {
CalculationError,
CalculationType,
ConfigurationError,
EngineError,
EngineErrorLevel,
EngineErrorType,
isBeingReviewed,
MissingQuotaError,
type Statement as StatementType,
} from '@amalia/core/types';
import { OverwritesService } from '@amalia/data-correction/overwrites/core';
import { toError } from '@amalia/ext/typescript';
import {
UserStatement,
type PlanTemplate,
type StatementReport,
} from '@amalia/payout-calculation/compute-engine/core-plan-template';
import {
CalculationStoppedError,
StatementCalculationCache,
} from '@amalia/payout-calculation/compute-engine/core-statement-calculation-cache';
import { StatementsService } from '@amalia/payout-calculation/statements/core';
import { type ComputedRule, type ComputedVariable } from '@amalia/payout-calculation/types';
import { type Plan as PlanInterface } from '@amalia/payout-definition/plans/types';
import { TeamAssignmentService } from '@amalia/tenants/assignments/teams/core';
import { TeamsService } from '@amalia/tenants/teams/core';
import { StatementSaveService } from '../statementSave/statementSave.service';
import { type CalculationContext } from '../types/calculation-context.types';
import { AssignmentScopeBuilder } from './assignmentScope.builder';
import { ComputeTokenService } from './compute-token/ComputeToken.service';
import { DatasetService } from './datasets/dataset.service';
import { TeamScopeBuilder } from './teamScopeBuilder';
@Injectable()
export class ComputationService {
private readonly logger = new Logger(ComputationService.name);
public readonly assignmentScopeBuilder: AssignmentScopeBuilder;
public readonly teamScopeBuilder: TeamScopeBuilder;
public constructor(
private readonly statementsService: StatementsService,
private readonly statementSaveService: StatementSaveService,
private readonly overwriteService: OverwritesService,
private readonly datasetService: DatasetService,
private readonly teamService: TeamsService,
private readonly teamAssignmentService: TeamAssignmentService,
) {
this.assignmentScopeBuilder = new AssignmentScopeBuilder(this.teamService, this.teamAssignmentService);
this.teamScopeBuilder = new TeamScopeBuilder();
}
public async calculateOneStatement(
statementCalculationCache: StatementCalculationCache,
company: Company,
calculationType: CalculationType,
planTemplate: PlanTemplate,
period: Period,
nextPeriods: Period[],
planAssignment: PlanAssignment,
): Promise<{ statement: Statement; reviewStarted?: boolean; report?: StatementReport }> {
const { id: planId, name: planName } = planTemplate.getPlan();
const userAssigned: User = planAssignment.user;
this.logger.log({
message: `Computing ${planName} - ${userAssigned.email} - ${period.name}`,
planName,
userAssigned: pick(userAssigned, ['id', 'email']),
period,
});
// See if there is already a statement that matches those criteria.
const statementFound = await this.getExistingStatement(company, period, userAssigned, planId);
// If the statement is being reviewed, don't touch it.
// Normally, it should not happen because statements are filtered before.
if (
statementFound &&
calculationType === CalculationType.STATEMENT &&
isBeingReviewed(statementFound as StatementType)
) {
return {
reviewStarted: true,
statement: statementFound,
};
}
// Calculate the statement.
const { error, userStatement } = await this.calculateStatement(
statementCalculationCache,
planTemplate,
planAssignment,
period,
statementFound,
);
await statementCalculationCache.calculation!.verifyCalculationIsOngoingNonThrottled();
const savedStatement: Statement = await this.saveStatement(
statementCalculationCache,
userStatement,
period,
userAssigned,
planTemplate.getPlan(),
error,
statementFound,
nextPeriods,
);
return {
statement: savedStatement,
report: error ? undefined : userStatement.computeStatementReport(savedStatement.id),
};
}
/**
* Try to get an existing statement for the combo period / plan / user.
*
* If one exists, then it'll serve as a base during calculation, because
* it may already have things attached, like overwrites, adjustments, ...
*
* @param company
* @param period
* @param user
* @param planId
* @private
*/
private async getExistingStatement(
company: Company,
period: Period,
user: User,
planId: string,
): Promise<Statement | null> {
// See if there is already a statement that matches those criteria.
let statementFound: Statement | null = null;
try {
statementFound = await this.statementsService.findOneByPeriodAndUserAndPlan(company, period.id, user.id, planId, [
'adjustments',
'adjustments.paymentPeriod',
'adjustments.rowDefinition',
'period',
'plan',
'user',
]);
} catch (e) {
// Fails silently if it's a NotFoundException, it means that there is no statement.
if (!(e instanceof NotFoundException)) {
throw e;
}
}
return statementFound;
}
private async saveStatement(
statementCalculationCache: StatementCalculationCache,
userStatement: UserStatement,
period: Period,
user: User,
plan: Plan,
error: EngineError | null,
statementFound: Partial<Statement> | null,
nextPeriods: Period[],
): Promise<Statement> {
const { company } = statementCalculationCache;
const rate = await statementCalculationCache.getConversionRate(user.currency, period.endDate);
// Add rates.
userStatement.registerCurrencyRate(company.currency, 1);
userStatement.registerCurrencyRate(user.currency, rate);
const statementToSave = statementFound
? {
// Copy everything from the previously computed statement.
...statementFound,
// Change currency if user has changed.
currency: user.currency,
rate,
...userStatement.getAssignmentsToStore(),
}
: {
company: statementCalculationCache.company,
period,
plan: {
id: plan.id,
name: plan.name,
} as Plan,
user,
workflowComplete: false,
currency: user.currency,
rate,
...userStatement.getAssignmentsToStore(),
};
return this.statementSaveService.saveStatement(
statementCalculationCache.company,
statementCalculationCache,
statementToSave,
userStatement,
error,
nextPeriods,
plan.forecast,
);
}
public async calculateStatementsByPlan(
statementCalculationCache: StatementCalculationCache,
calculationType: CalculationType,
company: Company,
planTemplate: PlanTemplate,
period: Period,
planAssignments: PlanAssignment[],
saveProgress: (statement: Statement) => Promise<void>,
): Promise<{
statements: Statement[];
reports: StatementReport[];
}> {
const reports: StatementReport[] = [];
// Prepare next periods for payment splits.
const nextPeriods = await this.statementSaveService.getNextPeriodsToSplitStatement(
company,
planTemplate.getPlan().planRules!.map((pr) => pr.rule),
period,
);
// Populate an array of statements that we've seen during this calculation.
const seenStatements: Statement[] = [];
// Loop on planAssignments and try to find existing statements.
for (const planAssignment of planAssignments) {
// Sometimes we need to compute a statement twice because it's using its own metrics.
// It's a temporary hack, we'll wait until we have the dashboards.
if (company.featureFlags.CALCULATE_STATEMENT_TWICE) {
await this.calculateOneStatement(
statementCalculationCache,
company,
calculationType,
planTemplate,
period,
nextPeriods,
planAssignment,
);
}
const { statement, report, reviewStarted } = await this.calculateOneStatement(
statementCalculationCache,
company,
calculationType,
planTemplate,
period,
nextPeriods,
planAssignment,
);
if (!reviewStarted) {
// In sync, no concurrency.
await saveProgress(statement);
if (report) {
reports.push(report);
}
}
seenStatements.push(statement);
}
return {
statements: seenStatements,
reports,
};
}
public async prepareStatementCalculation(
statementCalculationCache: StatementCalculationCache,
planTemplate: PlanTemplate,
planAssignment: PlanAssignment,
period: Period,
overwrites: Overwrite[],
): Promise<CalculationContext> {
const { user, mainTeamId } = planAssignment;
const { company } = statementCalculationCache;
// Get all scopes for team assignments, employees, managers...
// If needed, fetch all assignments that could be interesting without a date limit.
// Trust the plan template on which scopes we need to fetch.
const allAssignmentsEver = await this.assignmentScopeBuilder.build(
company,
user,
mainTeamId,
planTemplate.getScopesToFetch(),
);
// Fetch assignments and employees of the current user. Those relate to the period of the calculation, so
// we can fill the team.employees, team.managers, and user.teamMembers scope key. If you need to
// get assignment at the precise date, you should use MATCH_USERS_ASSIGNED instead, which scope is
// populated below (in allAssignmentsEver).
const [teams, teamAssignments, teamMembers] = await Promise.all([
this.teamService.findAllWhereUserAssignedOrManager(company, user.id, period),
this.teamAssignmentService.findAllByParameters(company, [], [user.id], undefined, period, ['team']),
this.teamAssignmentService.getTeamMembers(company, user, period),
]);
const { myTeamAssignment, teamsWithKeywords } = this.teamScopeBuilder.build(teams, planAssignment, period);
// Build a calculation parser.
const calculationParser = new CalculationParser({
user,
teams: teamsWithKeywords,
plan: planTemplate.getPlan() as PlanInterface,
period,
userTeamMembers: teamMembers.map((tm) => tm.user!),
});
// Add assignments.
calculationParser.setPlanAssignment(planAssignment);
calculationParser.setTeamAssignment(myTeamAssignment || null);
// Init an empty computed statement.
const userStatement = new UserStatement(company, {
planTemplate,
planAssignment,
overwrites,
teamAssignments,
teamUsedDuringCalculationId: calculationParser.getTeam()?.id,
allAssignments: allAssignmentsEver,
parentTeamAssignments: (await this.teamService.getParentTeams(teams)).map((t) => ({
teamId: t.id,
teamName: t.name,
})),
});
return {
calculationParser,
userStatement,
statementCalculationCache,
};
}
private async calculateStatement(
statementCalculationCache: StatementCalculationCache,
planTemplate: PlanTemplate,
planAssignment: PlanAssignment,
period: Period,
existingStatement: Statement | null,
): Promise<{ error: EngineError | null; userStatement: UserStatement }> {
if (statementCalculationCache.calculation!.type === CalculationType.FORECAST && !existingStatement) {
return {
error: {
message: `Launch a forecast calculation on a non existing statement - ${planAssignment.user.email} - ${period.name} - ${planTemplate.getPlan().name}`,
type: EngineErrorType.CALCULATION,
level: EngineErrorLevel.ERROR,
} satisfies EngineError,
// Add a userStatement to the answer, so it's going to be saved in the database with the error.
userStatement: new UserStatement(statementCalculationCache.company, { planTemplate, planAssignment }),
};
}
let overwrites: Overwrite[] = [];
if (existingStatement) {
// Fetch overwrites.
overwrites = await this.overwriteService.findByCustomObjectAndStatementAndVariableAndFilter(
statementCalculationCache.company,
null,
existingStatement,
undefined,
true,
);
}
const calculationContext = await this.prepareStatementCalculation(
statementCalculationCache,
planTemplate,
planAssignment,
period,
overwrites,
);
const { userStatement } = calculationContext;
if (existingStatement) {
userStatement.setStatementId(existingStatement.id);
}
// Failsafe: plan without rules.
if (planTemplate.getPlan().planRules?.length === 0) {
return {
userStatement,
error: {
message: 'There are no rules in this plan.',
type: EngineErrorType.CALCULATION,
level: EngineErrorLevel.ERROR,
} satisfies EngineError,
};
}
let error: EngineError | null = null;
try {
// Iterate on the list until everything is computed.
await planTemplate.traversePlan(async ({ computedItem, dataset, parentDatasetId }) => {
// Now would be a good time to check if the calculation wasn't stopped.
await statementCalculationCache.calculation!.verifyCalculationIsOngoingThrottled();
const startDate = Date.now();
if (computedItem) {
if (parentDatasetId) {
// A computedItem in a dataset is an object variable.
const actuallyComputedItem = await ComputeTokenService.computeItem(
calculationContext,
computedItem as ComputedVariable,
parentDatasetId,
);
userStatement.saveComputedItemInDataset(actuallyComputedItem as ComputedVariable, parentDatasetId);
} else {
// A computedItem outside a dataset is a global variable (statement, rule or quota).
const actuallyComputedItem = await ComputeTokenService.computeItem(
calculationContext,
computedItem as ComputedRule | ComputedVariable,
);
userStatement.saveGlobalComputedItem(actuallyComputedItem);
}
userStatement.registerTimeComputationItem(computedItem, Date.now() - startDate);
} else if (dataset) {
await this.datasetService.fetchAndLoadDataset(calculationContext, dataset, existingStatement);
userStatement.registerTimeComputationItem(dataset, Date.now() - startDate);
} else {
throw new Error('Cannot compute item');
}
});
userStatement.registerEndDate();
} catch (e) {
error = this.properlyHandleStatementCalculationError(statementCalculationCache.company, e);
}
return {
userStatement,
error,
};
}
private properlyHandleStatementCalculationError(company: Company, e: unknown): EngineError {
// If it's a CalculationError, put the error in the statement.
if (e instanceof CalculationError || e instanceof ConfigurationError || e instanceof MissingQuotaError) {
return e.getError();
}
if (e instanceof CalculationStoppedError) {
// The calculation was stopped by the user, bubble up the error, so it'll stop the
// whole ongoing calculation and not only stop for this statement.
throw e;
}
const error = toError(e);
// Else, error is probably on our side, so we're staying vague.
this.logger.error({
error: e,
stack: error.stack,
message: error.message,
company: pick(company, ['id', 'name']),
});
return {
message: 'Error, please contact the admin',
type: EngineErrorType.UNHANDLED,
level: EngineErrorLevel.ERROR,
};
}
}
|