All files / src/stores messages.ts

99.28% Statements 138/139
98.66% Branches 74/75
96.96% Functions 32/33
100% Lines 125/125

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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363                                                                                                                          9x 148x 148x 148x 148x     148x 148x 148x 148x   148x   148x 148x 148x   148x 148x     148x     4x 3x 3x   4x 4x 4x 4x 1x   4x 4x 4x     4x 4x   4x         2x 1x       2x 1x 1x   2x 2x 2x 2x 1x   2x 2x 2x 2x 2x   2x         2x 1x       7x 7x 7x               2x 1x         5x 5x 6x 4x 2x 2x         3x 3x 3x       2x 2x 2x       1x       1x               2x 2x       1x 1x       10x 7x 7x   10x 10x 10x 10x 10x 2x   10x 10x 10x     10x       10x   10x         2x 1x                     2x     2x 2x 3x 2x 1x     1x           4x       2x 2x 2x         2x 1x         2x       3x 3x 3x 1x 1x   3x 3x 1x 1x 1x         31x 24x 24x                             5x 5x 1x             5x 1x 5x 2x 2x 2x       148x                                                                        
// @implements UC-DM-003.2, UC-DM-004.2, UC-DM-005.1, UC-DM-006.1, UC-DM-007.1, UC-DM-009.1
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'
import type { User } from '@/stores/users'
 
export type ConversationStatus = 'accepted' | 'pending' | 'declined'
 
/**
 * What the current user can do in a conversation right now — see
 * flows-api's utils/directMessages.js describeSendState.
 */
export type SendState =
  | 'ok'
  | 'request_first_message'
  | 'awaiting_acceptance'
  | 'request_received'
  | 'blocked_by_you'
  | 'unavailable'
 
export interface ConversationDetails {
  conversationId: string
  otherUserId: string
  otherUserNickname: string | null
  otherUserName: string | null
  otherUserProfilePicture: string | null
  status: ConversationStatus
  isRequester: boolean
  isBlockedByCurrentUser: boolean
  sendState: SendState
}
 
export type ConversationFolder = 'inbox' | 'requests'
 
export interface ConversationSummary {
  conversationId: string
  otherUserId: string
  otherUserNickname: string | null
  otherUserName: string | null
  otherUserProfilePicture: string | null
  lastMessageAt: string
  lastMessagePreview: string | null
  lastMessageSenderId: string | null
  unreadCount: number
  status?: ConversationStatus
}
 
export interface Message {
  id: string
  conversationId: string
  senderId: string
  body: string
  createdAt: string
}
 
export interface BlockedUsersPage {
  items: User[]
  nextToken: string | null
  hasMore: boolean
}
 
