All files / src/composables useTeamFollows.js

98.2% Statements 164/167
94.82% Branches 55/58
100% Functions 11/11
98.2% Lines 164/167

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 1891x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x   1x   81x 81x 81x 1x 1x 1x 1x 1x   80x 80x 80x 80x 80x 80x 81x 81x 81x 81x 81x       81x 80x 80x 81x   1x 167x   167x 64x 61x 61x 61x 61x 167x   167x 20x 20x 20x 20x 167x   167x 167x   167x 167x 167x 546x 546x 37x 37x 12x 37x 167x   167x 167x 167x   167x 15x 15x   15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 11x 11x 15x 3x 3x 3x 3x 3x 167x   167x 167x 167x 167x 9x 9x   9x 9x 9x 10x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 9x 1x 1x 1x 1x 1x 167x   167x 13x 13x 13x 167x   167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x   1x 1x 61x 61x 61x 61x 61x 61x 61x  
/**
 * Team-follows composable (SB-55).
 *
 * Singleton reactive state shared by every FollowButton instance and the
 * NotificationsCard "Teams you follow" list. Mirrors the useAuthStore
 * pattern: module-level reactive state, useTeamFollows() returns the
 * same refs every call.
 *
 * Backend endpoints (all idempotent):
 *   GET    /api/users/me/team-follows           → { follows: [{ team_id, age_group_id, team, age_group, ... }] }
 *   POST   /api/users/me/team-follows           → 201; body { team_id, age_group_id? }
 *   DELETE /api/users/me/team-follows/{id}[?age_group_id=N] → 204
 *
 * A follow is for match alerts. `age_group_id` null follows every age group
 * of the team; a value follows that squad only (SB-1608, SB-1618).
 */
 
import { reactive, computed } from 'vue';
import { useAuthStore } from '../stores/auth';
import { getApiBaseUrl } from '../config/api';
 
const state = reactive({
  followedTeamIds: new Set(),
  follows: [],
  loaded: false,
  loading: false,
  error: null,
});
 
let inflightLoad = null;
 
async function fetchFollows() {
  const authStore = useAuthStore();
  if (!authStore.isAuthenticated.value) {
    state.followedTeamIds = new Set();
    state.follows = [];
    state.loaded = true;
    return;
  }
 
  state.loading = true;
  state.error = null;
  try {
    const data = await authStore.apiRequest(
      `${getApiBaseUrl()}/api/users/me/team-follows`
    );
    const rows = data?.follows || [];
    state.follows = rows;
    state.followedTeamIds = new Set(rows.map(r => r.team_id));
    state.loaded = true;
  } catch (err) {
    state.error = err.message || String(err);
    state.followedTeamIds = new Set();
    state.follows = [];
  } finally {
    state.loading = false;
  }
}
 
export function useTeamFollows() {
  const authStore = useAuthStore();
 
  const ensureLoaded = () => {
    if (state.loaded || state.loading) return inflightLoad || Promise.resolve();
    inflightLoad = fetchFollows().finally(() => {
      inflightLoad = null;
    });
    return inflightLoad;
  };
 
  const refresh = () => {
    inflightLoad = fetchFollows().finally(() => {
      inflightLoad = null;
    });
    return inflightLoad;
  };
 
  const rowsFor = teamId =>
    state.follows.filter(r => Number(r.team_id) === Number(teamId));
 
  // With an age group: following that squad, directly or through a
  // whole-team follow. Without: following any part of the team.
  const isFollowing = (teamId, ageGroupId = null) => {
    const rows = rowsFor(teamId);
    if (ageGroupId == null) return rows.length > 0;
    return rows.some(
      r =>
        r.age_group_id == null || Number(r.age_group_id) === Number(ageGroupId)
    );
  };
 
  // True when the squad is covered only by a whole-team follow.
  const followsWholeTeam = teamId =>
    rowsFor(teamId).some(r => r.age_group_id == null);
 
  const follow = async (teamId, ageGroupId = null) => {
    const id = Number(teamId);
    if (isFollowing(id, ageGroupId)) return { success: true };
 
    const age = ageGroupId == null ? null : Number(ageGroupId);
    const before = state.follows;
    state.follows = [...before, { team_id: id, age_group_id: age }];
    state.followedTeamIds = new Set([...state.followedTeamIds, id]);
    state.error = null;
    try {
      await authStore.apiRequest(
        `${getApiBaseUrl()}/api/users/me/team-follows`,
        {
          method: 'POST',
          body: JSON.stringify(
            age == null ? { team_id: id } : { team_id: id, age_group_id: age }
          ),
        }
      );
      refresh();
      return { success: true };
    } catch (err) {
      state.follows = before;
      state.followedTeamIds = new Set(before.map(r => r.team_id));
      state.error = err.message || String(err);
      return { success: false, error: state.error };
    }
  };
 
  // With an age group, stop that squad only; if it is covered by a whole-team
  // follow, that follow goes (it cannot be narrowed without knowing every
  // age group the team plays). Without, stop every follow of the team.
  const unfollow = async (teamId, ageGroupId = null) => {
    const id = Number(teamId);
    if (!isFollowing(id, ageGroupId)) return { success: true };
 
    const squadOnly = ageGroupId != null && !followsWholeTeam(id);
    const removed = state.follows.filter(
      r =>
        Number(r.team_id) === id &&
        (!squadOnly || Number(r.age_group_id) === Number(ageGroupId))
    );
    const before = state.follows;
    state.follows = before.filter(r => !removed.includes(r));
    state.followedTeamIds = new Set(state.follows.map(r => r.team_id));
    state.error = null;
    const query = squadOnly ? `?age_group_id=${Number(ageGroupId)}` : '';
    try {
      await authStore.apiRequest(
        `${getApiBaseUrl()}/api/users/me/team-follows/${id}${query}`,
        { method: 'DELETE' }
      );
      refresh();
      return { success: true };
    } catch (err) {
      state.follows = before;
      state.followedTeamIds = new Set(before.map(r => r.team_id));
      state.error = err.message || String(err);
      return { success: false, error: state.error };
    }
  };
 
  const toggle = async (teamId, ageGroupId = null) => {
    return isFollowing(teamId, ageGroupId)
      ? unfollow(teamId, ageGroupId)
      : follow(teamId, ageGroupId);
  };
 
  return {
    follows: computed(() => state.follows),
    followedTeamIds: computed(() => state.followedTeamIds),
    loaded: computed(() => state.loaded),
    loading: computed(() => state.loading),
    error: computed(() => state.error),
    ensureLoaded,
    refresh,
    isFollowing,
    followsWholeTeam,
    follow,
    unfollow,
    toggle,
  };
}
 
// Test-only: reset module-level singleton between tests.
export function _resetTeamFollowsForTest() {
  state.followedTeamIds = new Set();
  state.follows = [];
  state.loaded = false;
  state.loading = false;
  state.error = null;
  inflightLoad = null;
}