import { EventsHandler, IEventHandler } from '@nestjs/cqrs'; import { DataSchedulingChangeStatusEvent } from '../../entities/event/data-scheduling-change-status.event'; import { capitalizeEachWord } from 'src/modules/reports/shared/helpers'; import { DataSchedulingLogEntity, SCHEDULING_LOG_ACTION_ENUM, SCHEDULING_LOG_TYPE_ENUM, } from '../../entities/data-scheduling.entity'; import { Logger } from '@nestjs/common'; import { DataSchedulingLogDataService } from '../../../data/services/data-scheduling-log-data.service'; import { decryptionTotal } from '../../../infrastructure/helpers'; @EventsHandler(DataSchedulingChangeStatusEvent) export class DataSchedulingChangeStatusHandler implements IEventHandler { private readonly logger = new Logger(DataSchedulingChangeStatusHandler.name); constructor(private service: DataSchedulingLogDataService) {} async handle(event: DataSchedulingChangeStatusEvent) { // Prevent execution if the event data is null, which can happen if triggered from the default percentage update service. if (event.data?.data) { const oldData = event?.data?.old; const newData = event?.data?.data; const oldStatus = capitalizeEachWord(oldData?.status); const newStatus = capitalizeEachWord(newData?.status); const scheduleName = newData?.name || 'an item'; const editorName = newData.editor_name || 'System'; const totalPercentage = decryptionTotal(newData?.indexing_key); const description = `
${editorName} changed the status of ${scheduleName} (${totalPercentage}%) schedule from ${newData?.schedule_date_from} to ${newData.schedule_date_to} from ${oldStatus} to ${newStatus}.
`; const payload: DataSchedulingLogEntity = { type: SCHEDULING_LOG_TYPE_ENUM.DATA_SCHEDULING, action: SCHEDULING_LOG_ACTION_ENUM.CHANGE_STATUS, log_created_at: new Date().getTime(), data_id: newData?.id, name: newData?.name, indexing_key: newData?.indexing_key, schedule_date_from: newData?.schedule_date_from, schedule_date_to: newData?.schedule_date_to, status: newData?.status, creator_id: newData?.creator_id, creator_name: newData?.creator_name, editor_id: newData?.editor_id, editor_name: newData?.editor_name, created_at: newData?.created_at, updated_at: newData?.updated_at, description: description, }; await this.service.create(payload as any); this.logger.verbose( `[SCHEDULING LOG] Change status data for ID: ${payload.data_id}`, ); } } }