All files / src/repositories company.repository.ts

46.43% Statements 26/56
0% Branches 0/24
16.67% Functions 1/6
44.44% Lines 24/54

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 1741x 1x                       1x 1x                     1x                     1x                                 156x   156x   156x   156x   156x   156x   156x 156x 156x 156x 156x 156x 156x 156x         156x 156x 156x 156x                                                                                                                                                                                          
import { Getter, inject } from '@loopback/core';
import {
  AnyObject,
  BelongsToAccessor,
  Count,
  HasManyThroughRepositoryFactory,
  HasOneRepositoryFactory,
  Options,
  repository,
  Where,
  HasManyRepositoryFactory,
} from '@loopback/repository';
import { CompanyLicenceRepository, CompanyPersonaRepository, CountryRepository, UserViewRepository } from '.';
import { LogChainDataSource } from '../datasources';
import {
  Company,
  CompanyLocation,
  CompanyPersona,
  CompanyRelations,
  Country,
  Persona,
  User,
  CompanyRegulatory,
  CompanyLicence,
} from '../models';
import { BaseCrudRepository } from './base-crud.repository.base';
import { PersonaRepository } from './persona.repository';
import { CompanyRegulatoryRepository } from './company-regulatory.repository';
 
interface CompanyWithPersona {
  id: number;
  status: number;
  identifier: string;
  persona_ids: number[];
}
 
export class CompanyRepository extends BaseCrudRepository<Company, typeof Company.prototype.id, CompanyRelations> {
  public readonly creator: BelongsToAccessor<User, typeof User.prototype.id>;
  public readonly modifier: BelongsToAccessor<User, typeof User.prototype.id>;
  public readonly main_contact: HasOneRepositoryFactory<User, typeof User.prototype.id>;
  public readonly personas: HasManyThroughRepositoryFactory<
    Persona,
    typeof Persona.prototype.id,
    CompanyPersona,
    typeof Company.prototype.id
  >;
  public readonly country: HasOneRepositoryFactory<Country, typeof CompanyLocation.prototype.id>;
  public readonly regulations: HasManyRepositoryFactory<CompanyRegulatory, typeof Company.prototype.id>;
  public readonly licences: HasManyRepositoryFactory<CompanyLicence, typeof CompanyLicence.prototype.id>;
 
  constructor(
    @inject('datasources.logchain') dataSource: LogChainDataSource,
    @repository.getter('CompanyPersonaRepository')
    protected comp_persona_repo_getter: Getter<CompanyPersonaRepository>,
    @repository.getter('PersonaRepository')
    protected persona_repo_getter: Getter<PersonaRepository>,
    @repository.getter('UserViewRepository')
    protected user_repo_getter: Getter<UserViewRepository>,
    @repository.getter('CountryRepository')
    protected country_repo_getter: Getter<CountryRepository>,
    @repository.getter('CompanyRegulatoryRepository')
    protected companyRegulatoryRepositoryGetter: Getter<CompanyRegulatoryRepository>,
    @repository.getter('CompanyLicenceRepository')
    protected companyLicenceRepositoryGetter: Getter<CompanyLicenceRepository>,
  ) {
    super(Company, dataSource);
    this.regulations = this.createHasManyRepositoryFactoryFor('regulations', companyRegulatoryRepositoryGetter);
    this.registerInclusionResolver('regulations', this.regulations.inclusionResolver);
    this.licences = this.createHasManyRepositoryFactoryFor('licences', companyLicenceRepositoryGetter);
    this.registerInclusionResolver('licences', this.licences.inclusionResolver);
    this.creator = this.createBelongsToAccessor('creator', user_repo_getter);
    this.modifier = this.createBelongsToAccessor('modifier', user_repo_getter);
    this.personas = this.createHasManyThroughRepositoryFactoryFor(
      'personas',
      persona_repo_getter,
      comp_persona_repo_getter,
    );
    this.main_contact = this.createHasOneRepositoryFactoryFor('main_contact', user_repo_getter);
    this.registerInclusionResolver('main_contact', this.main_contact.inclusionResolver);
    this.country = this.createHasOneRepositoryFactoryFor('country', country_repo_getter);
    this.registerInclusionResolver('country', this.country.inclusionResolver);
  }
 
  /**
   * Delete all company by where.
   * - Override deleteAll from DefaultCrudRepository to do:
   *  + Cleanup S3 after delete company.
   *  + Cleanup HLF after delete company.
   *  + Any logic related to business should be done at the Service level (ex. Send Email).
   * @param where The where object
   * @param options The options object.
   */
  async deleteAll(where?: Where<Company>, options?: Options): Promise<Count> {
    let deleted_company = options?.deleted_company;
    const resl = await super.deleteAll(where, options);
 
    // If nothing was deleted and no deleted_company info, return the result as is
    if (!resl.count && !deleted_company) {
      return { count: 0 };
    }
 
    // If deleted_company is not provided, try to find the company that matches the where clause
    if (!deleted_company) {
      const foundCompany = await this.findOne({ where });
      if (!foundCompany) {
        // If no company found, return the result as is
        return { count: 0 };
      }
      deleted_company = foundCompany;
    }
 
    // Ensure deleted_company is always an array for further processing
    if (!Array.isArray(deleted_company)) {
      deleted_company = [deleted_company];
    }
 
    setImmediate(() => {
      const images: string[] = [];
      for (const company of deleted_company) {
        if (company?.logo) {
          images.push(company.logo);
        }
      }
 
      // delete company logo
      // eslint-disable-next-line @typescript-eslint/no-floating-promises
      this.s3_service.deleteObjects(images).catch(err => {
        console.log(err);
      });
    });
 
    // Return the actual count of deleted companies
    return { count: deleted_company.length };
  }
 
  /**
   * Get mapping of company and personas.
   * @param ids The array id or identifier of companies.
   * @param options The options.
   */
  async getPersonasByIdOrIdentifier(ids: number[] | string[], options?: Options): Promise<AnyObject> {
    let field = '';
    if (typeof ids[0] === 'number') {
      field = 'comp.id';
    }
 
    if (typeof ids[0] === 'string') {
      field = 'comp.identifier';
    }
 
    const sql_exp = this.buildInClause(field, ids);
    const sql = `
      SELECT
        comp.id as id,
        comp.status as status,
        comp.identifier as identifier,
        array_agg(comp_per.persona_id) as persona_ids
      FROM
        companies AS comp
        LEFT JOIN company_personas AS comp_per ON comp.ID = comp_per.company_id
      WHERE ${sql_exp}
      GROUP BY comp.id;`;
    const resl = await this.execute(sql, ids, options);
    return (resl as CompanyWithPersona[]).reduce((agg: AnyObject, current: CompanyWithPersona) => {
      agg[current.identifier] = {
        id: current.id,
        status: current.status,
        persona_ids: current.persona_ids,
      };
      return agg;
    }, {} as AnyObject);
  }
}