analytica-frontend-lib
Version:
Repositório público dos componentes utilizados nas plataformas da Analytica Ensino
247 lines (243 loc) • 9.17 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/store/notificationStore.ts
var _zustand = require('zustand');
var _middleware = require('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: _nullishCoalesce(backendNotification.actionLink, () => ( null)),
linkImg: _nullishCoalesce(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 _zustand.create.call(void 0, )(
_middleware.devtools.call(void 0,
(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 (e) {
}
},
markAsRead: async (id) => {
const { notifications } = get();
const notification = notifications.find((n) => n.id === id);
if (_optionalChain([notification, 'optionalAccess', _ => _.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"
}
)
);
};
exports.formatTimeAgo = formatTimeAgo; exports.createNotificationStore = createNotificationStore;
//# sourceMappingURL=chunk-BXORK7GM.js.map