| 1 | import { BaseSessionMetadata } from "core"; |
| 2 | import type { RemoteSessionMetadata } from "core/control-plane/client"; |
| 3 | |
| 4 | export const parseDate = (date: string): Date => { |
| 5 | let dateObj = new Date(date); |
| 6 | if (isNaN(dateObj.getTime())) { |
| 7 | dateObj = new Date(parseInt(date)); |
| 8 | } |
| 9 | return dateObj; |
| 10 | }; |
| 11 | |
| 12 | export interface SessionGroup { |
| 13 | label: string; |
| 14 | sessions: (BaseSessionMetadata | RemoteSessionMetadata)[]; |
| 15 | } |
| 16 | |
| 17 | export const groupSessionsByDate = ( |
| 18 | sessions: (BaseSessionMetadata | RemoteSessionMetadata)[], |
| 19 | ): SessionGroup[] => { |
| 20 | const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24); |
| 21 | const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7); |
| 22 | const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30); |
| 23 | |
| 24 | const groups: SessionGroup[] = []; |
| 25 | |
| 26 | const todaySessions = sessions.filter( |
| 27 | (session) => parseDate(session.dateCreated) > yesterday, |
| 28 | ); |
| 29 | const weekSessions = sessions.filter((session) => { |
| 30 | const date = parseDate(session.dateCreated); |
| 31 | return date <= yesterday && date > lastWeek; |
| 32 | }); |
| 33 | const monthSessions = sessions.filter((session) => { |
| 34 | const date = parseDate(session.dateCreated); |
| 35 | return date <= lastWeek && date > lastMonth; |
| 36 | }); |
| 37 | const olderSessions = sessions.filter( |
| 38 | (session) => parseDate(session.dateCreated) <= lastMonth, |
| 39 | ); |
| 40 | |
| 41 | if (todaySessions.length > 0) |
| 42 | groups.push({ label: "Today", sessions: todaySessions }); |
| 43 | if (weekSessions.length > 0) |
| 44 | groups.push({ label: "This Week", sessions: weekSessions }); |
| 45 | if (monthSessions.length > 0) |
| 46 | groups.push({ label: "This Month", sessions: monthSessions }); |
| 47 | if (olderSessions.length > 0) |
| 48 | groups.push({ label: "Older", sessions: olderSessions }); |
| 49 | |
| 50 | return groups; |
| 51 | }; |