All files / src/viewmodels/notifications useNotificationsViewModel.ts

5.63% Statements 8/142
100% Branches 0/0
0% Functions 0/1
5.63% Lines 8/142

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 1811x 1x 1x               1x 1x 1x                                       1x   1x                                                                                                                                                                                                                                                                                                    
import { useCallback, useEffect, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import {
  deleteAllNotifications,
  deleteNotification,
  listNotifications,
  markAllNotificationsRead,
  markNotificationRead,
} from '@/services/notificationService';
import type { NotificationItem } from '@/models/notification';
import { ApiError } from '@/services/api';
import i18n from '@/i18n';
import {
  emitUnreadCountDelta,
  emitUnreadCountValue,
} from '@/utils/notificationUnreadEvents';
 
export interface NotificationsViewModel {
  notifications: NotificationItem[];
  isLoading: boolean;
  isLoadingMore: boolean;
  hasNext: boolean;
  error: string | null;
  fetchNotifications: () => Promise<void>;
  loadMore: () => Promise<void>;
  markRead: (id: string) => Promise<void>;
  markAllRead: () => Promise<void>;
  deleteOne: (id: string) => Promise<void>;
  deleteAll: () => Promise<void>;
  dismissError: () => void;
}
 
const PAGE_SIZE = 20;
 
export function useNotificationsViewModel(): NotificationsViewModel {
  const { token } = useAuth();
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [hasNext, setHasNext] = useState(false);
  const [error, setError] = useState<string | null>(null);
 
  const fetchNotifications = useCallback(async () => {
    if (!token) {
      setNotifications([]);
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    setError(null);
    try {
      const response = await listNotifications(token, { limit: PAGE_SIZE });
      setNotifications(response.items ?? []);
      setNextCursor(response.page_info.next_cursor);
      setHasNext(response.page_info.has_next);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : i18n.t('errors.unexpected'));
    } finally {
      setIsLoading(false);
    }
  }, [token]);
 
  const loadMore = useCallback(async () => {
    if (!token || !nextCursor || isLoadingMore) return;
    setIsLoadingMore(true);
    try {
      const response = await listNotifications(token, {
        limit: PAGE_SIZE,
        cursor: nextCursor,
      });
      setNotifications((prev) => [...prev, ...(response.items ?? [])]);
      setNextCursor(response.page_info.next_cursor);
      setHasNext(response.page_info.has_next);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : i18n.t('errors.unexpected'));
    } finally {
      setIsLoadingMore(false);
    }
  }, [token, nextCursor, isLoadingMore]);
 
  const markRead = useCallback(
    async (id: string) => {
      if (!token) return;
      const wasUnread = notifications.some((n) => n.id === id && !n.is_read);
      if (wasUnread) emitUnreadCountDelta(-1);
      // Optimistic update
      setNotifications((prev) =>
        prev.map((n) =>
          n.id === id && !n.is_read
            ? { ...n, is_read: true, read_at: new Date().toISOString() }
            : n,
        ),
      );
      try {
        await markNotificationRead(id, token);
      } catch {
        if (wasUnread) emitUnreadCountDelta(1);
        // Roll back on failure
        setNotifications((prev) =>
          prev.map((n) => (n.id === id ? { ...n, is_read: false, read_at: null } : n)),
        );
      }
    },
    [token, notifications],
  );
 
  const markAllRead = useCallback(async () => {
    if (!token) return;
    const previous = notifications;
    const previousUnreadCount = previous.filter((n) => !n.is_read).length;
    if (previousUnreadCount > 0) emitUnreadCountValue(0);
    setNotifications((prev) =>
      prev.map((n) =>
        n.is_read ? n : { ...n, is_read: true, read_at: new Date().toISOString() },
      ),
    );
    try {
      await markAllNotificationsRead(token);
    } catch (err) {
      setNotifications(previous);
      if (previousUnreadCount > 0) emitUnreadCountValue(previousUnreadCount);
      setError(err instanceof ApiError ? err.message : i18n.t('errors.unexpected'));
    }
  }, [token, notifications]);
 
  const deleteOne = useCallback(
    async (id: string) => {
      if (!token) return;
      const previous = notifications;
      const deletedWasUnread = previous.some((n) => n.id === id && !n.is_read);
      if (deletedWasUnread) emitUnreadCountDelta(-1);
      setNotifications((prev) => prev.filter((n) => n.id !== id));
      try {
        await deleteNotification(id, token);
      } catch (err) {
        setNotifications(previous);
        if (deletedWasUnread) emitUnreadCountDelta(1);
        setError(err instanceof ApiError ? err.message : i18n.t('errors.unexpected'));
      }
    },
    [token, notifications],
  );
 
  const deleteAll = useCallback(async () => {
    if (!token) return;
    const previous = notifications;
    const previousUnreadCount = previous.filter((n) => !n.is_read).length;
    if (previousUnreadCount > 0) emitUnreadCountValue(0);
    setNotifications([]);
    try {
      await deleteAllNotifications(token);
    } catch (err) {
      setNotifications(previous);
      if (previousUnreadCount > 0) emitUnreadCountValue(previousUnreadCount);
      setError(err instanceof ApiError ? err.message : i18n.t('errors.unexpected'));
    }
  }, [token, notifications]);
 
  const dismissError = useCallback(() => setError(null), []);
 
  useEffect(() => {
    fetchNotifications();
  }, [fetchNotifications]);
 
  return {
    notifications,
    isLoading,
    isLoadingMore,
    hasNext,
    error,
    fetchNotifications,
    loadMore,
    markRead,
    markAllRead,
    deleteOne,
    deleteAll,
    dismissError,
  };
}