All files / libs/payout-definition/designer/core/src/lib/virtualCustomObjectDefinition virtualCustomObjectDefinition.service.ts

99.01% Statements 404/408
84.21% Branches 32/38
100% Functions 10/10
99.01% Lines 404/408

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 4091x 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 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 1x 1x 1x 10x 10x 10x 10x 10x 1x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 1x 1x 189x 189x 189x 189x 189x 189x 189x 189x 69x 69x 189x 61x 61x 189x 59x 59x 189x     189x 189x 189x 189x 1x 1x 189x 189x 189x 189x 189x 189x 189x     189x 189x 189x 1x 1x 69x 69x 69x 24x 24x 24x 24x 24x 24x 69x 69x 69x 24x 24x 24x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 26x 26x 26x 69x 69x 10x 10x 10x 69x 69x 69x 1x 1x 61x 61x 24x 24x 24x 24x 24x 24x 61x 61x 61x 61x 61x 26x 26x 26x 26x 24x 24x 24x 24x 24x 24x 24x 24x 2x 2x 2x 2x 2x 2x 2x 2x 26x 2x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 4x 4x 4x 4x 26x 26x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 1x 1x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 3419x 3419x 3419x 3419x 189x 189x 189x 189x 189x 189x 189x 1x  
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { keyBy, uniqBy } from 'lodash-es';
import { In, Raw, Repository } from 'typeorm';
 
import {
  DataConnectionName,
  MetricMetadata,
  MetricMetadataType,
  Plan,
  RuleAssignment,
  type Company,
} from '@amalia/core/models';
import { FormatsEnum } from '@amalia/data-capture/fields/types';
import {
  CustomObjectDefinitionType,
  HUMAN_READABLE_VIRTUAL_CUSTOM_OBJECT_DEFINITION,
  VirtualCustomObjects,
  type VirtualCustomObjectDefinition,
} from '@amalia/data-capture/record-models/types';
import { assert } from '@amalia/ext/typescript';
 
interface VirtualField {
  label: string;
  name: string;
  type: FormatsEnum;
  baseMachineName?: string;
}
 
const COMMON_METRICS_FIELDS = [
  {
    label: 'User',
    name: 'userId',
    type: FormatsEnum.text,
  },
  {
    label: 'User First Name',
    name: 'userFirstName',
    type: FormatsEnum.text,
  },
  {
    label: 'User Last Name',
    name: 'userLastName',
    type: FormatsEnum.text,
  },
  {
    label: 'User External Id',
    name: 'userExternalId',
    type: FormatsEnum.text,
  },
  {
    label: 'User Email',
    name: 'userEmail',
    type: FormatsEnum.text,
  },
  {
    label: 'Statement',
    name: 'statementId',
    type: FormatsEnum.text,
  },
  {
    label: 'Plan',
    name: 'planId',
    type: FormatsEnum.text,
  },
  {
    label: 'Plan Name',
    name: 'planName',
    type: FormatsEnum.text,
  },
  {
    label: 'Rule Id',
    name: 'ruleId',
    type: FormatsEnum.text,
  },
  {
    label: 'Rule Name',
    name: 'ruleName',
    type: FormatsEnum.text,
  },
  {
    label: 'Rule Type',
    name: 'ruleType',
    type: FormatsEnum.text,
  },
  {
    label: 'Period',
    name: 'periodId',
    type: FormatsEnum.text,
  },
  {
    label: 'Period Name',
    name: 'periodName',
    type: FormatsEnum.text,
  },
  {
    label: 'Period Start Date',
    name: 'periodStartDate',
    type: FormatsEnum.date,
  },
  {
    label: 'Period End Date',
    name: 'periodEndDate',
    type: FormatsEnum.date,
  },
  {
    label: 'Team Id',
    name: 'teamId',
    type: FormatsEnum.text,
  },
  {
    label: 'Team Name',
    name: 'teamName',
    type: FormatsEnum.text,
  },
];
 
@Injectable()
export class VirtualCustomObjectDefinitionService {
  public constructor(
    @InjectRepository(MetricMetadata, DataConnectionName)
    private readonly metricMetadataRepository: Repository<MetricMetadata>,
    @InjectRepository(RuleAssignment)
    private readonly ruleAssignmentRepository: Repository<RuleAssignment>,
  ) {}
 
