# Code coverage report for modules/notifications/gateways/notifications.gateway.ts

# All files / modules/notifications/gateways notifications.gateway.ts

100% Statements 89/89
100% Branches 32/32
100% Functions 15/15
100% Lines 87/87

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
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    2811x

    1x
    1x

    1x

    1x

    35x

    35x

    35x

    33x
    33x
    33x

    33x
    3x
    3x
    3x

    30x
    30x

    30x

    30x
    22x

    30x

    30x

    30x
    29x

    29x

    29x

    1x
    1x

    4x

    4x
    3x
    3x
    3x
    3x
    2x

    3x

    4x

    4x
    4x

    4x
    2x
    2x

    2x
    3x

    2x

    2x

    3x
    3x

    1x

    3x
    1x

    2x
    2x

    2x

    2x
    3x
    1x

    2x

    1x
    2x
    1x

    1x
    1x

    1x
    1x
    2x
    1x

    1x

    1x

    1x

    2x
    2x

    2x
    1x
    2x

    2x
    2x

    2x
    1x
    1x

    5x

    7x

    6x
    6x
    6x

    33x

    33x

     import {
      WebSocketGateway,
      WebSocketServer,
      SubscribeMessage,
      OnGatewayConnection,
      OnGatewayDisconnect,
      MessageBody,
      ConnectedSocket,
    } from '@nestjs/websockets';
    import { Server, Socket } from 'socket.io';
    import { Logger, UseGuards } from '@nestjs/common';
    import { Notification } from '../entities';

    interface AuthenticatedSocket extends Socket {
      userId?: string;
      tenantId?: string;
    }

    @WebSocketGateway({
      namespace: '/notifications',
      cors: {
        origin: process.env.FRONTEND_URL || '*',
        credentials: true,
      },
    })
    export class NotificationsGateway
      implements OnGatewayConnection, OnGatewayDisconnect
    {
      @WebSocketServer()
      server: Server;

      private readonly logger = new Logger(NotificationsGateway.name);

      // Map: "tenantId:userId" -> Set of socket IDs
      private userSockets = new Map<string, Set<string>>();

      // Map: socket ID -> user key
      private socketUsers = new Map<string, string>();

      handleConnection(client: AuthenticatedSocket) {
        try {
          const userId = this.extractUserId(client);
          const tenantId = this.extractTenantId(client);

          if (!userId || !tenantId) {
            this.logger.warn(`Client ${client.id} connected without auth, disconnecting`);
            client.disconnect();
            return;
          }

          client.userId = userId;
          client.tenantId = tenantId;

          const userKey = `${tenantId}:${userId}`;

          // Add to user sockets map
          if (!this.userSockets.has(userKey)) {
            this.userSockets.set(userKey, new Set());
          }
          this.userSockets.get(userKey)!.add(client.id);

          // Add to socket users map
          this.socketUsers.set(client.id, userKey);

          // Join rooms
          client.join(`tenant:${tenantId}`);
          client.join(`user:${userId}`);

          this.logger.debug(
            `User ${userId} connected from tenant ${tenantId} (socket: ${client.id})`,
          );

          // Send connection confirmation
          client.emit('connected', {
            socketId: client.id,
            userId,
            tenantId,
          });
        } catch (error) {
          this.logger.error(`Connection error: ${error.message}`);
          client.disconnect();
        }
      }

      handleDisconnect(client: AuthenticatedSocket) {
        const userKey = this.socketUsers.get(client.id);

        if (userKey) {
          const sockets = this.userSockets.get(userKey);
          if (sockets) {
            sockets.delete(client.id);
            if (sockets.size === 0) {
              this.userSockets.delete(userKey);
            }
          }
          this.socketUsers.delete(client.id);
        }

        this.logger.debug(`Client ${client.id} disconnected`);
      }

      /**
       * Emit notification to a specific user
       */
      async emitToUser(
        tenantId: string,
        userId: string,
        notification: Partial<Notification>,
      ): Promise<number> {
        const userKey = `${tenantId}:${userId}`;
        const socketIds = this.userSockets.get(userKey);

        if (!socketIds || socketIds.size === 0) {
          this.logger.debug(`No active sockets for user ${userId}`);
          return 0;
        }

        for (const socketId of socketIds) {
          this.server.to(socketId).emit('notification:created', notification);
        }

        this.logger.debug(
          `Emitted notification to user ${userId} (${socketIds.size} sockets)`,
        );

        return socketIds.size;
      }

      /**
       * Emit to all users in a tenant
       */
      async emitToTenant(
        tenantId: string,
        event: string,
        data: any,
      ): Promise<void> {
        this.server.to(`tenant:${tenantId}`).emit(event, data);
        this.logger.debug(`Emitted ${event} to tenant ${tenantId}`);
      }

      /**
       * Emit notification read event to sync across devices
       */
      @SubscribeMessage('notification:read')
      handleMarkAsRead(
        @ConnectedSocket() client: AuthenticatedSocket,
        @MessageBody() payload: { notificationId: string },
      ): void {
        if (!client.userId || !client.tenantId) {
          return;
        }

        const userKey = `${client.tenantId}:${client.userId}`;
        const socketIds = this.userSockets.get(userKey);

        if (socketIds) {
          // Broadcast to all other sockets of the same user
          for (const socketId of socketIds) {
            if (socketId !== client.id) {
              this.server.to(socketId).emit('notification:read', payload);
            }
          }
        }

        this.logger.debug(
          `User ${client.userId} marked notification ${payload.notificationId} as read`,
        );
      }

      /**
       * Handle mark all as read
       */
      @SubscribeMessage('notification:read-all')
      handleMarkAllAsRead(@ConnectedSocket() client: AuthenticatedSocket): void {
        if (!client.userId || !client.tenantId) {
          return;
        }

        const userKey = `${client.tenantId}:${client.userId}`;
        const socketIds = this.userSockets.get(userKey);

        if (socketIds) {
          for (const socketId of socketIds) {
            if (socketId !== client.id) {
              this.server.to(socketId).emit('notification:read-all', {});
            }
          }
        }

        this.logger.debug(`User ${client.userId} marked all notifications as read`);
      }

      /**
       * Handle client requesting unread count
       */
      @SubscribeMessage('notification:get-unread-count')
      handleGetUnreadCount(
        @ConnectedSocket() client: AuthenticatedSocket,
      ): { event: string } {
        // The actual count will be fetched by the service and emitted back
        return { event: 'notification:unread-count-requested' };
      }

      /**
       * Emit unread count update to user
       */
      async emitUnreadCount(
        tenantId: string,
        userId: string,
        count: number,
      ): Promise<void> {
        const userKey = `${tenantId}:${userId}`;
        const socketIds = this.userSockets.get(userKey);

        if (socketIds) {
          for (const socketId of socketIds) {
            this.server.to(socketId).emit('notification:unread-count', { count });
          }
        }
      }

      /**
       * Emit notification deleted event
       */
      async emitNotificationDeleted(
        tenantId: string,
        userId: string,
        notificationId: string,
      ): Promise<void> {
        const userKey = `${tenantId}:${userId}`;
        const socketIds = this.userSockets.get(userKey);

        if (socketIds) {
          for (const socketId of socketIds) {
            this.server
              .to(socketId)
              .emit('notification:deleted', { notificationId });
          }
        }
      }

      /**
       * Get connected users count
       */
      getConnectedUsersCount(): number {
        return this.userSockets.size;
      }

      /**
       * Get total socket connections
       */
      getTotalConnections(): number {
        return this.socketUsers.size;
      }

      /**
       * Check if user is online
       */
      isUserOnline(tenantId: string, userId: string): boolean {
        const userKey = `${tenantId}:${userId}`;
        const sockets = this.userSockets.get(userKey);
        return sockets !== undefined && sockets.size > 0;
      }

      private extractUserId(client: Socket): string | null {
        return (
          (client.handshake.auth?.userId as string) ||
          (client.handshake.query?.userId as string) ||
          null
        );
      }

      private extractTenantId(client: Socket): string | null {
        return (
          (client.handshake.auth?.tenantId as string) ||
          (client.handshake.query?.tenantId as string) ||
          null
        );
      }
    }