All files / src/routes rooms.js

100% Statements 85/85
94% Branches 47/50
100% Functions 5/5
100% Lines 79/79

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              5x 5x 5x 5x 5x 5x   5x 5x           29x 29x           1x             5x 22x 22x 22x 2x   20x 1x   19x 19x   19x   19x 18x 17x       17x 17x 17x 17x     13x 13x         13x     13x 13x 13x 13x       13x                               1x     13x 13x   1x 1x         5x 36x 36x 36x 36x 36x 36x               8x   28x   28x       28x 27x 24x             24x 3x   21x 21x 21x 21x     17x             16x 2x 2x 2x       2x 2x     14x 14x   14x                       14x 14x 14x                                   1x             14x 14x   2x         2x       5x  
/**
 * Room routes — invite sending and seat request creation (FCM push required).
 *
 * POST /api/rooms/:roomId/invites/send  -> Send invite (FCM push to invitee)
 * POST /api/rooms/:roomId/seat-requests -> Create seat request (FCM push to room owner)
 */
 
const router = require('express').Router();
const { db, rtdb } = require('../utils/firebase');
const { generateId, now } = require('../utils/helpers');
const { sendPushToUser } = require('../utils/fcm');
const { requireSameCohort } = require('../middleware/sameCohort');
const log = require('../utils/log');
 
const MAX_USER_NAME_LENGTH = 50;
const MAX_SEAT_INDEX = 20;
 
// --- Helpers ---
 
/** Broadcast a room event via RTDB. */
async function broadcastToRoom(roomId, data) {
  try {
    await rtdb.ref(`rooms/${roomId}/events/lastEvent`).set({
      type: data.type,
      ts: Date.now(),
      ...(data.userId ? { userId: data.userId } : {}),
    });
  } catch (err) {
    log.error('rooms', 'Failed to write RTDB event', { roomId, error: err.message });
  }
}
 
// --- Route registration ---
 
// -- Send invite --
router.post('/rooms/:roomId/invites/send', async (req, res) => {
  try {
    const body = req.body;
    if (!body?.userId || !body?.invitedBy) {
      return res.status(400).json({ error: 'userId and invitedBy required' });
    }
    if (req.auth.uniqueId !== body.invitedBy) {
      return res.status(403).json({ error: 'Cannot send invite on behalf of another user' });
    }
    const roomId = req.params.roomId;
    const inviteeId = body.userId;
 
    log.info('rooms', 'Sending room invite', { roomId, inviteeId, invitedBy: body.invitedBy });
 
    const roomSnap = await db.doc(`rooms/${roomId}`).get();
    if (!roomSnap.exists) return res.status(404).json({ error: 'Room not found' });
    const room = roomSnap.data();
 
    // UK OSA #17 PR 4 — fetch invitee up front for the cross-cohort
    // gate; the FCM block reuses the same doc.
    const inviteeSnap = await db.doc(`users/${inviteeId}`).get();
    const inviteeDoc = inviteeSnap.exists ? inviteeSnap.data() : null;
    const blocked = await requireSameCohort(req, res, inviteeId, () => inviteeDoc);
    if (blocked) return;
 
    // Update pendingInvites on the room doc (matches Android client field name)
    const pendingInvites = room.pendingInvites || {};
    pendingInvites[inviteeId] = {
      invitedBy: body.invitedBy,
      invitedAt: now(),
    };
 
    await db.doc(`rooms/${roomId}`).update({ pendingInvites });
 
    // Send FCM push to invitee
    try {
      const inviterSnap = await db.doc(`users/${body.invitedBy}`).get();
      const roomName = room.name || 'a room';
      const inviterName = inviterSnap.exists
        ? inviterSnap.data().displayName || 'Someone'
        : 'Someone';
 
      await sendPushToUser(
        inviteeId,
        {
          type: 'ROOM_INVITE',
          roomId,
          roomName,
          invitedBy: body.invitedBy,
          inviterName,
        },
        {
          userData: inviteeDoc,
          senderUniqueId: body.invitedBy,
          recipientUniqueId: inviteeId,
        },
      );
    } catch (err) {
      log.error('rooms', 'Failed to send invite FCM', { roomId, inviteeId, error: err.message });
    }
 
    await broadcastToRoom(roomId, { type: 'room_updated' });
    return res.json({ success: true });
  } catch (err) {
    log.error('rooms', 'Send invite failed', { roomId: req.params.roomId, error: err.message });
    return res.status(500).json({ error: 'Internal server error' });
  }
});
 