  public async getAllVirtualCustomObjectDefinitions(
    company: Company,
    planIds: Plan['id'][],
  ): Promise<VirtualCustomObjectDefinition[]> {
    return (
      await Promise.all([
        this.getVirtualCustomObjectDefinitionOrFail(company, VirtualCustomObjects.STATEMENT_METRIC, planIds),
        this.getVirtualCustomObjectDefinitionOrFail(company, VirtualCustomObjects.OBJECT_METRIC, planIds),
        this.getVirtualCustomObjectDefinitionOrFail(company, VirtualCustomObjects.QUOTA, planIds),
      ])
    ).toSorted((a, b) => a.name.localeCompare(b.name));
  }
 
  public async getVirtualCustomObjectDefinition(
    company: Company,
    machineName: VirtualCustomObjects | string,
    planIds: Plan['id'][],
  ): Promise<VirtualCustomObjectDefinition | null> {
    let fields: VirtualField[];
 
    switch (machineName) {
      case VirtualCustomObjects.STATEMENT_METRIC:
        fields = await this.buildForStatementMetric(company, planIds);
        break;
      case VirtualCustomObjects.OBJECT_METRIC:
        fields = await this.buildForObjectMetric(company, planIds);
        break;
      case VirtualCustomObjects.QUOTA:
        fields = await this.buildForQuota();
        break;
      default: {
        return null;
      }
    }
 
    return VirtualCustomObjectDefinitionService.createVirtualCustomObject(machineName, fields);
  }
 
  public async getVirtualCustomObjectDefinitionOrFail(
    company: Company,
    machineName: VirtualCustomObjects,
    planIds: Plan['id'][],
  ): Promise<VirtualCustomObjectDefinition> {
    const virtualCustomObjectDefinition = await this.getVirtualCustomObjectDefinition(company, machineName, planIds);
 
    if (!virtualCustomObjectDefinition) {
      throw new NotFoundException(`Virtual Custom Object Definition not implemented for type ${machineName}`);
    }
 
    return virtualCustomObjectDefinition;
  }
 
  private async buildForStatementMetric(company: Company, planIds: Plan['id'][]): Promise<VirtualField[]> {
    const [metricMetadata, ruleAssignments] = await Promise.all([
      planIds.length
        ? this.metricMetadataRepository.find({
            where: {
              companyId: company.id,
              metadataType: In([MetricMetadataType.QUOTA, MetricMetadataType.VARIABLE]),
              planIds: Raw((alias) => `${alias} ?| array[:...planIds]`, { planIds }),
            },
          })
        : [],
      planIds.length
        ? this.ruleAssignmentRepository.find({
            where: { company: { id: company.id }, planId: In(planIds) },
            relations: ['rule'],
          })
        : [],
    ]);
 
    const rules = uniqBy(
      ruleAssignments.map((ruleAssignment) => ruleAssignment.rule),
      'id',
    );
 
    return [
      ...COMMON_METRICS_FIELDS,
      {
        label: 'Total',
        name: 'total',
        type: FormatsEnum.currency,
      },
      ...rules.map((rule) => ({
        type: FormatsEnum.currency,
        name: `rule_${rule.machineName}`,
        label: rule.name,
      })),
      ...metricMetadata.map((m) => ({
        name: m.key,
        label: m.label,
        type: m.format,
      })),
    ];
  }
 
