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 | 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 16x 16x 16x 16x 1x 1x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 66x 66x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 14x 14x 14x 76x 66x 66x 66x 80x 80x 80x 1x 1x 160x 160x 160x 160x 160x 160x 160x 1x 1x 1x 1x 1x 1x 1x 1x 1x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 79x 79x 79x 79x 79x 79x 79x 79x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 98x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 2x 2x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 77x 79x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 77x 77x 79x 80x 80x 80x 77x 77x 80x 1x 1x 80x 80x 80x 80x 80x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x | import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isNil, omit, pick } from 'lodash-es';
import { DataSource, Repository } from 'typeorm';
import { PlansAssignmentsService } from '@amalia/assignments/plans/core';
import { Calculation, getSchema, type Company, type Statement } from '@amalia/core/models';
import {
CALCULATION_ONGOING_STATUSES,
CalculationStatus,
CalculationType,
EngineErrorLevel,
EngineErrorType,
isEngineErrorHandledProperly,
PaymentReleaseError,
type CalculationDescriptorResult,
type EngineError,
} from '@amalia/core/types';
import { assert, toError } from '@amalia/ext/typescript';
import { AppLogger, InjectAppLogger, withLoggerContext } from '@amalia/kernel/logger/server';
import { type CalculationPayload, type TaskHandler } from '@amalia/kernel/queue/core';
import { TriggerStepUseCase } from '@amalia/payout-calculation/compute-engine/core-lifecycle';
import {
PlanTemplateService,
StatementReport,
UserStatementReports,
} from '@amalia/payout-calculation/compute-engine/core-plan-template';
import {
CalculationStoppedError,
StatementCalculationCacheFactory,
StoppableCalculationMapper,
} from '@amalia/payout-calculation/compute-engine/core-statement-calculation-cache';
import { PeriodsService } from '@amalia/payout-definition/periods/core';
import { CompaniesService } from '@amalia/tenants/companies/core';
import { CalculationUpdater } from '../calculationUpdater';
import { ComputationService } from '../computation/computation.service';
import { StatementSaveService } from '../statementSave/statementSave.service';
/**
* This event is called by the message queue to execute a calculation.
*
* It means the calculation has been created, it's in the database waiting for
* execution. Parameters are already set, and we just need its id to run it. Here
* we're just going to execute a single batch of it.
*/
@Injectable()
export class RunCalculationBatchUseCase implements TaskHandler<CalculationPayload> {
private readonly logger = new Logger(RunCalculationBatchUseCase.name);
public constructor(
@InjectAppLogger(RunCalculationBatchUseCase.name)
private readonly appLogger: AppLogger,
private readonly connection: DataSource,
@InjectRepository(Calculation)
private readonly calculationRepository: Repository<Calculation>,
private readonly periodService: PeriodsService,
private readonly planAssignmentsService: PlansAssignmentsService,
private readonly statementSaveService: StatementSaveService,
private readonly companiesService: CompaniesService,
private readonly computationService: ComputationService,
private readonly planTemplateService: PlanTemplateService,
private readonly stoppableCalculationMapper: StoppableCalculationMapper,
private readonly triggerStepUseCase: TriggerStepUseCase,
private readonly statementCalculationCacheFactory: StatementCalculationCacheFactory,
) {}
public async handle({ calculationId, step, batch, companyId }: CalculationPayload) {
assert(!isNil(step) && !isNil(batch), `Calculation ${calculationId} failed: Missing step or batch`);
const company = await this.companiesService.findById(companyId);
const calculation = await this.calculationRepository.findOne({
where: {
company: { id: companyId },
id: calculationId,
},
relations: ['company'],
});
assert(calculation, `Calculation ${calculationId} not found.`);
// If I'm the first one to work on this calculation, set its status to "started".
if ([CalculationStatus.PENDING, CalculationStatus.REFRESH].includes(calculation.status)) {
await this.calculationRepository.update({ id: calculationId }, { status: CalculationStatus.STARTED });
}
const currentStep = calculation.descriptor[step];
assert(currentStep, `Calculation ${calculationId} - step ${step} -- not found.`);
const currentBatch = currentStep.batches[batch];
assert(currentBatch, `Calculation ${calculationId} - step ${step} - batch ${batch} -- not found.`);
await withLoggerContext(
this.appLogger,
{
company: pick(company, ['id', 'name']),
// remove descriptor or it will fully log every user.
calculation: pick(calculation, ['id', 'type']),
step,
batch,
currentStep: omit(currentStep, 'batches'),
currentBatch: {
...currentBatch,
users: currentBatch.users.map((u) => pick(u, ['id', 'email'])),
},
},
async () => {
if (currentBatch.status !== CalculationStatus.PENDING) {
this.logger.warn({
message: `Calculation ${calculationId} - step ${step} - batch ${batch} -- already been picked up.`,
status: currentBatch.status,
});
return;
}
this.logger.log(`Calculation ${calculationId} - step ${step} - batch ${batch} -- STARTED`);
await this.updateBatchStatus(calculationId, step, batch, CalculationStatus.STARTED);
const finalBatchStatus = await this.computeCurrentBatch(company, calculation, step, batch);
this.logger.log(`Calculation ${calculationId} - step ${step} - batch ${batch} -- FINISHED`);
// Update the status of the current batch.
await this.updateBatchStatus(calculationId, step, batch, finalBatchStatus);
// Fetch the current calculation.
const updatedCalculation = await this.calculationRepository.findOneBy({
company: { id: company.id },
id: calculationId,
});
assert(updatedCalculation, 'In RunCalculationBatch, updatedCalculation failed');
// If I'm the last batch to finish, trigger the next one.
if (updatedCalculation.descriptor[step].batches.some((b) => CALCULATION_ONGOING_STATUSES.includes(b.status))) {
this.logger.debug(
`Calculation ${calculationId} - step ${step} - batch ${batch} -- waiting for others to finish.`,
);
} else {
this.logger.debug(`Calculation ${calculationId} - step ${step} - batch ${batch} -- scheduling next step.`);
await this.triggerStepUseCase.execute(company, updatedCalculation, step + 1);
}
},
);
}
private async updateBatchStatus(calculationId: string, step: number, batch: number, status: CalculationStatus) {
await this.connection.query(
`UPDATE ${getSchema(
this.connection,
)}."calculation" SET "descriptor" = jsonb_set("descriptor", $1, $2, true) WHERE id=$3`,
[`{${step},batches,${batch},status}`, `"${status}"`, calculationId],
);
}
/**
* Launch statement calculation.
* @param company
* @param calculation
* @param step
* @param batch
*/
private async computeCurrentBatch(
company: Company,
calculation: Calculation,
step: number,
batch: number,
): Promise<CalculationStatus> {
const { descriptor } = calculation;
const { periodId } = descriptor[step];
const { planId, users } = descriptor[step].batches[batch];
return withLoggerContext(
this.appLogger,
{
calculation: omit(calculation, 'descriptor'),
company: pick(company, ['id', 'name']),
step,
batch,
planId,
usersCount: users.length,
},
async () => {
const calculationUpdater = new CalculationUpdater(company, this.calculationRepository, calculation);
calculationUpdater.start();
try {
const period = await this.periodService.getById(company, periodId);
assert(period, 'In computeCurrentBatch, period not found');
const statementCalculationCache = await this.statementCalculationCacheFactory.instantiate(
company,
{ planId },
this.stoppableCalculationMapper.calculationToStoppableCalculation(calculation, this.calculationRepository),
);
const plan = statementCalculationCache.getDefinitions().getPlan();
assert(plan, 'In computeCurrentBatch, plan not found');
if (calculation.type === CalculationType.FORECAST && (!plan.isForecasted || !plan.forecast)) {
return await this.handleCalculationError(
calculation,
new Error('Forecast calculation started on a plan that has not forecast'),
);
}
if (period.frequency !== plan.frequency) {
return await this.handleCalculationError(
calculation,
new Error('Current period frequency is not compatible to plan frequency'),
);
}
// One check before starting to populate the cache, calculation could have been stopped
// while it was in the queue, for instance.
await statementCalculationCache.calculation!.verifyCalculationIsOngoingNonThrottled();
const statementReports: StatementReport[] = [];
// Another check before actually starting the calculation and updating the status.
await statementCalculationCache.calculation!.verifyCalculationIsOngoingNonThrottled();
// Small closure here to avoid injecting the calculation service in the level below.
const saveProgress = async (statement: Statement) => {
const result: CalculationDescriptorResult = {
error: statement.error ? statement.error.message : null,
status: statement.error ? CalculationStatus.ERROR : CalculationStatus.SUCCESS,
statementId: statement.id,
};
const path = `{${step},batches,${batch},users,${users.findIndex((u) => u.id === statement.userId)},result}`;
await this.connection.query(
`UPDATE ${getSchema(
this.connection,
)}."calculation" SET "descriptor" = jsonb_set("descriptor", $1, $2, true) WHERE id=$3`,
[path, result, calculation.id],
);
await this.connection.query(
`UPDATE ${getSchema(this.connection)}."calculation" SET calculated = calculated + 1 WHERE id=$1`,
[calculation.id],
);
};
const seenStatements: Statement[] = [];
const userIds = users.map((u) => u.id);
const planAssignments = await this.planAssignmentsService.findAll(company.id, [plan.id], userIds, period, [
'user',
'plan',
]);
const { planTemplate, error } = await this.planTemplateService.buildTemplate(
company,
plan,
statementCalculationCache,
false,
);
// If an error happened during the compilation, throw it right away.
if (error) {
return await this.handleCalculationError(calculation, error);
}
const { statements, reports } = await this.computationService.calculateStatementsByPlan(
statementCalculationCache,
calculation.type,
company,
planTemplate,
period,
planAssignments,
saveProgress,
);
statementReports.push(...reports);
seenStatements.push(...statements);
// If not in forecast, release payments and resync challenges.
if (calculation.type === CalculationType.STATEMENT) {
// Perform the release of the payments belonging to users affected by the calculation.
await this.statementSaveService.releasePaymentsForUsers(
userIds,
period,
company,
statementCalculationCache,
);
await this.statementSaveService.syncChallengesLeaderboards(company, seenStatements);
}
const batchStatus: CalculationStatus = seenStatements.some((s) => !!s.error)
? CalculationStatus.INCOMPLETE
: CalculationStatus.SUCCESS;
await new UserStatementReports().writeReportsToDisk(statementReports);
return batchStatus;
} catch (error) {
return await this.handleCalculationError(calculation, toError(error));
} finally {
calculationUpdater.stop();
}
},
);
}
/**
* Handler Error based on error type.
* @param calculation
* @param error
* @private
*/
private async handleCalculationError(calculation: Calculation, error: Error): Promise<CalculationStatus> {
if (error instanceof CalculationStoppedError) {
this.logger.log({ message: `Calculation ${calculation.id} stopped.`, calculation, error });
return CalculationStatus.STOPPED;
}
let errorMessage: string | null;
let errorMetadata: EngineError | null;
let shouldLogInStderr = false;
if (isEngineErrorHandledProperly(error)) {
errorMessage = error.message;
errorMetadata = error.getError();
// If we have an error message, it means we don't have to log it (unless we have
// a PaymentReleaseError, they're not displayed on the app).
shouldLogInStderr = error instanceof PaymentReleaseError;
} else {
errorMessage = 'Non recoverable error while computing';
errorMetadata = { type: EngineErrorType.UNHANDLED, message: errorMessage, level: EngineErrorLevel.ERROR };
shouldLogInStderr = true;
}
if (shouldLogInStderr) {
this.logger.error({ message: `Error on running calculation: ${error.message}`, error, stack: error.stack });
} else {
this.logger.warn({ message: `Recoverable error on calculation: ${error.message}`, error });
}
await this.calculationRepository.update(
{ id: calculation.id },
{
error: errorMessage,
errorMetadata,
},
);
return CalculationStatus.ERROR;
}
}
|