// -- Create seat request --
router.post('/rooms/:roomId/seat-requests', async (req, res) => {
  try {
    const uniqueId = req.auth.uniqueId;
    const body = req.body;
    const seatIndex = body?.seatIndex;
    const userName = (body?.userName || '').slice(0, MAX_USER_NAME_LENGTH);
    if (
      seatIndex === null ||
      seatIndex === undefined ||
      typeof seatIndex !== 'number' ||
      !Number.isInteger(seatIndex) ||
      seatIndex < 0 ||
      seatIndex > MAX_SEAT_INDEX
    ) {
      return res.status(400).json({ error: 'Valid seatIndex required (0-20)' });
    }
    const roomId = req.params.roomId;
 
    log.info('rooms', 'Creating seat request', { roomId, userId: uniqueId, seatIndex });
 
    // UK OSA #17 PR 4 — fetch room + owner up front for the cross-
    // cohort gate; reused later in the FCM push block.
    const roomSnap = await db.doc(`rooms/${roomId}`).get();
    if (!roomSnap.exists) return res.status(404).json({ error: 'Room not found' });
    const room = roomSnap.data();
 
    // A room without an `ownerId` cannot resolve a cohort for the
    // gate (cohort stand-in = owner cohort until PR 7). Refuse the
    // action rather than letting the API-layer gate fall through —
    // the Firestore rules layer (PR 3) is a backstop, not the only
    // line of defence.
    if (!room?.ownerId) {
      return res.status(404).json({ error: 'Room not found' });
    }
    const ownerSnap = await db.doc(`users/${room.ownerId}`).get();
    const ownerDoc = ownerSnap.exists ? ownerSnap.data() : null;
    const blocked = await requireSameCohort(req, res, room.ownerId, () => ownerDoc);
    if (blocked) return;
 
    // Check for existing pending request
    const existingSnap = await db
      .collection(`rooms/${roomId}/seatRequests`)
      .where('userId', '==', uniqueId)
      .where('status', '==', 'PENDING')
      .limit(1)
      .get();
 
    if (!existingSnap.empty) {
      const existingDoc = existingSnap.docs[0];
      const reqId = existingDoc.id;
      await db.doc(`rooms/${roomId}/seatRequests/${reqId}`).update({
        seatIndex,
        createdAt: now(),
      });
      await broadcastToRoom(roomId, { type: 'seat_request_updated' });
      return res.json({ requestId: reqId });
    }
 
    const reqId = generateId();
    const timestamp = now();
 
    await db.doc(`rooms/${roomId}/seatRequests/${reqId}`).set({
      requestId: reqId,
      userId: uniqueId,
      userName: userName || '',
      seatIndex,
      status: 'PENDING',
      resolvedBy: null,
      createdAt: timestamp,
      resolvedAt: null,
    });
 
    // Send FCM push to room owner (reusing the up-front fetched docs)
    try {
      Eif (room?.ownerId) {
        await sendPushToUser(
          room.ownerId,
          {
            type: 'SEAT_REQUEST',
            roomId,
            roomName: room.name || 'a room',
            requesterId: uniqueId,
            requesterName: userName || '',
            seatIndex: String(seatIndex),
          },
          {
            userData: ownerDoc,
            senderUniqueId: uniqueId,
            recipientUniqueId: room.ownerId,
          },
        );
      }
    } catch (err) {
      log.error('rooms', 'Failed to send seat request FCM', {
        roomId,
        userId: uniqueId,
        error: err.message,
      });
    }
 
    await broadcastToRoom(roomId, { type: 'seat_request_updated' });
    return res.json({ requestId: reqId });
  } catch (err) {
    log.error('rooms', 'Create seat request failed', {
      roomId: req.params.roomId,
      userId: req.auth?.uniqueId,
      error: err.message,
    });
    return res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;