  private async buildForObjectMetric(company: Company, planIds: Plan['id'][]): Promise<VirtualField[]> {
    const metricMetadataFindResult = planIds.length
      ? await this.metricMetadataRepository.find({
          where: {
            companyId: company.id,
            metadataType: In([MetricMetadataType.PROPERTY, MetricMetadataType.FIELD]),
            planIds: Raw((alias) => `${alias} ?| array[:...planIds]`, { planIds }),
          },
        })
      : [];
 
    const metricMetadataFieldsGroupedByMachineName = Object.groupBy(metricMetadataFindResult, (m) => m.key);
 
    const metricMetadata = Object.entries(metricMetadataFieldsGroupedByMachineName).flatMap(([machineName, fields]) => {
      assert(fields, 'fields cannot be nullish');
 
      const firstField = fields[0];
      if (fields.length === 1) {
        return [
          {
            name: firstField.key,
            label: firstField.label,
            type: firstField.format,
          },
        ];
      }
 
      // case when we have multiple fields with the same machine name
      const fieldLabel = firstField.label;
      const allFieldsFormats = fields.map((metadata) => metadata.format);
 
      // Downcast to number if we don't see any text or date.
      const downcastFormatTarget =
        allFieldsFormats.includes(FormatsEnum.text) ||
        allFieldsFormats.includes(FormatsEnum.date) ||
        allFieldsFormats.includes(FormatsEnum['date-time'])
          ? FormatsEnum.text
          : FormatsEnum.number;
 
      return [
        {
          label: fieldLabel,
          type: downcastFormatTarget,
          name: machineName,
        },
        ...allFieldsFormats.map((format) => ({
          type: format,
          name: `${machineName}_${format}`,
          label: `${fieldLabel} (${format})`,
          baseMachineName: machineName,
        })),
      ];
    });
 
    return metricMetadata.concat([
      ...COMMON_METRICS_FIELDS,
      {
        label: 'Row External Id',
        name: 'rowExternalId',
        type: FormatsEnum.text,
      },
      {
        label: 'Name',
        name: 'rowName',
        type: FormatsEnum.text,
      },
      {
        label: 'Custom Object Machine Name',
        name: 'customObjectDefinitionMachineName',
        type: FormatsEnum.text,
      },
      {
        label: 'Filter Id',
        name: 'filterId',
        type: FormatsEnum.text,
      },
      {
        label: 'Filter Name',
        name: 'filterName',
        type: FormatsEnum.text,
      },
      {
        label: 'Filter Machine Name',
        name: 'filterMachineName',
        type: FormatsEnum.text,
      },
    ]);
  }
 
  private buildForQuota(): Promise<VirtualField[]> {
    return Promise.resolve([
      {
        label: 'Machine Name',
        name: 'machineName',
        type: FormatsEnum.text,
      },
      {
        label: 'Variable Name',
        name: 'name',
        type: FormatsEnum.text,
      },
      {
        label: 'Variable Type',
        name: 'type',
        type: FormatsEnum.text,
      },
      {
        label: 'User',
        name: 'userId',
        type: FormatsEnum.text,
      },
      {
        label: 'User full name',
        name: 'userFullName',
        type: FormatsEnum.text,
      },
      {
        label: 'User last name',
        name: 'userLastName',
        type: FormatsEnum.text,
      },
      {
        label: 'User first name',
        name: 'userFirstName',
        type: FormatsEnum.text,
      },
      {
        label: 'User email',
        name: 'userEmail',
        type: FormatsEnum.text,
      },
      {
        label: 'User External Id',
        name: 'userExternalId',
        type: FormatsEnum.text,
      },
      {
        label: 'Start Date',
        name: 'startDate',
        type: FormatsEnum.date,
      },
      {
        label: 'End Date',
        name: 'endDate',
        type: FormatsEnum.date,
      },
      {
        label: 'Value',
        name: 'value',
        type: FormatsEnum.text,
      },
    ]);
  }
 
  /**
   * Transform given object to something that looks like a custom object definition.
   *
   * It maps field formats then build a JSON Schema.
   *
   * @param machineName
   * @param virtualFields
   * @private
   */
  private static createVirtualCustomObject(
    machineName: VirtualCustomObjects,
    virtualFields: VirtualField[],
  ): VirtualCustomObjectDefinition {
    return {
      id: machineName,
      name: HUMAN_READABLE_VIRTUAL_CUSTOM_OBJECT_DEFINITION[machineName] || machineName,
      nameField: null,
      machineName,
      properties: keyBy(
        virtualFields.map((vf) => ({
          name: vf.label,
          machineName: vf.name,
          format: vf.type,
          baseMachineName: vf.baseMachineName,
        })),
        'machineName',
      ),
      type: CustomObjectDefinitionType.VIRTUAL,
      externalIds: [],
    };
  }
}