All files / apps/notifications-service/src/notifications work-order-events.consumer.ts

100% Statements 34/34
100% Branches 30/30
100% Functions 8/8
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 912x 2x   2x   2x 2x 2x   2x           2x 7x     7x 7x 7x                 2x       4x 4x                   2x       4x 4x         4x 3x     3x             3x       4x 3x     3x         3x           8x 2x 2x      
import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
import { Injectable, Logger } from '@nestjs/common';
import type { ConsumeMessage } from 'amqplib';
import { EXCHANGES, WORK_ORDER_EVENTS } from '@app/contracts';
import type { WorkOrderEvent } from '@app/contracts';
import { EventRetryHandler } from './event-retry.handler';
import { NotificationSender } from './notification-sender';
import { ProcessedEventsStore } from './processed-events.store';
 
export const QUEUES = {
  WORK_ORDER_CREATED: 'notifications.work-order-created',
  WORK_ORDER_COMPLETED: 'notifications.work-order-completed',
} as const;
 
@Injectable()
export class WorkOrderEventsConsumer {
  private readonly logger = new Logger(WorkOrderEventsConsumer.name);
 
  constructor(
    private readonly sender: NotificationSender,
    private readonly retry: EventRetryHandler,
    private readonly processed: ProcessedEventsStore,
  ) {}
 
  @RabbitSubscribe({
    exchange: EXCHANGES.EVENTS,
    routingKey: WORK_ORDER_EVENTS.CREATED,
    queue: QUEUES.WORK_ORDER_CREATED,
    queueOptions: { durable: true },
  })
  async onWorkOrderCreated(
    event: WorkOrderEvent,
    message: ConsumeMessage,
  ): Promise<void> {
    await this.retry.handle(QUEUES.WORK_ORDER_CREATED, event, message, () =>
      this.notifyCreated(event),
    );
  }
 
  @RabbitSubscribe({
    exchange: EXCHANGES.EVENTS,
    routingKey: WORK_ORDER_EVENTS.COMPLETED,
    queue: QUEUES.WORK_ORDER_COMPLETED,
    queueOptions: { durable: true },
  })
  async onWorkOrderCompleted(
    event: WorkOrderEvent,
    message: ConsumeMessage,
  ): Promise<void> {
    await this.retry.handle(QUEUES.WORK_ORDER_COMPLETED, event, message, () =>
      this.notifyCompleted(event),
    );
  }
 
  private async notifyCreated(event: WorkOrderEvent): Promise<void> {
    if (this.isDuplicate(event)) return;
    this.logger.log(
      `received ${event.type} (${event.eventId}) correlationId=${event.correlationId ?? 'none'}`,
    );
    await this.sender.send({
      // Recipient resolution (property manager lookup) arrives with the
      // Properties service; a deterministic placeholder keeps the flow honest.
      recipient: `manager-of-${event.data.propertyId}`,
      subject: `New work order: ${event.data.title}`,
      body: `A ${event.data.priority} priority work order was opened for property ${event.data.propertyId}.`,
    });
    this.processed.mark(event.eventId);
  }
 
  private async notifyCompleted(event: WorkOrderEvent): Promise<void> {
    if (this.isDuplicate(event)) return;
    this.logger.log(
      `received ${event.type} (${event.eventId}) correlationId=${event.correlationId ?? 'none'}`,
    );
    await this.sender.send({
      recipient: `tenant-of-${event.data.propertyId}`,
      subject: `Work order completed: ${event.data.title}`,
      body: `The work order for property ${event.data.propertyId} has been completed.`,
    });
    this.processed.mark(event.eventId);
  }
 
  /** At-least-once delivery makes duplicates a matter of when, not if; the
   * store marks only after a successful send, so retries still go through. */
  private isDuplicate(event: WorkOrderEvent): boolean {
    if (!this.processed.has(event.eventId)) return false;
    this.logger.debug(`duplicate ${event.type} (${event.eventId}) skipped`);
    return true;
  }
}