From 1b935ca3058c42fdf64e5ef72b7db89d8ad6f6b8 Mon Sep 17 00:00:00 2001 From: Maksym Mykhailenko Date: Wed, 2 May 2018 17:38:19 +0800 Subject: [PATCH] fix issue #1980 - Fix sorting for notifications --- .../notifications/helpers/notifications.js | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/src/routes/notifications/helpers/notifications.js b/src/routes/notifications/helpers/notifications.js index b45e2c8e3..292f97de3 100644 --- a/src/routes/notifications/helpers/notifications.js +++ b/src/routes/notifications/helpers/notifications.js @@ -75,8 +75,9 @@ export const getNotificationsFilters = (sources) => { filterSections.push([{ title: 'Global', value: 'global', quantity: globalNotificationsQuantity }]) } const filtersBySource = [] + const sortedSources = [...sources].sort(compareSourcesByLastNotificationDate) - sources.forEach(source => { + sortedSources.forEach(source => { if (source.id !== 'global') { filtersBySource.push({ title: source.title, @@ -93,6 +94,20 @@ export const getNotificationsFilters = (sources) => { return filterSections } +/** + * Compare two sources by the first's (latest) notification date + * If source doesn't have notifications, such source is "less" than another + * + * @param {Object} s1 source object + * @param {Object} s2 source object + */ +const compareSourcesByLastNotificationDate = (s1, s2) => { + const date1 = s1.notifications && s1.notifications.length ? new Date(s1.notifications[0].date).getTime() : 0 + const date2 = s2.notifications && s2.notifications.length ? new Date(s2.notifications[0].date).getTime() : 0 + + return date2 - date1 +} + /** * Split notifications by sources * @@ -105,13 +120,13 @@ export const splitNotificationsBySources = (sources, notifications) => { const notificationsBySources = [] sources.filter(source => source.total > 0).forEach(source => { - source.notifications = _.filter(notifications, n => { - if (n.sourceId !== source.id) return false - return true - }) + source.notifications = _.filter(notifications, n => n.sourceId === source.id) notificationsBySources.push(source) }) + // source that has the most recent notification should be on top + notificationsBySources.sort(compareSourcesByLastNotificationDate) + return notificationsBySources } @@ -370,5 +385,13 @@ export const prepareNotifications = (rawNotifications) => { const notifications = _.map(bundledNotificationsWithRules, 'notification') + // sort notifications by date (newer first) + notifications.sort((n1, n2) => { + const date1 = new Date(n1.date).getTime() + const date2 = new Date(n2.date).getTime() + + return date2 - date1 + }) + return notifications }