import { Injectable } from '@nestjs/common'; import { EntityManager } from 'typeorm'; import { ReflectionHelper } from '../../../utils/service/reflection-helper.service'; @Injectable() export class EntityUpdateRepository { constructor( private readonly entityManager: EntityManager, private readonly reflectionHelper: ReflectionHelper, ) {} async updateEntityAttribute(entity, config, user) { const { entity_type } = config; const { organization_id } = user; // 1. Get the table name const entityMasterRepo = this.reflectionHelper.getRepoService('EntityMaster'); const result = await entityMasterRepo.findOne({ where: { mapped_entity_type: entity_type, organization_id, }, }); if (!result) { throw new Error('Entity table not found'); } const entityTableName = result.db_table_name; // 2. Determine the ID condition const isLead = config.entity_type === 'LEAD'; const idColumn = isLead ? 'id' : 'parent_id'; // 3. Update using dynamic table name return await this.entityManager .createQueryBuilder() .update(entityTableName) .set({ [config.attribute_key]: config.attribute_value }) .where(`${idColumn} = :id`, { id: entity.id }) .execute(); } }