All files / stores attendance.ts

100% Statements 102/102
87.5% Branches 28/32
100% Functions 9/9
100% Lines 102/102

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            1x                 1x 1x 27x 27x 27x 27x   1x       1x 19x 10x 10x 19x         1x 20x 5x 5x 5x 20x         1x 19x 6x 6x 6x 6x 6x 6x 6x 19x 1x   1x       1x 18x 18x   18x 18x 18x 16x 18x 2x 2x 18x 18x 18x 18x         1x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x     6x     6x 1x 6x 5x 5x 6x   6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 4x 4x 4x   4x 6x   2x 2x 2x 2x 2x 6x         1x 2x 2x         1x 1x 1x 1x         1x 1x 1x 1x 1x  
/**
 * Attendance Store
 * Manages RSVP responses with optimistic updates
 */
 
import type { AttendanceResponse, AttendanceStatus, AttendanceCount } from '~/types'
import { useApi } from '~/services/api'
 
interface AttendanceState {
  /** Map of eventId -> array of responses */
  responsesByEvent: Map<string, AttendanceResponse[]>
  loading: boolean
  error: string | null
}
 
export const useAttendanceStore = defineStore('attendance', {
  state: (): AttendanceState => ({
    responsesByEvent: new Map(),
    loading: false,
    error: null
  }),
 
  getters: {
    /**
     * Get responses for a specific event
     */
    getResponsesForEvent: (state: AttendanceState) => {
      return (eventId: string): AttendanceResponse[] => {
        return state.responsesByEvent.get(eventId) || []
      }
    },
 
    /**
     * Get a user's response for a specific event
     */
    getUserResponse: (state: AttendanceState) => {
      return (eventId: string, userId: string): AttendanceResponse | undefined => {
        const responses = state.responsesByEvent.get(eventId) || []
        return responses.find(r => r.userId === userId)
      }
    },
 
    /**
     * Get attendance count for an event
     */
    getAttendanceCount: (state: AttendanceState) => {
      return (eventId: string): AttendanceCount => {
        const responses = state.responsesByEvent.get(eventId) || []
        return {
          yes: responses.filter(r => r.status === 'yes').length,
          no: responses.filter(r => r.status === 'no').length,
          maybe: responses.filter(r => r.status === 'maybe').length
        }
      }
    }
  },
 
  actions: {
    /**
     * Fetch attendance for an event
     */
    async fetchAttendance(eventId: string) {
      this.loading = true
      this.error = null
 
      try {
        const api = useApi()
        const responses = await api.getAttendance(eventId)
        this.responsesByEvent.set(eventId, responses)
      } catch (e) {
        this.error = e instanceof Error ? e.message : 'Failed to load attendance'
        console.error('[Attendance Store] fetchAttendance error:', e)
      } finally {
        this.loading = false
      }
    },
 
    /**
     * Submit RSVP with optimistic update
     */
    async submitRSVP(
      eventId: string,
      userId: string,
      status: AttendanceStatus
    ): Promise<boolean> {
      this.error = null
 
      // Create optimistic response
      const now = new Date().toISOString()
      const optimisticResponse: AttendanceResponse = {
        id: `temp-${Date.now()}`,
        eventId,
        userId,
        status,
        createdAt: now,
        updatedAt: now
      }
 
      // Get current responses for this event
      const currentResponses = this.responsesByEvent.get(eventId) || []
      const existingIndex = currentResponses.findIndex(r => r.userId === userId)
 
      // Store previous state for rollback
      const previousResponses = [...currentResponses]
 
      // Apply optimistic update
      if (existingIndex !== -1) {
        currentResponses[existingIndex] = optimisticResponse
      } else {
        currentResponses.push(optimisticResponse)
      }
      this.responsesByEvent.set(eventId, [...currentResponses])
 
      try {
        const api = useApi()
        const confirmedResponse = await api.submitRSVP({
          eventId,
          userId,
          status
        })
 
        // Update with server response
        const responses = this.responsesByEvent.get(eventId) || []
        const index = responses.findIndex(r => r.userId === userId)
        if (index !== -1) {
          responses[index] = confirmedResponse
          this.responsesByEvent.set(eventId, [...responses])
        }
 
        return true
      } catch (e) {
        // Rollback on error
        this.responsesByEvent.set(eventId, previousResponses)
        this.error = e instanceof Error ? e.message : 'Failed to submit RSVP'
        console.error('[Attendance Store] submitRSVP error:', e)
        return false
      }
    },
 
    /**
     * Clear attendance data for an event
     */
    clearEventAttendance(eventId: string) {
      this.responsesByEvent.delete(eventId)
    },
 
    /**
     * Clear all attendance data
     */
    clearAll() {
      this.responsesByEvent.clear()
      this.error = null
    },
 
    /**
     * Clear error state
     */
    clearError() {
      this.error = null
    }
  }
})