import { Injectable } from '@nestjs/common'; import { EntityServiceImpl } from 'src/module/meta/service/entity-service-impl.service'; import { DataSource } from 'typeorm'; import { LinkedAttributes } from '../entity/linked_attribute.entity'; import { FilterService } from 'src/module/filter/service/filter.service'; @Injectable() export class LinkedAttributesService extends EntityServiceImpl { constructor( private readonly dataSource: DataSource, private readonly filterService: FilterService, ) { super(); } async createEntity(payload: any, loggedInUser: any): Promise { // Auto-generate attribute_key if missing OR empty if (!payload.attribute_key || payload.attribute_key.trim() === '') { payload.attribute_key = payload.field_name .trim() .toLowerCase() .replace(/\s+/g, '_'); } // Pass to base class create method return super.createEntity(payload, loggedInUser); } async getAllLinkedAttributes(loggedInUser: any) { const entId = loggedInUser.enterprise_id; return this.dataSource .getRepository(LinkedAttributes) .createQueryBuilder('fla') .where('fla.enterprise_id = :entId', { entId }) .getMany(); } async upsertLinkedAttributes(payloadList: any[], loggedInUser: any) { const entId = loggedInUser.enterprise_id; // Step 1: Delete all existing rows for this organization await this.dataSource .createQueryBuilder() .delete() .from(LinkedAttributes) .where('enterprise_id = :entId', { entId }) .execute(); // Step 2: Normalize & prepare payloads const newPayloads = payloadList.map((item) => ({ ...item, enterprise_id: entId, attribute_key: item.attribute_key ? item.attribute_key.trim().toLowerCase().replace(/\s+/g, '_') : item.field_name.trim().toLowerCase().replace(/\s+/g, '_'), })); // Step 3: Bulk Insert const insertResult = await this.dataSource .createQueryBuilder() .insert() .into(LinkedAttributes) .values(newPayloads) .execute(); // Step 4: Return inserted list const ids = insertResult.identifiers.map((i) => i.id); return await this.dataSource .getRepository(LinkedAttributes) .createQueryBuilder('la') .where('la.id IN (:...ids)', { ids }) .andWhere('la.enterprise_id = :entId', { entId }) .getMany(); } async getEntityListing(entity_type: string, loggedInUser: any) { const entId = loggedInUser.enterprise_id; // check if is_flag_json is true for the entity_type const entityMasterRepo = this.reflectionHelper.getRepoService('EntityMaster'); const isFlagJson = await entityMasterRepo.findOne({ where: { mapped_entity_type: entity_type, enterprise_id: entId, is_flag_json: true, }, }); if (isFlagJson?.is_flag_json) { // If is_flag_json is true, return getAllLinkedAttributes return await this.getAllLinkedAttributes(loggedInUser); } // Otherwise, return filter result return await this.filterService.applyFilterWrapper({ entity_type, loggedInUser, }); } }