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