All files / src/composables useNotificationPreferences.js

95.37% Statements 165/173
78.78% Branches 26/33
85.71% Functions 6/7
95.37% Lines 165/173

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 1931x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x   12x 12x 12x 1x 1x 1x 1x   11x 11x 11x 11x 11x 11x 11x 11x 12x 12x 12x 12x     12x 11x 11x 12x   1x 13x   13x 15x 12x 12x 12x 12x 13x   13x         13x   13x 4x 1x 1x 3x 4x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x   13x 13x 13x 13x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x   13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x   1x 1x 12x 12x 12x 12x 12x 12x  
/**
 * Notification-preferences composable (SB-57).
 *
 * Singleton reactive state for per-event push opt-in flags. Mirrors the
 * useTeamFollows.js pattern from SB-55 — module-level reactive state, every
 * call to useNotificationPreferences() returns the same refs.
 *
 * Backend (idempotent, lazy-default on the server):
 *   GET /api/users/me/notification-preferences   → { preferences: {event_type: bool, ...} }
 *   PUT /api/users/me/notification-preferences   body: { preferences: {...} } → same shape
 *
 * Defaults must mirror backend/notifications/preferences.py so the UI can
 * render correctly before the first GET completes.
 */
 
import { reactive, computed } from 'vue';
import { useAuthStore } from '../stores/auth';
import { getApiBaseUrl } from '../config/api';
 
export const EVENT_TYPES = Object.freeze([
  'kickoff',
  'goal',
  'halftime',
  'fulltime',
  'yellow_card',
  'red_card',
]);
 
export const DEFAULT_PREFERENCES = Object.freeze({
  kickoff: true,
  goal: true,
  halftime: true,
  fulltime: true,
  yellow_card: false,
  red_card: false,
});
 
const state = reactive({
  preferences: { ...DEFAULT_PREFERENCES },
  loaded: false,
  loading: false,
  error: null,
});
 
let inflightLoad = null;
 
async function fetchPreferences() {
  const authStore = useAuthStore();
  if (!authStore.isAuthenticated.value) {
    state.preferences = { ...DEFAULT_PREFERENCES };
    state.loaded = true;
    return;
  }
 
  state.loading = true;
  state.error = null;
  try {
    const data = await authStore.apiRequest(
      `${getApiBaseUrl()}/api/users/me/notification-preferences`
    );
    state.preferences = {
      ...DEFAULT_PREFERENCES,
      ...(data?.preferences || {}),
    };
    state.loaded = true;
  } catch (err) {
    state.error = err.message || String(err);
    state.preferences = { ...DEFAULT_PREFERENCES };
  } finally {
    state.loading = false;
  }
}
 
export function useNotificationPreferences() {
  const authStore = useAuthStore();
 
  const ensureLoaded = () => {
    if (state.loaded || state.loading) return inflightLoad || Promise.resolve();
    inflightLoad = fetchPreferences().finally(() => {
      inflightLoad = null;
    });
    return inflightLoad;
  };
 
  const refresh = () => {
    inflightLoad = fetchPreferences().finally(() => {
      inflightLoad = null;
    });
    return inflightLoad;
  };
 
  const setPreference = async (eventType, enabled) => {
    if (!EVENT_TYPES.includes(eventType)) {
      return { success: false, error: `Unknown event_type: ${eventType}` };
    }
    const prev = state.preferences[eventType];
    if (prev === enabled) return { success: true };
 
    // Optimistic
    state.preferences = { ...state.preferences, [eventType]: enabled };
    state.error = null;
    try {
      const data = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/users/me/notification-preferences`,
        {
          method: 'PUT',
          body: JSON.stringify({ preferences: { [eventType]: enabled } }),
        }
      );
      // Backend echoes the merged state — trust it over the optimistic guess
      // in case other devices changed prefs in parallel.
      if (data?.preferences) {
        state.preferences = {
          ...DEFAULT_PREFERENCES,
          ...data.preferences,
        };
      }
      return { success: true };
    } catch (err) {
      state.preferences = { ...state.preferences, [eventType]: prev };
      state.error = err.message || String(err);
      return { success: false, error: state.error };
    }
  };
 
  // Combined cards toggle — sets yellow_card and red_card together.
  // Backend stores them separately so SB-58/future per-card prefs stay
  // possible without a schema change.
  const setCards = async enabled => {
    const prevYellow = state.preferences.yellow_card;
    const prevRed = state.preferences.red_card;
    if (prevYellow === enabled && prevRed === enabled) {
      return { success: true };
    }
 
    state.preferences = {
      ...state.preferences,
      yellow_card: enabled,
      red_card: enabled,
    };
    state.error = null;
    try {
      const data = await authStore.apiRequest(
        `${getApiBaseUrl()}/api/users/me/notification-preferences`,
        {
          method: 'PUT',
          body: JSON.stringify({
            preferences: { yellow_card: enabled, red_card: enabled },
          }),
        }
      );
      if (data?.preferences) {
        state.preferences = {
          ...DEFAULT_PREFERENCES,
          ...data.preferences,
        };
      }
      return { success: true };
    } catch (err) {
      state.preferences = {
        ...state.preferences,
        yellow_card: prevYellow,
        red_card: prevRed,
      };
      state.error = err.message || String(err);
      return { success: false, error: state.error };
    }
  };
 
  return {
    preferences: computed(() => state.preferences),
    cardsEnabled: computed(
      () => state.preferences.yellow_card || state.preferences.red_card
    ),
    loaded: computed(() => state.loaded),
    loading: computed(() => state.loading),
    error: computed(() => state.error),
    ensureLoaded,
    refresh,
    setPreference,
    setCards,
  };
}
 
// Test-only: reset module-level singleton between tests.
export function _resetNotificationPreferencesForTest() {
  state.preferences = { ...DEFAULT_PREFERENCES };
  state.loaded = false;
  state.loading = false;
  state.error = null;
  inflightLoad = null;
}