import { ClosedQuestionStatus } from '@koh/common' ; import { Connection , EntitySubscriberInterface , EventSubscriber , InsertEvent , RemoveEvent , UpdateEvent , } from 'typeorm' ; import { NotificationService , NotifMsgs , } from '../notification/notification.service' ; import { QueueSSEService } from '../queue/queue-sse.service' ; import { QueueModel } from '../queue/queue.entity' ; import { QuestionModel } from './question.entity' ; @ EventSubscriber ( ) export class QuestionSubscriber implements EntitySubscriberInterface < QuestionModel > { private notifService : NotificationService ; private queueSSEService : QueueSSEService ; constructor ( connection , notifService , queueSSEService ) { this . notifService = notifService ; this . queueSSEService = queueSSEService ; connection . subscribers . push ( this ) ; } listenTo ( ) { return QuestionModel ; } async afterUpdate ( event ) { if ( ! event . entity ) { return ; } await this . queueSSEService . updateQuestions ( event . entity . queueId ) ; if ( event . updatedColumns . find ( ( c ) => c . propertyName === 'status' ) && event . entity . status in ClosedQuestionStatus ) { const previousThird = await QuestionModel . waitingInQueue ( event . entity . queueId ) . offset ( 2 ) . getOne ( ) ; const third = await QuestionModel . waitingInQueue ( event . entity . queueId ) . setQueryRunner ( event . queryRunner ) . offset ( 2 ) . getOne ( ) ; if ( third && previousThird ?. id !== third ?. id ) { const { creatorId } = third ; this . notifService . notifyUser ( creatorId , NotifMsgs . queue . THIRD_PLACE ) ; } } } async afterInsert ( event ) { const numberOfQuestions = await QuestionModel . waitingInQueue ( event . entity . queueId ) . getCount ( ) ; if ( numberOfQuestions === 0 ) { const staff = ( await QueueModel . findOne ( event . entity . queueId , { relations : [ 'staffList' ] , } ) ) . staffList ; staff . forEach ( ( staff ) => { this . notifService . notifyUser ( staff . id , NotifMsgs . ta . STUDENT_JOINED_EMPTY_QUEUE ) ; } ) ; } await this . queueSSEService . updateQuestions ( event . entity . queueId ) ; } async beforeRemove ( event ) { if ( event . entity ) { await this . queueSSEService . updateQuestions ( event . entity . queueId ) ; } } }