import { Injectable } from '@nestjs/common'; import { EntityServiceImpl } from './entity-service-impl.service'; import { EntityMasterRepository } from '../repository/entity-master.repository'; import { EntityRelationRepository } from '../repository/entity-relation.repository'; @Injectable() export class EntityRelationService extends EntityServiceImpl { constructor(private entityMasterRepo: EntityMasterRepository, private entityRelationRepository: EntityRelationRepository) { super(); } async getEntityRelations( entityType: string, loggedInUser: any, includeSelf = false, ): Promise { const entityRelationRepo = this.reflectionHelper.getRepoService('EntityRelation'); const relations = await entityRelationRepo .createQueryBuilder('er') .select([ 'er.name AS label', 'er.target_entity_type AS value', 'er.id AS id', ]) .where('er.source_entity_type = :entityType', { entityType }) .andWhere('er.enterprise_id = :entId', { entId: loggedInUser.enterprise_id }) .getRawMany(); if (includeSelf) { const entity = await this.entityMasterRepo.getEntityByMappedEntityType(entityType, loggedInUser.enterprise_id); if (entity) { relations.unshift({ label: entity.name, value: entityType, id: null, // or some special marker }); } } return relations; } async getRelatedEntityIds( sourceEntity: string, targetEntity: string, targetIds: number[], enterpriseId: number, ): Promise { if (!targetIds.length) return []; const entityRelationRepo = this.reflectionHelper.getRepoService('EntityRelationData'); const rows = await entityRelationRepo .createQueryBuilder('erd') .select('DISTINCT erd.source_entity_id', 'source_entity_id') .where('erd.source_entity_type = :sourceEntity', { sourceEntity }) .andWhere('erd.target_entity_type = :targetEntity', { targetEntity }) .andWhere('erd.target_entity_id IN (:...targetIds)', { targetIds }) .andWhere('erd.enterprise_id = :enterpriseId', { enterpriseId }) .getRawMany(); return rows.map((r) => Number(r.source_entity_id)); } async findBySourceEntityTypeAndTargetEntityType(source_entity_type: string, target_entity_type: string) { return await this.entityRelationRepository.findBySourceEntityTypeAndTargetEntityType( source_entity_type, target_entity_type ); } }