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 | 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 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 10x 10x 10x 10x 10x 10x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 10x 10x 10x 10x 10x 11x 11x 11x 10x 10x 10x 10x 10x 11x 11x 11x 11x 10x 10x 10x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 10x 10x 10x 10x 10x 10x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 21x 21x 21x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 10x 10x 1x 1x 20x 20x 20x 20x 15x 20x 1x 1x 1x 1x 1x 1x 1x 1x 40x 40x 40x 40x 40x 40x 40x 40x 40x 1x | import { Injectable, Logger } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { keyBy, pick, uniq, uniqBy } from 'lodash-es';
import { DataSource, In } from 'typeorm';
import { CalculationParser } from '@amalia/amalia-lang/formula/evaluate/shared';
import {
CustomObject,
DataConnectionName,
Plan,
PlanAssignment,
Rule,
type Company,
type Payment,
type Period,
type User,
} from '@amalia/core/models';
import { ConfigurationError, PaymentErrorType, type DatasetRow } from '@amalia/core/types';
import { dateFromCalculationEngineToJsDate } from '@amalia/ext/dates';
import { assert, promiseAllSettledAutoThrow, promiseDotAllChunk, toError } from '@amalia/ext/typescript';
import { PlanTemplate, UserStatement } from '@amalia/payout-calculation/compute-engine/core-plan-template';
import { type StatementCalculationCache } from '@amalia/payout-calculation/compute-engine/core-statement-calculation-cache';
import { type PaymentMergeResult } from '@amalia/payout-calculation/payments/core';
import { type ComputedRule, type ComputedVariable } from '@amalia/payout-calculation/types';
import { PeriodsService } from '@amalia/payout-definition/periods/core';
import { PeriodFrequencyEnum } from '@amalia/payout-definition/periods/types';
import { type HoldAndReleaseSettings } from '@amalia/payout-definition/plans/types';
import { AdminScopesRepository } from '@amalia/tenants/companies/admin-scopes/auth';
import { ComputeTokenService } from '../computation/compute-token/ComputeToken.service';
import { RelationshipService } from '../computation/datasets/query/filter/relationship.service';
import { type CalculationContext } from '../types/calculation-context.types';
import { PlanTemplateRelease } from './PlanTemplateRelease';
@Injectable()
export class ReleaseService {
private readonly logger = new Logger(ReleaseService.name);
public constructor(
private readonly connection: DataSource,
@InjectDataSource(DataConnectionName)
private readonly dataConnection: DataSource,
private readonly relationshipService: RelationshipService,
private readonly periodsService: PeriodsService,
private readonly adminScopesRepository: AdminScopesRepository,
) {}
/**
* Compute the diff to apply to locked payments.
*
* It updates the payment and forecast date, and eventually releases
* the payment if the release condition is fulfilled.
*
* @param company
* @param period
* @param userIds
* @param paymentsOnHold
* @param statementCalculationCache
* @returns The diff to apply on payments.
*/
public async updateOnHoldPayments(
company: Company,
period: Period,
userIds: User['id'][],
paymentsOnHold: Payment[],
statementCalculationCache: StatementCalculationCache,
): Promise<NonNullable<PaymentMergeResult['paymentsToEdit']>> {
// Create a "mini plan template" for each rule based on the config of the hold and release.
// I wanted to go for a simpler approach by just creating a dataset, a variable
// and call it a day.
// However, business needs increased, and now they basically
// want the same functionalities as the calculation engine (ComputedFunctionResults,
// relations, quotas, ...).
// The easiest way is to reuse the same implementations as the engine,
// or else we're gonna re-develop everything.
// Since we cannot release without a plan (needed for scopes), we're making groups planId + ruleId,
// then we'll build a PlanTemplateRelease for each element of this group.
const rulesToCompute = uniqBy(
paymentsOnHold.map((p) => pick(p, ['ruleId', 'planId'])),
(p) => `${p.planId}::${p.ruleId}`,
);
const planIds = uniq(paymentsOnHold.map((p) => p.planId));
if (!rulesToCompute.length || !rulesToCompute.length) {
return [];
}
const plans = await this.connection
.getRepository(Plan)
.find({ where: { company: { id: company.id }, id: In(planIds) } });
const plansMap = keyBy(plans, 'id');
const planTemplates = await Promise.all(
rulesToCompute.map(async ({ planId, ruleId }) => {
const plan = plansMap[planId];
assert(plan, `During release, plan with id ${planId} not found`);
const scopes = await this.adminScopesRepository.listScopesForPlan(company.id, plan);
const planTemplateForRule = new PlanTemplateRelease(plan, statementCalculationCache, scopes);
await planTemplateForRule.buildForReleaseCondition(ruleId);
planTemplateForRule.buildQueryContainers(this.connection, this.dataConnection, false);
return { planId, ruleId, planTemplateForRule };
}),
);
// Build a hashmap of planTemplates indexed by planId + ruleId.
const planTemplateHashmaps = planTemplates.reduce(
(acc, { planId, ruleId, planTemplateForRule }) => {
acc[planId] ??= {};
acc[planId][ruleId] = planTemplateForRule;
return acc;
},
{} as Record<Plan['id'], Record<Rule['id'], PlanTemplateRelease> | undefined>,
);
// We group payments by users.
const paymentsGroupsByUser = Object.groupBy(paymentsOnHold, (payment) => payment.userId);
const diffs: PaymentMergeResult['paymentsToEdit'] = [];
const planAssignments = await this.connection.getRepository(PlanAssignment).find({
where: { userId: In(uniq(userIds)) },
relations: {
user: {
teamAssignments: {
team: true,
},
},
},
});
// And now we loop on users to unlock the deals.
await promiseDotAllChunk(
Object.entries(paymentsGroupsByUser),
async ([userId, paymentsForUser]) => {
try {
// Given all payments for a user, group them by rule and try to unlock them.
const paymentsGroupsByUserByRule = Object.groupBy(
paymentsForUser ?? [],
(payment) => `${payment.planId}::${payment.ruleId}`,
);
await promiseAllSettledAutoThrow(
Object.entries(paymentsGroupsByUserByRule).map(async ([planIdAndRuleId, paymentsForRule]) => {
try {
const [planId, ruleId] = planIdAndRuleId.split('::');
// Fetch in the hashmap the PlanTemplate we're going to use.
const planTemplateForCurrentRule = planTemplateHashmaps[planId]?.[ruleId];
assert(planTemplateForCurrentRule, `Plan template not found for couple ${planId} - ${ruleId}`);
// Fetch user-related data.
const planAssignment = planAssignments.find(
(planAssignment) => userId === planAssignment.user.id && planId === planAssignment.planId,
);
// Log without throwing because we don't want to stop the whole process.
if (!planAssignment) {
this.logger.error(
`Cannot release some payments for plan ${planTemplateForCurrentRule.getPlan().name} - user ${userId} - user not assigned anymore`,
);
// Add all payments for this rule with error
const erroredPayments = (paymentsForRule ?? []).map((payment) => ({
newPayment: {
...payment,
error: {
type: PaymentErrorType.ASSIGNMENT_REMOVED as const,
},
},
previousPayment: payment,
}));
diffs.push(...erroredPayments);
return;
}
assert(planAssignment.user, 'In updateOnHoldPayments, relation on user missing');
assert(
planAssignment.user.teamAssignments,
'In updateOnHoldPayments, relation on teamAssignments missing',
);
// Instantiate a parser.
const calculationParser = new CalculationParser({
user: planAssignment.user,
period,
teams: uniqBy(
(planAssignment.user.teamAssignments ?? []).map(({ team }) => team!),
(team) => team.id,
),
});
// Load the planTemplate into an empty userStatement.
const userStatement = new UserStatement(company, {
planTemplate: planTemplateForCurrentRule,
planAssignment,
});
const calculationContext: CalculationContext = {
calculationParser,
statementCalculationCache,
userStatement,
};
const ruleDefinition = await statementCalculationCache.fetchRuleById(ruleId);
const ruleConfiguration = ruleDefinition.configuration;
const paymentPeriod = await this.getPaymentPeriod(
company,
period,
ruleConfiguration?.payMonthly || false,
ruleConfiguration?.paymentMonthOffset ?? 0,
);
// Get the list of externalIds to release.
const diffsInRule = await this.evaluateDiffsInRule(
company,
calculationContext,
paymentsForRule ?? [],
planTemplateForCurrentRule,
paymentPeriod,
);
// And add them to the release list.
diffs.push(...diffsInRule);
} catch (err) {
const error = toError(err);
error.message = `Release: user ${userId}, plan and rule ${planIdAndRuleId}: ${err instanceof AggregateError ? err.errors.map((error) => toError(error).message).join(', ') : error.message}`;
throw error;
}
}),
);
} catch (err) {
const error = toError(err);
error.message = `Error while releasing payments: ${err instanceof AggregateError ? err.errors.map((error) => toError(error).message).join(', ') : error.message}`;
throw error;
}
},
100,
);
return diffs;
}
private async getPaymentPeriod(
company: Company,
period: Period,
payMonthly: boolean,
paymentMonth: number,
): Promise<Period> {
if (payMonthly && period.frequency !== PeriodFrequencyEnum.month) {
const nextPeriod = await this.periodsService.findNextPeriod(company, period, paymentMonth, {
createIfNotExist: true,
frequencySelectMode: 'COMPANY',
});
// It's not null because it's createIfNotExist.
assert(nextPeriod, 'Next period not exist');
return nextPeriod;
}
return period;
}
private async evaluateDiffsInRule(
company: Company,
calculationContext: CalculationContext,
payments: Payment[],
planTemplate: PlanTemplate,
period: Period,
): Promise<NonNullable<PaymentMergeResult['paymentsToEdit']>> {
const { calculationParser, userStatement } = calculationContext;
const { dataset, customObjectDefinition, holdAndReleaseFields } = planTemplate.getForReleaseCondition();
// Load the custom objects by their external id.
const customObjectsExternalIds = payments.map((p) => p.dealExternalId);
const customObjects = await this.dataConnection.getRepository<CustomObject>(CustomObject).find({
select: ['id', 'externalId', 'content'],
where: {
companyId: company.id,
definitionId: customObjectDefinition.id,
externalId: In(customObjectsExternalIds),
},
});
// Populate relations.
await this.relationshipService.fetchDatasetRowsRelations(
calculationParser,
userStatement,
dataset,
customObjects as DatasetRow[],
);
// And put the dataset into the userStatement.
userStatement.saveDataset(dataset, customObjects as DatasetRow[]);
// Compile object variables.
await planTemplate.traversePlan(
async ({ computedItem, parentDatasetId }) => {
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);
}
}
},
[dataset.id],
);
// Considering each payment associated to a datasetRow, fetch back the row
// and returns the diff.
const datasetRowsMap = keyBy(userStatement.getDatasetRows(dataset.id), 'externalId');
return payments.map((payment): NonNullable<PaymentMergeResult['paymentsToEdit']>[number] => {
const datasetRow =
payment.dealExternalId && payment.dealExternalId in datasetRowsMap && datasetRowsMap[payment.dealExternalId];
// If we don't have the datasetRow, it means that the custom object of that payment has been deleted.
// Return the payment with an error.
if (!datasetRow) {
this.logger.warn({
message: `Release - User ${calculationParser.getUser()!.email} - ${customObjectDefinition.machineName} ${
payment.dealExternalId
} (${payment.dealName}) not found`,
payment,
customObjectDefinition,
user: pick(calculationParser.getUser(), ['id', 'email']),
});
return {
newPayment: {
...payment,
error: {
type: PaymentErrorType.OBJECT_REMOVED,
customObjectMachineName: customObjectDefinition.machineName,
},
},
previousPayment: payment,
};
}
const newPayment = {
...payment,
id: payment.id,
// If the payment is released, replace the payment period for current.
paymentPeriodId: ReleaseService.isDatasetRowReleased(datasetRow, holdAndReleaseFields) ? period.id : null,
// Also update payment date and forecast if available.
paymentDate: ReleaseService.extractDateFromRow(datasetRow, holdAndReleaseFields.paymentDate || null),
forecastPaymentDate: ReleaseService.extractDateFromRow(
datasetRow,
holdAndReleaseFields.forecastPaymentDate || null,
),
// Clear the error if the payment was in error.
error: null,
};
return {
newPayment,
previousPayment: payment,
};
});
}
private static readonly isDatasetRowReleased = (row: DatasetRow, holdAndReleaseSettings: HoldAndReleaseSettings) => {
if (!holdAndReleaseSettings.releaseCondition) {
return false;
}
return (
row.content[holdAndReleaseSettings.releaseCondition] === 1 ||
row.content[holdAndReleaseSettings.releaseCondition] === true
);
};
/**
* Extract a date from a dataset while handling formatting and errors.
* @param row
* @param fieldName
*/
public static extractDateFromRow(row: DatasetRow, fieldName: string | null) {
if (!fieldName) {
return null;
}
const rawValue = row.content[fieldName];
if (!rawValue) {
return null;
}
assert(typeof rawValue === 'string' || typeof rawValue === 'number', 'Invalid type date conversion');
try {
return dateFromCalculationEngineToJsDate(rawValue);
} catch {
throw new ConfigurationError(`Date in field ${fieldName} is invalid.`);
}
}
}
|