All files / libs/data-capture/records/core/src/lib customObjects.service.ts

76.92% Statements 480/624
74.72% Branches 68/91
68.75% Functions 11/16
76.92% Lines 480/624

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 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 6251x 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 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 74x 74x 74x 74x 74x 74x     74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 1x 1x 73x 73x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x                                             43x 43x 43x 43x 43x 43x 43x 43x 43x 43x                                                                             43x 43x 43x           43x 43x 43x 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 16x 16x 7x 8x 3x 3x 7x 16x 16x 16x 16x     13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 16x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 13x 16x 1x 1x 13x 16x         13x 16x 16x 16x 16x 16x 16x 13x 13x 13x 16x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 23x 23x 23x 50x 23x 23x 10x 10x 10x 3x 3x 3x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x     5x 5x 5x 5x     5x 5x 5x 5x 5x 1x 1x 5x 5x     5x 5x 5x 5x 5x 5x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 5x 5x 1x 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 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 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 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 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { BadRequestException, HttpException, HttpStatus, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { escape, isEmpty, pick } from 'lodash-es';
import { paginate, type IPaginationOptions } from 'nestjs-typeorm-paginate';
import { match } from 'ts-pattern';
import {
  Brackets,
  ILike,
  In,
  Repository,
  type FindOptionsWhere,
  type SelectQueryBuilder,
  type WhereExpressionBuilder,
} from 'typeorm';
 
import {
  CustomObject,
  DataConnectionName,
  type Company,
  type CustomObjectDefinition,
  type Overwrite,
} from '@amalia/core/models';
import { ConditionsEnum, DateTypeCondition, toPaginatedResponse, type FilterType } from '@amalia/core/types';
import { PaginatedResponse } from '@amalia/core-http-types';
import { FieldTransformer, getCustomObjectExternalId, RowValidator } from '@amalia/data-capture/connectors/library';
import { RecordContent } from '@amalia/data-capture/connectors/types';
import { FormatsEnum, type Property } from '@amalia/data-capture/fields/types';
import { CustomObjectDefinitionsService } from '@amalia/data-capture/record-models/core';
import { OverwritesService } from '@amalia/data-correction/overwrites/core';
import { dayjs } from '@amalia/ext/dayjs';
import { StringUtils } from '@amalia/ext/string';
import { isUniqueViolationError } from '@amalia/ext/typeorm';
import { assert, toError } from '@amalia/ext/typescript';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
 
import { type QueryFilterGroupDto } from './dto/queryFilterGroup.dto';
import { CustomObjectsPurgeEvent } from './events/CustomObjectsPurgeEvent';
 
@Injectable()
export class CustomObjectsService {
  private readonly logger = new Logger(CustomObjectsService.name);
 
  public constructor(
    private readonly eventBus: EventBus,
    @InjectRepository(CustomObject, DataConnectionName)
    private readonly customObjectRepository: Repository<CustomObject>,
    private readonly objectDefinitionsService: CustomObjectDefinitionsService,
    private readonly overwriteService: OverwritesService,
  ) {}
 
  /**
   * Find customObject by id.
   * @id id of the customObject
   * @throws {NotFoundException}
   */
  public async findOne(company: Company, id: string): Promise<CustomObject> {
    const customObject = await this.customObjectRepository.findOneBy({
      companyId: company.id,
      id,
    });
    if (!customObject) {
      throw new NotFoundException();
    }
    return customObject;
  }
 
  /**
   * Find custom object by definition and externalId.
   * @param company
   * @param customObjectDefinitionId
   * @param externalId
   * @param throwIfNotFound
   * @throws {NotFoundException}
   */
  public async findByDefinitionAndExternalId(
    company: Company,
    customObjectDefinitionId: string,
    externalId: string,
    throwIfNotFound: boolean = true,
  ): Promise<CustomObject | null> {
    if (!customObjectDefinitionId || !externalId) {
      throw new NotFoundException('No param id');
    }
 
    const customObject = await this.customObjectRepository.findOne({
      where: {
        companyId: company.id,
        definitionId: customObjectDefinitionId,
        externalId,
      },
    });
 
    if (!customObject && throwIfNotFound) {
      throw new NotFoundException();
    }
 
    return customObject;
  }
 
  /**
   * Find related custom objects from a definition and an array of external ids
   *
   * @param company
   * @param customObjectDefinitionId
   * @param externalIds
   * @returns
   */
  public async findByDefinitionAndExternalIds(
    company: Company,
    customObjectDefinitionId: string,
    externalIds: string[],
  ): Promise<CustomObject[]> {
    if (!externalIds.length) {
      return [];
    }
    return this.customObjectRepository.find({
      where: {
        companyId: company.id,
        definitionId: customObjectDefinitionId,
        externalId: In(externalIds),
      },
    });
  }
 
  /**
   * Create new object.
   * @param company company of the new period
   * @param objectDefinition
   * @param row
   * @param updateExistingOverwrites
   * @throws {NotFoundException, @nestjs/common/BadRequestException, Error}
   */
  public async save(
    company: Company,
    objectDefinition: CustomObjectDefinition,
    row: object,
    updateExistingOverwrites: boolean = false,
  ): Promise<CustomObject> {
    const validatedRow = await RowValidator.validate(row, objectDefinition.properties);
    const externalId = getCustomObjectExternalId(objectDefinition, validatedRow);
    const name: string = validatedRow[objectDefinition.nameField!] as string;
 
    let existingCustomObject = await this.findByDefinitionAndExternalId(
      company,
      objectDefinition.id,
      externalId,
      false,
    );
 
    if (!existingCustomObject) {
      try {
        return await this.customObjectRepository.save({
          externalId,
          definitionId: objectDefinition.id,
          name,
          companyId: company.id,
          content: validatedRow,
        });
      } catch (err) {
        if (!isUniqueViolationError(err)) {
          // Error is catch in parent try/catch, query runner state is managed there
          throw err;
        }

        // Refetch the original custom object
        existingCustomObject = await this.findByDefinitionAndExternalId(company, objectDefinition.id, externalId);

        if (!existingCustomObject) {
          throw new Error('Could not fetch the duplicate custom object when importing');
        }
      }
    }
 
    try {
      assert(existingCustomObject, 'Custom Object does not exist');
 
      existingCustomObject.content = validatedRow;
 
      // Manage overrides
 
      // If overwrites exist update the content
      if (updateExistingOverwrites) {
        const overwrites = await this.overwriteService.findByCustomObjectAndStatementAndVariableAndFilter(
          company,
          existingCustomObject,
          undefined,
          undefined,
          false,
          true,
        );

        await Promise.all(
          overwrites.map((overwrite: Overwrite) => {
            const overwrittenFieldValue = isEmpty(overwrite.overwriteValue)
              ? null
              : FieldTransformer.transformField(
                  validatedRow,
                  overwrite.field,
                  (objectDefinition.properties[overwrite.field] as Property).format,
                )![overwrite.field];

            // Updating the overwrite source value with the value of the new row
            const finalOverwrite = {
              ...overwrite,
              sourceValue: {
                ...(overwrite.sourceValue as object),
                [overwrite.field]: overwrittenFieldValue,
              },
            };

            // Updating the value of the new row with the overwritten value
            existingCustomObject!.content[overwrite.field] = (overwrite.overwriteValue as RecordContent)[
              overwrite.field
            ];

            // Updates the overwrites.
            return this.overwriteService.update(company, finalOverwrite);
          }),
        );
      }
 
      existingCustomObject = await this.customObjectRepository.save(existingCustomObject);
    } catch (err) {
      const error = toError(err);
      this.logger.error({ message: 'Error on saving custom object', error, company: pick(company, ['id', 'name']) });

      throw new HttpException('Error on saving custom object, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
    }
 
    return existingCustomObject;
  }
 
  /**
   * Find custom Objects of a company with pagination
   * @param definition
   * @param company
   * @param search
   * @param sortColumn
   * @param desc
   * @param options pagination options
   * @param filters
   * @param overwrite boolean to get overwrites with custom Objects
   * @param externalIds
   */
  public async paginate(
    definition: string,
    company: Company,
    options: IPaginationOptions,
    search?: string,
    sortColumn?: string,
    desc?: boolean,
    filters?: QueryFilterGroupDto[],
    overwrite: boolean = false,
    externalIds?: string,
  ): Promise<PaginatedResponse<CustomObject & { overwrites?: Overwrite[] }>> {
    const objectDefinition = await this.objectDefinitionsService.findByMachineName(company, definition);
 
    assert(objectDefinition, new NotFoundException(`Custom object definition not found: ${definition}`));
 
    // --------- Input validation ------------------
    // Ensure that filters use a valid property. Otherwise, it's a bad format.
    filters?.forEach((filterGroup) => {
      (filterGroup.conditions ?? []).forEach((filter) => {
        if (!objectDefinition.properties[filter.property]) {
          throw new BadRequestException('Some filter properties do not exist');
        }
      });
    });
 
    // Same for sortColumn
    if (sortColumn && !objectDefinition.properties[sortColumn]) {
      throw new BadRequestException('Column used for sorting does not exist');
    }
 
    // --------- Build and run dynamic query ------------------
    const queryBuilder = this.customObjectRepository.createQueryBuilder('object');
 
    queryBuilder.where('object.companyId = :companyId', {
      companyId: company.id,
    });
    queryBuilder.andWhere('object.definitionId = :definitionId', {
      definitionId: objectDefinition.id,
    });
 
    if (filters && filters.length > 0) {
      queryBuilder.andWhere(
        new Brackets((qb: WhereExpressionBuilder) => {
          filters.forEach((filterGroup, filterIndex) => {
            qb[filterIndex === 0 ? 'where' : 'orWhere'](
              new Brackets((qbAnd: WhereExpressionBuilder) => {
                (filterGroup.conditions ?? []).forEach((filter, subFilterIndex) => {
                  const field = objectDefinition.properties[filter.property];
                  if (field) {
                    CustomObjectsService.addWhereClauses(filter, qbAnd, field, filterIndex, subFilterIndex);
                  }
                });
              }),
            );
          });
        }),
      );
    }
 
    if (search) {
      this.setFullTextSearch(queryBuilder, search);
    }
 
    if (externalIds) {
      queryBuilder.andWhere('object.externalId IN (:...externalIds)', {
        externalIds: externalIds.split(','),
      });
    }
 
    const sortDirection: 'ASC' | 'DESC' = desc ? 'DESC' : 'ASC';
    const sort = sortColumn ? `content->'${escape(sortColumn)}'` : 'id';
 
    queryBuilder.orderBy(`object.${sort}`, sortDirection);
 
    const paginatedResult = await paginate<CustomObject>(queryBuilder, options).then(toPaginatedResponse);
 
    // --------- Apply overwrites ------------------
    // If we want overwrites
    if (overwrite) {
      // For overwrites, we can't fetch them at the same time, because no joins, and pagination does not allow for leftJoinAndSelect
      const overwrites = await this.overwriteService.findAllForDefinitionByExternalIds(
        company,
        objectDefinition.id,
        paginatedResult.items.map((co) => co.externalId),
        false,
        null,
        false,
      );
 
      // Then extend the response with the extended custom objects
      return {
        ...paginatedResult,
        items: paginatedResult.items.map((customObject: CustomObject) => ({
          ...customObject,
          overwrites: overwrites.filter(
            (ov) =>
              ov.appliesToExternalId === customObject.externalId &&
              ov.appliesToDefinitionId === customObject.definitionId,
          ),
        })),
      };
    }
 
    return paginatedResult;
  }
 
  private static addWhereClauses(
    filter: FilterType,
    qbAnd: WhereExpressionBuilder,
    field: Property,
    index: number,
    subIndex: number,
  ) {
    // If filter.property is not formed as a machine name, it's probably an injection
    if (!StringUtils.isMachineName(filter.property)) {
      throw new BadRequestException(`Property "${filter.property}" of the filter is not valid`);
    }
 
    switch (filter.condition) {
      case ConditionsEnum.booleanIsFalse:
      case ConditionsEnum.booleanIsTrue:
        CustomObjectsService.addBooleanWhereClause(filter, qbAnd);
        break;
      case ConditionsEnum.dateTimeAfter:
      case ConditionsEnum.dateTimeAfterOrEqual:
      case ConditionsEnum.dateTimeBefore:
      case ConditionsEnum.dateTimeBeforeOrEqual:
      case ConditionsEnum.dateTimeEquals:
        CustomObjectsService.addDateWhereClause(filter, qbAnd);
        break;
      case ConditionsEnum.doesNotExist:
      case ConditionsEnum.exists:
        CustomObjectsService.addExistWhereClause(filter, field, qbAnd);
        break;
      case ConditionsEnum.numberEquals:
      case ConditionsEnum.numberNotEquals:
      case ConditionsEnum.numberGreaterThan:
      case ConditionsEnum.numberGreaterThanOrEqual:
      case ConditionsEnum.numberLessThan:
      case ConditionsEnum.numberLessThanOrEqual:
        CustomObjectsService.addNumberWhereClause(filter, field, qbAnd, index, subIndex);
        break;
 
      case ConditionsEnum.textContains:
      case ConditionsEnum.textDoesNotContain:
      case ConditionsEnum.textExactlyMatches:
      case ConditionsEnum.textDoesNotExactlyMatch:
      case ConditionsEnum.textStartsWith:
      case ConditionsEnum.textDoesNotStartWith:
      case ConditionsEnum.textEndsWith:
      case ConditionsEnum.textDoesNotEndWith:
      case ConditionsEnum.textIsIn:
      case ConditionsEnum.textIsNotIn:
        CustomObjectsService.addTextWhereClause(filter, qbAnd, index, subIndex);
        break;
    }
  }
 
  private static addBooleanWhereClause(filter: FilterType, qbAnd: WhereExpressionBuilder) {
    const booleanVal = filter.condition === ConditionsEnum.booleanIsTrue;
    qbAnd.andWhere(` object.content::jsonb @> '{"${filter.property}":${booleanVal}}'`);
  }
 
  private static addTextWhereClause(
    filter: FilterType,
    qbAnd: WhereExpressionBuilder,
    index: number,
    subIndex: number,
  ) {
    const textOperator = match(filter.condition)
      .with(ConditionsEnum.textContains, ConditionsEnum.textStartsWith, ConditionsEnum.textEndsWith, () => 'LIKE')
      .with(
        ConditionsEnum.textDoesNotContain,
        ConditionsEnum.textDoesNotStartWith,
        ConditionsEnum.textDoesNotEndWith,
        () => 'NOT LIKE',
      )
      .with(ConditionsEnum.textExactlyMatches, () => '=')
      .with(ConditionsEnum.textDoesNotExactlyMatch, () => '!=')
      .with(ConditionsEnum.textIsIn, () => 'IN')
      .with(ConditionsEnum.textIsNotIn, () => 'NOT IN')
      .otherwise(() => {
        throw new BadRequestException('Invalid text condition');
      });
 
    const filterValue = match(filter.condition)
      .with(ConditionsEnum.textContains, ConditionsEnum.textDoesNotContain, () => `%${filter.value}%`)
      .with(
        ConditionsEnum.textExactlyMatches,
        ConditionsEnum.textDoesNotExactlyMatch,
        ConditionsEnum.textIsNotIn,
        ConditionsEnum.textIsIn,
        () => `${filter.value}`,
      )
      .with(ConditionsEnum.textStartsWith, ConditionsEnum.textDoesNotStartWith, () => `${filter.value}%`)
      .with(ConditionsEnum.textEndsWith, ConditionsEnum.textDoesNotEndWith, () => `%${filter.value}`)
      .otherwise(() => {
        throw new BadRequestException('Invalid text condition');
      });
 
    qbAnd.andWhere(` "object"."content"->>'${filter.property}' ${textOperator} :filterValue_${index}_${subIndex}`, {
      [`filterValue_${index}_${subIndex}`]: filterValue,
    });
  }
 
  private static addNumberWhereClause(
    filter: FilterType,
    field: Property,
    qbAnd: WhereExpressionBuilder,
    index: number,
    subIndex: number,
  ) {
    const numberOperator = match(filter.condition)
      .with(ConditionsEnum.numberEquals, () => '=')
      .with(ConditionsEnum.numberNotEquals, () => '!=')
      .with(ConditionsEnum.numberGreaterThan, () => '>')
      .with(ConditionsEnum.numberGreaterThanOrEqual, () => '>=')
      .with(ConditionsEnum.numberLessThan, () => '<')
      .with(ConditionsEnum.numberLessThanOrEqual, () => '<=')
      .otherwise(() => {
        throw new BadRequestException('Invalid number condition');
      });
 
    // if currency ?
    if (field.format === FormatsEnum.currency) {
      qbAnd.andWhere(
        ` ("object"."content"->'${filter.property}'->>'value')::float ${numberOperator} :filterValue_${index}_${subIndex}`,
        { [`filterValue_${index}_${subIndex}`]: filter.value },
      );
    } else {
      qbAnd.andWhere(
        ` ("object"."content"->>'${filter.property}')::float ${numberOperator} :filterValue_${index}_${subIndex}`,
        { [`filterValue_${index}_${subIndex}`]: filter.value },
      );
    }
  }
 
  private static addExistWhereClause(filter: FilterType, field: Property, qbAnd: WhereExpressionBuilder) {
    const NOT = filter.condition === ConditionsEnum.doesNotExist ? '' : 'NOT';
    // if currency ?
    if (field.format === FormatsEnum.currency) {
      qbAnd.andWhere(` "object"."content"->'${filter.property}'->>'value' IS ${NOT} NULL`);
    } else {
      qbAnd.andWhere(` "object"."content"->>'${filter.property}' IS ${NOT} NULL`);
    }
  }
 
  private static addDateWhereClause(filter: FilterType, qbAnd: WhereExpressionBuilder) {
    if (filter.value) {
      const operator = match(filter.condition)
        .with(ConditionsEnum.dateTimeEquals, () => '=')
        .with(ConditionsEnum.dateTimeAfter, () => '>')
        .with(ConditionsEnum.dateTimeAfterOrEqual, () => '>=')
        .with(ConditionsEnum.dateTimeBefore, () => '<')
        .with(ConditionsEnum.dateTimeBeforeOrEqual, () => '<=')
        .otherwise(() => {
          throw new BadRequestException('Invalid date condition');
        });
 
      // IF TIME BASED, compare to today
      if (filter.dateTypeCondition === DateTypeCondition.TIME_BASED) {
        const formattedDate =
          filter.condition === ConditionsEnum.dateTimeAfter || filter.condition === ConditionsEnum.dateTimeAfterOrEqual
            ? dayjs().subtract(+filter.value, 'days').format('YYYYMMDD')
            : dayjs().add(+filter.value, 'days').format('YYYYMMDD');
 
        qbAnd.andWhere(
          `  ('${formattedDate}')::timestamp` +
            ` ${operator} (TO_DATE( "object"."content"->>'${filter.property}', 'YYYY-MM-DD'))::timestamp`,
        );
      } else {
        // Otherwise compare to the manual entry date
        qbAnd.andWhere(
          ` (TO_DATE( "object"."content"->>'${filter.property}', 'YYYY-MM-DD'))::timestamp` +
            ` ${operator} ('${dayjs(filter.value.toString(), 'YYYY-MM-DD').format('YYYYMMDD')}')::timestamp`,
        );
      }
    }
  }
 
  public async bulkDelete(company: Company, definitionId: string, authenticatedContext: AuthenticatedContext) {
    try {
      const customObject = await this.objectDefinitionsService.findById(company, definitionId);
      const result = await this.customObjectRepository.delete({
        companyId: company.id,
        definitionId,
      });
      await this.eventBus.publish(
        new CustomObjectsPurgeEvent({
          authenticatedContext,
          object: RecordObject.CUSTOM_OBJECT,
          type: RecordType.EDIT,
          values: {
            what: 'purge',
            target: { id: customObject.id, name: customObject.name },
          },
        }),
      );
 
      return result;
    } catch (e: unknown) {
      const error = toError(e);
      this.logger.error({ message: `Error on purging custom object: ${error.message}`, error });
      throw new HttpException('Error on purging custom object, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
 
  /**
   * Delete objects.
   * @param company company
   * @param id id
   */
  public async delete(company: Company, id: string) {
    const customObject = await this.customObjectRepository.findOneBy({
      id,
      companyId: company.id,
    });

    if (!customObject) {
      throw new NotFoundException();
    }

    // Remove the custom object.
    return this.customObjectRepository.delete(customObject.id);
  }
 
  /**
   * Search custom object by external id or name.
   * This function search data across all owners.
   * (one user can retrieve opportunities from another user according to product specifications)
   * Only used by forecast for now.
   * Retrieve max 10 results.
   * @param company
   * @param definitionName
   * @param search
   */
  public async quickSearch(company: Company, definitionName: string, search?: string) {
    const objectDefinition = await this.objectDefinitionsService.findByMachineName(company, definitionName);
 
    assert(objectDefinition, new NotFoundException(`Object definition ${definitionName} not found.`));
 
    const findConditions: FindOptionsWhere<CustomObject>[] = [
      {
        companyId: company.id,
        definitionId: objectDefinition.id,
        externalId: search ?? '',
      },
      {
        companyId: company.id,
        definitionId: objectDefinition.id,
        name: ILike(`%${search ?? ''}%`),
      },
    ];
 
    return this.customObjectRepository.find({
      where: findConditions,
      order: {
        name: 'ASC',
      },
      take: 10,
    });
  }
 
  private setFullTextSearch(queryBuilder: SelectQueryBuilder<CustomObject>, search: string) {
    const fullTextSearchParts = search.split(' ').filter(Boolean);
 
    if (fullTextSearchParts.length) {
      const fullTextSearch = fullTextSearchParts.join(' & ');
      queryBuilder.andWhere(
        "(to_tsvector('english', object.content) @@ to_tsquery(:search_fulltext) OR object.externalId ilike :search)",
        {
          search_fulltext: `*${fullTextSearch}:*`,
          search: `%${search}%`,
        },
      );
    }
  }
}