diff --git a/src/app/objectives/page.tsx b/src/app/objectives/page.tsx index bbe3bee..2e2d36e 100644 --- a/src/app/objectives/page.tsx +++ b/src/app/objectives/page.tsx @@ -4,6 +4,7 @@ import Link from 'next/link'; import { getUserOKRs } from '@/services/okrs'; import { Card } from '@/components/ui'; import { ObjectivesList } from '@/components/okrs/ObjectivesList'; +import { comparePeriods } from '@/lib/okr-utils'; export default async function ObjectivesPage() { const session = await auth(); @@ -27,16 +28,7 @@ export default async function ObjectivesPage() { {} as Record ); - const periods = Object.keys(okrsByPeriod).sort((a, b) => { - // Sort periods: extract year and quarter/period - const aMatch = a.match(/(\d{4})/); - const bMatch = b.match(/(\d{4})/); - if (aMatch && bMatch) { - const yearDiff = parseInt(bMatch[1]) - parseInt(aMatch[1]); - if (yearDiff !== 0) return yearDiff; - } - return b.localeCompare(a); - }); + const periods = Object.keys(okrsByPeriod).sort(comparePeriods); return (
diff --git a/src/lib/okr-utils.ts b/src/lib/okr-utils.ts index 2a0554c..37a5beb 100644 --- a/src/lib/okr-utils.ts +++ b/src/lib/okr-utils.ts @@ -14,3 +14,45 @@ export function getCurrentQuarterPeriod(date: Date = new Date()): string { export function isCurrentQuarterPeriod(period: string, date: Date = new Date()): boolean { return period === getCurrentQuarterPeriod(date); } + +/** + * Parse a period string to extract year and quarter + * Returns { year, quarter } or null if format is not recognized + * Supports formats like "Q1 2025", "Q2 2024", etc. + */ +function parsePeriod(period: string): { year: number; quarter: number } | null { + // Match format "Q{quarter} {year}" + const match = period.match(/^Q(\d)\s+(\d{4})$/); + if (match) { + return { + year: parseInt(match[2], 10), + quarter: parseInt(match[1], 10), + }; + } + return null; +} + +/** + * Compare two period strings for sorting (most recent first) + * Returns negative if a should come before b, positive if after, 0 if equal + */ +export function comparePeriods(a: string, b: string): number { + const aParsed = parsePeriod(a); + const bParsed = parsePeriod(b); + + // If both can be parsed, compare by year then quarter + if (aParsed && bParsed) { + // Most recent year first + const yearDiff = bParsed.year - aParsed.year; + if (yearDiff !== 0) return yearDiff; + // Most recent quarter first (same year) + return bParsed.quarter - aParsed.quarter; + } + + // Fallback: if one can be parsed, prioritize it + if (aParsed && !bParsed) return -1; + if (!aParsed && bParsed) return 1; + + // Both unparseable: fallback to string comparison (descending) + return b.localeCompare(a); +}