All files / src/composables usePostMatchStats.js

32.14% Statements 72/224
100% Branches 1/1
8.33% Functions 1/12
32.14% Lines 72/224

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 2461x 1x 1x 1x 1x 1x                   1x 3x   3x 3x 3x 3x 3x 3x   3x 3x 3x 3x                   3x 3x 3x 3x                       3x 3x 3x 3x                                     3x 3x 3x 3x                                   3x 3x 3x 3x                             3x 3x 3x 3x                                   3x 3x 3x 3x                             3x 3x 3x 3x                                   3x 3x 3x 3x                             3x 3x 3x 3x                                                               3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x  
/**
 * Post-Match Stats Composable
 *
 * Shared logic for recording goals, substitutions, and player stats
 * for completed matches. Follows the useMatchLineup pattern.
 */
 
import { ref, isRef } from 'vue';
import { useAuthStore } from '../stores/auth';
import { getApiBaseUrl } from '../config/api';
 
function unwrapMatchData(matchData) {
  return isRef(matchData) ? matchData.value : matchData;
}
 
export function usePostMatchStats(matchId, matchData) {
  const authStore = useAuthStore();
 
  // State
  const homeStats = ref([]);
  const awayStats = ref([]);
  const statsLoading = ref(false);
  const saving = ref(false);
  const error = ref(null);
 
  /**
   * Check if the current user can edit stats for a specific team.
   */
  function canEditTeam(teamId) {
    if (!authStore.isAuthenticated.value) return false;
    if (authStore.isAdmin.value) return true;
    if (authStore.isClubManager.value) return true;
    if (authStore.isTeamManager.value) {
      return authStore.userTeamId.value === teamId;
    }
    return false;
  }
 
  /**
   * Fetch player stats for a specific team in this match.
   */
  async function fetchTeamStats(teamId) {
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/stats/${teamId}`
      );
      return response?.stats || [];
    } catch (err) {
      console.error('Error fetching team stats:', err);
      return [];
    }
  }
 
  /**
   * Fetch stats for both teams.
   */
  async function fetchAllStats() {
    const match = unwrapMatchData(matchData);
    if (!match) return;
 
    statsLoading.value = true;
    try {
      const [home, away] = await Promise.all([
        fetchTeamStats(match.home_team_id),
        fetchTeamStats(match.away_team_id),
      ]);
      homeStats.value = home;
      awayStats.value = away;
    } catch (err) {
      console.error('Error fetching all stats:', err);
    } finally {
      statsLoading.value = false;
    }
  }
 
  /**
   * Record a goal for a completed match.
   */
  async function addGoal(goalData) {
    error.value = null;
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/goal`,
        {
          method: 'POST',
          body: JSON.stringify(goalData),
        }
      );
      return { success: true, event: response };
    } catch (err) {
      console.error('Error adding goal:', err);
      error.value = err.message || 'Failed to add goal';
      return { success: false, error: err.message };
    }
  }
 
  /**
   * Remove a goal event.
   */
  async function removeGoal(eventId) {
    error.value = null;
    try {
      await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/goal/${eventId}`,
        { method: 'DELETE' }
      );
      return { success: true };
    } catch (err) {
      console.error('Error removing goal:', err);
      error.value = err.message || 'Failed to remove goal';
      return { success: false, error: err.message };
    }
  }
 
  /**
   * Record a substitution for a completed match.
   */
  async function addSubstitution(subData) {
    error.value = null;
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/substitution`,
        {
          method: 'POST',
          body: JSON.stringify(subData),
        }
      );
      return { success: true, event: response };
    } catch (err) {
      console.error('Error adding substitution:', err);
      error.value = err.message || 'Failed to add substitution';
      return { success: false, error: err.message };
    }
  }
 
  /**
   * Remove a substitution event.
   */
  async function removeSubstitution(eventId) {
    error.value = null;
    try {
      await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/substitution/${eventId}`,
        { method: 'DELETE' }
      );
      return { success: true };
    } catch (err) {
      console.error('Error removing substitution:', err);
      error.value = err.message || 'Failed to remove substitution';
      return { success: false, error: err.message };
    }
  }
 
  /**
   * Record a card (yellow or red) for a completed match.
   */
  async function addCard(cardData) {
    error.value = null;
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/card`,
        {
          method: 'POST',
          body: JSON.stringify(cardData),
        }
      );
      return { success: true, event: response };
    } catch (err) {
      console.error('Error adding card:', err);
      error.value = err.message || 'Failed to add card';
      return { success: false, error: err.message };
    }
  }
 
  /**
   * Remove a card event.
   */
  async function removeCard(eventId) {
    error.value = null;
    try {
      await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/card/${eventId}`,
        { method: 'DELETE' }
      );
      return { success: true };
    } catch (err) {
      console.error('Error removing card:', err);
      error.value = err.message || 'Failed to remove card';
      return { success: false, error: err.message };
    }
  }
 
  /**
   * Batch save player stats (started, minutes_played) for a team.
   */
  async function savePlayerStats(teamId, entries) {
    saving.value = true;
    error.value = null;
    try {
      const response = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/matches/${matchId}/post-match/stats/${teamId}`,
        {
          method: 'PUT',
          body: JSON.stringify({ players: entries }),
        }
      );
 
      // Update local state
      const match = unwrapMatchData(matchData);
      if (match) {
        if (teamId === match.home_team_id) {
          homeStats.value = response?.stats || [];
        } else if (teamId === match.away_team_id) {
          awayStats.value = response?.stats || [];
        }
      }
 
      return { success: true, stats: response?.stats };
    } catch (err) {
      console.error('Error saving player stats:', err);
      error.value = err.message || 'Failed to save player stats';
      return { success: false, error: err.message };
    } finally {
      saving.value = false;
    }
  }
 
  return {
    homeStats,
    awayStats,
    statsLoading,
    saving,
    error,
    canEditTeam,
    fetchTeamStats,
    fetchAllStats,
    addGoal,
    removeGoal,
    addSubstitution,
    removeSubstitution,
    addCard,
    removeCard,
    savePlayerStats,
  };
}