import { BadRequestException, Injectable, NotFoundException, } from '@nestjs/common'; import { EntityServiceImpl } from 'src/module/meta/service/entity-service-impl.service'; import { UserData } from 'src/module/user/entity/user.entity'; import { DataSource, EntityManager } from 'typeorm'; import { EntityMasterService } from '../../meta/service/entity-master.service'; import { ConfigService } from '@nestjs/config'; @Injectable() export class EntityModificationService extends EntityServiceImpl { schema: String; constructor( private readonly entityManager: EntityManager, private readonly configService: ConfigService, ) { super(); this.schema = this.configService.get('DB_SCHEMA') || 'default'; } async logModification(modificationData: any, loggedInUser: UserData) { const { mapped_entity_type, mapped_entity_id, attribute_key } = modificationData; const { organization_id } = loggedInUser; if (!mapped_entity_type || !mapped_entity_id || !attribute_key) { throw new BadRequestException( 'Missing required modification data: mapped_entity_type, mapped_entity_id, or attribute_key', ); } const entityMeta = await this.entityMasterService.getEntityData( mapped_entity_type, loggedInUser, ); if (!entityMeta || !entityMeta.db_table_name) { throw new NotFoundException( 'Entity metadata not found in frm_entity_master', ); } const tableName = entityMeta.db_table_name; // Step 2: Get the row from the target table using mapped_entity_id const [entityRow] = await this.entityManager.query( ` SELECT * FROM ${this.schema}.${tableName} WHERE id = $1 `, [mapped_entity_id], ); if (!entityRow) { throw new NotFoundException( `No record found in ${this.schema}.${tableName} with ID ${mapped_entity_id}`, ); } // Step 3: Extract current value from the target column const currentAttributeValue = entityRow[attribute_key]; // Step 4: Set current_value in modificationData modificationData.current_value = currentAttributeValue; // Step 5: Call super.createEntity with updated modificationData return await super.createEntity(modificationData, loggedInUser); } }