All files / src/lib/socket emitters.ts

0% Statements 0/249
100% Branches 0/0
0% Functions 0/1
0% Lines 0/249

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Socket.IO Emitters
 *
 * Server-side functions for emitting events to connected clients.
 * Use these in API routes, services, and server actions.
 */

import { getSocketServer } from './server';
import { logger } from '@/lib/logging';
import type { NotificationPayload } from '@/lib/notifications/types';
import type {
  OrderUpdatePayload,
  InventoryAlertPayload,
  CartSyncPayload,
  NewOrderPayload,
} from './types';

/**
 * Emit a notification to a specific user
 */
export function emitNotification(
  userId: string,
  notification: NotificationPayload
): boolean {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, notification not emitted via socket', {
      category: 'EXTERNAL',
    });
    return false;
  }

  io.to(`user:${userId}`).emit('notification', notification);
  return true;
}

/**
 * Emit multiple notifications to different users
 */
export function emitNotifications(
  notifications: Array<{ userId: string; notification: NotificationPayload }>
): number {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, notifications not emitted via socket', {
      category: 'EXTERNAL',
    });
    return 0;
  }

  let count = 0;
  notifications.forEach(({ userId, notification }) => {
    io.to(`user:${userId}`).emit('notification', notification);
    count++;
  });

  return count;
}

/**
 * Emit an order update to the customer and admins
 */
export function emitOrderUpdate(
  userId: string,
  orderId: string,
  update: OrderUpdatePayload
): boolean {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, order update not emitted via socket', {
      category: 'EXTERNAL',
    });
    return false;
  }

  // Notify the customer who placed the order
  io.to(`user:${userId}`).emit('orderUpdate', update);

  // Notify anyone specifically tracking this order
  io.to(`order:${orderId}`).emit('orderUpdate', update);

  // Notify all admins monitoring orders
  io.to('admin').emit('orderUpdate', update);
  io.to('orders').emit('orderUpdate', update);

  return true;
}

/**
 * Emit a new order notification to admins
 */
export function emitNewOrder(order: NewOrderPayload): boolean {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, new order not emitted via socket', {
      category: 'EXTERNAL',
    });
    return false;
  }

  // Notify all admins
  io.to('admin').emit('newOrder', order);
  io.to('orders').emit('newOrder', order);

  return true;
}

/**
 * Emit an inventory alert to admins
 */
export function emitInventoryAlert(alert: InventoryAlertPayload): boolean {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, inventory alert not emitted via socket', {
      category: 'EXTERNAL',
    });
    return false;
  }

  // Notify admins on both admin and inventory channels
  io.to('admin').emit('inventoryAlert', alert);
  io.to('inventory').emit('inventoryAlert', alert);

  return true;
}

/**
 * Emit cart sync to all user devices
 */
export function emitCartSync(userId: string, cartData: CartSyncPayload): boolean {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, cart sync not emitted via socket', {
      category: 'EXTERNAL',
    });
    return false;
  }

  io.to(`user:${userId}`).emit('cartSync', cartData);
  return true;
}

/**
 * Broadcast to all connected clients
 */
export function broadcastToAll<T extends Record<string, unknown>>(
  event: string,
  data: T
): boolean {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, broadcast not sent', {
      category: 'EXTERNAL',
    });
    return false;
  }

  // Type assertion needed for dynamic event names
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  io.emit(event as any, data as any);
  return true;
}

/**
 * Emit to a specific room
 */
export function emitToRoom<T extends Record<string, unknown>>(
  room: string,
  event: string,
  data: T
): boolean {
  const io = getSocketServer();
  if (!io) {
    logger.warn('Socket server not initialized, room emit not sent', {
      category: 'EXTERNAL',
    });
    return false;
  }

  // Type assertion needed for dynamic event names
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  io.to(room).emit(event as any, data as any);
  return true;
}

/**
 * Get count of connected clients
 */
export async function getConnectedClientsCount(): Promise<number> {
  const io = getSocketServer();
  if (!io) return 0;

  const sockets = await io.fetchSockets();
  return sockets.length;
}

/**
 * Get count of clients in a specific room
 */
export async function getRoomSize(room: string): Promise<number> {
  const io = getSocketServer();
  if (!io) return 0;

  const sockets = await io.in(room).fetchSockets();
  return sockets.length;
}

/**
 * Check if socket server is initialized and running
 */
export function isSocketServerRunning(): boolean {
  return getSocketServer() !== null;
}

/**
 * Get connection statistics
 */
export async function getConnectionStats(): Promise<{
  totalConnections: number;
  adminConnections: number;
  orderTrackingRooms: number;
}> {
  const io = getSocketServer();
  if (!io) {
    return {
      totalConnections: 0,
      adminConnections: 0,
      orderTrackingRooms: 0,
    };
  }

  const allSockets = await io.fetchSockets();
  const adminSockets = await io.in('admin').fetchSockets();

  // Get all rooms and count order: rooms
  const rooms = io.sockets.adapter.rooms;
  let orderRoomCount = 0;
  rooms.forEach((_, key) => {
    if (key.startsWith('order:')) {
      orderRoomCount++;
    }
  });

  return {
    totalConnections: allSockets.length,
    adminConnections: adminSockets.length,
    orderTrackingRooms: orderRoomCount,
  };
}