export const useMessagesStore = defineStore('messages', () => {
  const conversations = ref<ConversationSummary[]>([])
  const conversationsLoading = ref(false)
  const conversationsNextToken = ref<string | null>(null)
  const conversationsHasMore = ref(false)
 
  // Message requests received and not answered yet (the Requests tab)
  const requests = ref<ConversationSummary[]>([])
  const requestsLoading = ref(false)
  const requestsNextToken = ref<string | null>(null)
  const requestsHasMore = ref(false)
 
  const conversationDetails = ref<Record<string, ConversationDetails>>({})
 
  const messagesByConversation = ref<Record<string, Message[]>>({})
  const messagesLoading = ref(false)
  const messagesNextToken = ref<Record<string, string | null>>({})
 
  const unreadTotal = ref(0)
  const unreadRequestCount = ref(0)
  // Bumped on every successful WebSocket (re)connect so an open conversation
  // can re-sync what a lost push may have skipped (see syncLatestMessages).
  const realtimeConnectCount = ref(0)
 
  async function fetchInbox(reset = true) {
    if (reset) {
      conversations.value = []
      conversationsNextToken.value = null
    }
    conversationsLoading.value = true
    try {
      const params: Record<string, string> = { limit: '20' }
      if (!reset && conversationsNextToken.value) {
        params.nextToken = conversationsNextToken.value
      }
      const response = await api.get('/v1/conversations', { params })
      const data = response.data
      conversations.value = reset
        ? data.conversations
        : [...conversations.value, ...data.conversations]
      conversationsNextToken.value = data.nextToken
      conversationsHasMore.value = !!data.nextToken
    } finally {
      conversationsLoading.value = false
    }
  }
 
  async function loadMoreInbox() {
    if (conversationsLoading.value || !conversationsHasMore.value) return
    await fetchInbox(false)
  }
 
  async function fetchRequests(reset = true) {
    if (reset) {
      requests.value = []
      requestsNextToken.value = null
    }
    requestsLoading.value = true
    try {
      const params: Record<string, string> = { limit: '20', folder: 'requests' }
      if (!reset && requestsNextToken.value) {
        params.nextToken = requestsNextToken.value
      }
      const response = await api.get('/v1/conversations', { params })
      const data = response.data
      requests.value = reset ? data.conversations : [...requests.value, ...data.conversations]
      requestsNextToken.value = data.nextToken
      requestsHasMore.value = !!data.nextToken
    } finally {
      requestsLoading.value = false
    }
  }
 
  async function loadMoreRequests() {
    if (requestsLoading.value || !requestsHasMore.value) return
    await fetchRequests(false)
  }
 
  async function fetchConversation(conversationId: string) {
    const response = await api.get<ConversationDetails>(`/v1/conversations/${conversationId}`)
    conversationDetails.value = { ...conversationDetails.value, [conversationId]: response.data }
    return response.data
  }
 
  /**
   * Re-reads a conversation the server says changed (its request was
   * accepted) — only when this client already shows it.
   */
  async function receiveConversationUpdate(conversationId: string) {
    if (conversationDetails.value[conversationId]) {
      await fetchConversation(conversationId)
    }
  }
 
  function removeRequest(conversationId: string) {
    const request = requests.value.find((r) => r.conversationId === conversationId)
    if (!request) return
    requests.value = requests.value.filter((r) => r.conversationId !== conversationId)
    if (request.unreadCount > 0) {
      unreadTotal.value = Math.max(0, unreadTotal.value - request.unreadCount)
      unreadRequestCount.value = Math.max(0, unreadRequestCount.value - 1)
    }
  }
 
  async function acceptRequest(conversationId: string) {
    await api.post(`/v1/conversations/${conversationId}/accept`)
    removeRequest(conversationId)
    await fetchConversation(conversationId)
  }
 
  async function declineRequest(conversationId: string) {
    await api.post(`/v1/conversations/${conversationId}/decline`)
    removeRequest(conversationId)
    await fetchConversation(conversationId)
  }
 
  async function blockUser(userId: string) {
    await api.post(`/v1/users/${userId}/block`)
  }
 
  async function unblockUser(userId: string) {
    await api.delete(`/v1/users/${userId}/block`)
  }
 
  /** One page of the users the current user blocked, for their profile page. */
  async function fetchBlockedUsers(params?: {
    limit?: number
    nextToken?: string
  }): Promise<BlockedUsersPage> {
    const response = await api.get<BlockedUsersPage>('/v1/users/me/blocks', { params })
    return response.data
  }
 
  async function createOrGetConversation(recipientId: string): Promise<string> {
    const response = await api.post('/v1/conversations', { recipientId })
    return response.data.id
  }
 
  async function fetchMessages(conversationId: string, reset = true) {
    if (reset) {
      messagesByConversation.value = { ...messagesByConversation.value, [conversationId]: [] }
      messagesNextToken.value = { ...messagesNextToken.value, [conversationId]: null }
    }
    messagesLoading.value = true
    try {
      const params: Record<string, string> = { limit: '30' }
      const existingToken = messagesNextToken.value[conversationId]
      if (!reset && existingToken) {
        params.nextToken = existingToken
      }
      const response = await api.get(`/v1/conversations/${conversationId}/messages`, { params })
      const data = response.data
      const existing = reset ? [] : (messagesByConversation.value[conversationId] ?? [])
      // Older pages come first chronologically, so a "load more" page is
      // prepended (it's earlier history), not appended.
      messagesByConversation.value = {
        ...messagesByConversation.value,
        [conversationId]: reset ? data.messages : [...data.messages, ...existing]
      }
      messagesNextToken.value = { ...messagesNextToken.value, [conversationId]: data.nextToken }
    } finally {
      messagesLoading.value = false
    }
  }
 
  async function loadMoreMessages(conversationId: string) {
    if (messagesLoading.value || !messagesNextToken.value[conversationId]) return
    await fetchMessages(conversationId, false)
  }
 
  /**
   * Merges the newest page of a conversation into what's already loaded,
   * without resetting the list or its pagination state. A push is
   * best-effort — one sent while this client's socket was still connecting
   * (or reconnecting) is never replayed — so the open conversation calls this
   * on every (re)connect to recover it.
   */
  async function syncLatestMessages(conversationId: string) {
    const response = await api.get(`/v1/conversations/${conversationId}/messages`, {
      params: { limit: '30' }
    })
    const existing = messagesByConversation.value[conversationId] ?? []
    const known = new Set(existing.map((m) => m.id))
    const missing: Message[] = response.data.messages.filter((m: Message) => !known.has(m.id))
    if (missing.length === 0) return
    messagesByConversation.value = {
      ...messagesByConversation.value,
      [conversationId]: [...existing, ...missing].sort((a, b) =>
        a.createdAt.localeCompare(b.createdAt)
      )
    }
  }
 
  function notifyRealtimeConnected() {
    realtimeConnectCount.value++
  }
 
  async function sendMessage(conversationId: string, body: string) {
    const response = await api.post(`/v1/conversations/${conversationId}/messages`, { body })
    const message: Message = response.data
    const existing = messagesByConversation.value[conversationId] ?? []
    // The conversation page's initial fetchMessages can resolve after the
    // server committed this message but before this POST response arrives
    // (the POST also awaits the recipient's push), so the message may
    // already be in the list — appending it blindly renders it twice.
    if (!existing.some((m) => m.id === message.id)) {
      messagesByConversation.value = {
        ...messagesByConversation.value,
        [conversationId]: [...existing, message]
      }
    }
    return message
  }
 
  async function markRead(conversationId: string) {
    await api.post(`/v1/conversations/${conversationId}/read`)
    const conversation = conversations.value.find((c) => c.conversationId === conversationId)
    if (conversation && conversation.unreadCount > 0) {
      unreadTotal.value = Math.max(0, unreadTotal.value - conversation.unreadCount)
      conversation.unreadCount = 0
    }
    const request = requests.value.find((r) => r.conversationId === conversationId)
    if (request && request.unreadCount > 0) {
      unreadTotal.value = Math.max(0, unreadTotal.value - request.unreadCount)
      unreadRequestCount.value = Math.max(0, unreadRequestCount.value - 1)
      request.unreadCount = 0
    }
  }
 
  async function fetchUnreadCount() {
    const response = await api.get('/v1/conversations/unread-count')
    unreadTotal.value = response.data.count
    unreadRequestCount.value = response.data.requestCount ?? 0
  }
 
  /**
   * Merges a WebSocket-pushed new message into local state — called by
   * useMessagesSocket.ts's onmessage handler. Does not touch unreadTotal
   * itself; the socket layer re-fetches the authoritative count via
   * fetchUnreadCount() instead, to avoid client-side drift.
   *
   * Skips a message id already in the list: the sender's own page already
   * appended it locally from the POST response, and a reconnect can also
   * replay a push already delivered once — without this guard either case
   * renders the same message bubble twice.
   */
  function receivePushedMessage(conversationId: string, message: Message) {
    const existing = messagesByConversation.value[conversationId]
    if (existing && !existing.some((m) => m.id === message.id)) {
      messagesByConversation.value = {
        ...messagesByConversation.value,
        [conversationId]: [...existing, message]
      }
    }
 
    const conversation =
      conversations.value.find((c) => c.conversationId === conversationId) ??
      requests.value.find((r) => r.conversationId === conversationId)
    if (conversation) {
      conversation.lastMessageAt = message.createdAt
      conversation.lastMessagePreview = message.body
      conversation.lastMessageSenderId = message.senderId
    }
  }
 
  return {
    conversations,
    conversationsLoading,
    conversationsHasMore,
    requests,
    requestsLoading,
    requestsHasMore,
    conversationDetails,
    messagesByConversation,
    messagesLoading,
    messagesNextToken,
    unreadTotal,
    unreadRequestCount,
    realtimeConnectCount,
    fetchInbox,
    loadMoreInbox,
    fetchRequests,
    loadMoreRequests,
    fetchConversation,
    receiveConversationUpdate,
    acceptRequest,
    declineRequest,
    blockUser,
    unblockUser,
    fetchBlockedUsers,
    createOrGetConversation,
    fetchMessages,
    loadMoreMessages,
    syncLatestMessages,
    notifyRealtimeConnected,
    sendMessage,
    markRead,
    fetchUnreadCount,
    receivePushedMessage
  }
})