UNPKG

analytica-frontend-lib

Version:

Repositório público dos componentes utilizados nas plataformas da Analytica Ensino

247 lines (246 loc) 8.29 kB
// src/store/notificationStore.ts import { create } from "zustand"; import { devtools } from "zustand/middleware"; var mapBackendNotification = (backendNotification) => { let type = "GENERAL"; let entityType = null; if (backendNotification.entityType) { switch (backendNotification.entityType.toUpperCase()) { case "ACTIVITY" /* ACTIVITY */: type = "ACTIVITY"; entityType = "ACTIVITY" /* ACTIVITY */; break; case "TRAIL" /* TRAIL */: type = "TRAIL"; entityType = "TRAIL" /* TRAIL */; break; case "RECOMMENDEDCLASS" /* RECOMMENDEDCLASS */: type = "RECOMMENDEDCLASS"; entityType = "RECOMMENDEDCLASS" /* RECOMMENDEDCLASS */; break; default: break; } } return { id: backendNotification.id, title: backendNotification.title, message: backendNotification.description, type, isRead: backendNotification.read, createdAt: new Date(backendNotification.createdAt), entityType, entityId: backendNotification.entityId, sender: backendNotification.sender, activity: backendNotification.activity, recommendedClass: backendNotification.recommendedClass, actionLink: backendNotification.actionLink ?? null, linkImg: backendNotification.linkImg ?? null }; }; var groupNotificationsByTime = (notifications) => { const now = /* @__PURE__ */ new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1e3); const sortDesc = (a, b) => +new Date(b.createdAt) - +new Date(a.createdAt); const todayNotifications = notifications.filter((notification) => new Date(notification.createdAt) >= today).sort(sortDesc); const lastWeekNotifications = notifications.filter( (notification) => new Date(notification.createdAt) >= lastWeek && new Date(notification.createdAt) < today ).sort(sortDesc); const olderNotifications = notifications.filter((notification) => new Date(notification.createdAt) < lastWeek).sort(sortDesc); const groups = []; if (todayNotifications.length > 0) { groups.push({ label: "Hoje", notifications: todayNotifications }); } if (lastWeekNotifications.length > 0) { groups.push({ label: "\xDAltima semana", notifications: lastWeekNotifications }); } if (olderNotifications.length > 0) { groups.push({ label: "Mais antigas", notifications: olderNotifications }); } return groups; }; var formatTimeAgo = (date) => { const now = /* @__PURE__ */ new Date(); const diffInMs = now.getTime() - new Date(date).getTime(); const diffInHours = Math.floor(diffInMs / (1e3 * 60 * 60)); const diffInDays = Math.floor(diffInMs / (1e3 * 60 * 60 * 24)); if (diffInHours < 24) { return `H\xE1 ${diffInHours}h`; } else if (diffInDays < 30) { const day = new Date(date).getDate(); const months = [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez" ]; const month = months[new Date(date).getMonth()]; return `${day} ${month}`; } return new Date(date).toLocaleDateString("pt-BR"); }; var createNotificationStore = (apiClient) => { return create()( devtools( (set, get) => ({ // Initial state notifications: [], unreadCount: 0, loading: false, error: null, hasMore: true, currentPage: 1, // Actions fetchNotifications: async (params = {}) => { set({ loading: true, error: null }); try { const response = await apiClient.get( "/notifications", { params: { ...params } } ); const mappedNotifications = response.data.notifications.map( mapBackendNotification ); const page = response.data.pagination.page; const totalPages = response.data.pagination.totalPages; const merged = params.page && params.page > 1 ? [...get().notifications, ...mappedNotifications] : mappedNotifications; const deduped = Array.from( new Map(merged.map((n) => [n.id, n])).values() ); const localUnread = deduped.filter((n) => !n.isRead).length; set({ notifications: deduped, unreadCount: Math.max(localUnread, get().unreadCount), hasMore: page < totalPages, currentPage: page, loading: false }); } catch (error) { console.error("Error fetching notifications:", error); set({ error: "Erro ao carregar notifica\xE7\xF5es", loading: false }); } }, fetchUnreadCount: async () => { try { const response = await apiClient.get( "/notifications", { params: { read: false, limit: 1, page: 1 } } ); set({ unreadCount: response.data.pagination.total }); } catch { } }, markAsRead: async (id) => { const { notifications } = get(); const notification = notifications.find((n) => n.id === id); if (notification?.isRead) { return; } try { await apiClient.patch(`/notifications/${id}`, { read: true }); const updatedNotifications = notifications.map( (notification2) => notification2.id === id ? { ...notification2, isRead: true } : notification2 ); const unreadCount = updatedNotifications.filter( (n) => !n.isRead ).length; set({ notifications: updatedNotifications, unreadCount }); } catch (error) { console.error("Error marking notification as read:", error); set({ error: "Erro ao marcar notifica\xE7\xE3o como lida" }); } }, markAllAsRead: async () => { const { notifications } = get(); try { const unreadNotifications = notifications.filter((n) => !n.isRead); await Promise.all( unreadNotifications.map( (notification) => apiClient.patch(`/notifications/${notification.id}`, { read: true }) ) ); const updatedNotifications = notifications.map((notification) => ({ ...notification, isRead: true })); set({ notifications: updatedNotifications, unreadCount: 0 }); } catch (error) { console.error("Error marking all notifications as read:", error); set({ error: "Erro ao marcar todas as notifica\xE7\xF5es como lidas" }); } }, deleteNotification: async (id) => { const { notifications } = get(); try { await apiClient.delete(`/notifications/${id}`); const updatedNotifications = notifications.filter( (notification) => notification.id !== id ); const unreadCount = updatedNotifications.filter( (n) => !n.isRead ).length; set({ notifications: updatedNotifications, unreadCount }); } catch (error) { console.error("Error deleting notification:", error); set({ error: "Erro ao deletar notifica\xE7\xE3o" }); } }, clearNotifications: () => { set({ notifications: [], unreadCount: 0, hasMore: false, currentPage: 1 }); }, resetError: () => { set({ error: null }); }, getGroupedNotifications: () => { const { notifications } = get(); return groupNotificationsByTime(notifications); } }), { name: "notification-store" } ) ); }; export { formatTimeAgo, createNotificationStore }; //# sourceMappingURL=chunk-6Y3UKXTF.mjs.map