From a1a9b0c412520efbb35a15ff185452d9f4a89dfa Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Wed, 2 Dec 2026 21:43:57 -0800 Subject: [PATCH 1/9] Replace hardcoded SERVICE_PERIOD and removed outdated servicePeriod interface --- .../src/config/servicePeriodHelpers.test.ts | 401 +++++------------- frontend/src/config/servicePeriodHelpers.ts | 137 +++--- frontend/src/config/servicePeriods.ts | 102 ----- frontend/src/config/subsidyConfig.ts | 8 +- frontend/src/lib/database.types.ts | 69 ++- frontend/src/lib/server/getServicePeriods.ts | 39 ++ frontend/src/lib/servicePeriodUtils.ts | 165 +++++++ frontend/src/types/servicePeriod.ts | 13 + 8 files changed, 474 insertions(+), 460 deletions(-) create mode 100644 frontend/src/lib/server/getServicePeriods.ts create mode 100644 frontend/src/lib/servicePeriodUtils.ts create mode 100644 frontend/src/types/servicePeriod.ts diff --git a/frontend/src/config/servicePeriodHelpers.test.ts b/frontend/src/config/servicePeriodHelpers.test.ts index cd221c9..affc786 100644 --- a/frontend/src/config/servicePeriodHelpers.test.ts +++ b/frontend/src/config/servicePeriodHelpers.test.ts @@ -1,230 +1,122 @@ /** @jest-environment node */ import { - COVERED_DATES_INBOUND, - COVERED_DATES_OUTBOUND, -} from '@/config/subsidyConfig' -import { SERVICE_PERIODS } from '@/config/servicePeriods' -import { + formatCoverageWindowForDisplay, formatDeadlineForDisplay, - formatSubsidizedWindowsForDisplay, getAllowedDirectionsForDate, getDerivedCoveredDates, isDateCovered, isDirectionAllowedForDate, isFlightPastDeadline, - isInSubsidizedWindow, } from '@/config/servicePeriodHelpers' -const springPeriod = SERVICE_PERIODS.find( - (period) => period.id === 'spring-2026', -)! -const summerPeriod = SERVICE_PERIODS.find( - (period) => period.id === 'summer-2026', -)! -const fallArrivalPeriod = SERVICE_PERIODS.find( - (period) => period.id === 'fall-arrival-2026', -)! - -describe('SERVICE_PERIODS', () => { - it('has unique ids and required fields on every row', () => { - const ids = SERVICE_PERIODS.map((period) => period.id) - expect(ids.length).toBeGreaterThan(0) - expect(new Set(ids).size).toBe(ids.length) - - for (const period of SERVICE_PERIODS) { - expect(period.name).toBeTruthy() - expect(period.allowedDirections.length).toBeGreaterThan(0) - expect(period.buffered.start).toMatch(/^\d{4}-\d{2}-\d{2}$/) - expect(period.buffered.end).toMatch(/^\d{4}-\d{2}-\d{2}$/) - expect(period.deadline).toMatch(/T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/) - } - }) +import { + getServicePeriods, + type ServicePeriod, +} from '@/lib/server/getServicePeriods' + +jest.mock('react', () => ({ + ...jest.requireActual('react'), + cache: (fn: any) => fn, +})) + +jest.mock('@/lib/server/getServicePeriods') + +const mockGetServicePeriods = jest.mocked(getServicePeriods) + +const mockPeriods: ServicePeriod[] = [ + { + id: 'spring-2026-outbound', + name: 'Spring Break', + coverage_start: '2026-03-13', + coverage_end: '2026-03-15', + outbound: true, + inbound: false, + deadline: '2026-03-06T23:59:59-08:00', + }, + { + id: 'spring-2026-inbound', + name: 'Spring Break', + coverage_start: '2026-03-20', + coverage_end: '2026-03-22', + outbound: false, + inbound: true, + deadline: '2026-03-06T23:59:59-08:00', + }, +] + +beforeEach(() => { + jest.clearAllMocks() + mockGetServicePeriods.mockResolvedValue(mockPeriods) +}) - it('includes split winter outbound and return rows', () => { - expect( - SERVICE_PERIODS.some((period) => period.id === 'winter-2025-outbound'), - ).toBe(true) - expect( - SERVICE_PERIODS.some((period) => period.id === 'winter-2026-return'), - ).toBe(true) - }) +describe('getDerivedCoveredDates', () => { + it('builds outbound and inbound MM-DD lists', async () => { + const dates = await getDerivedCoveredDates() - it('keeps golden buffered windows and deadlines for anchor breaks', () => { - expect( - SERVICE_PERIODS.find((period) => period.id === 'thanksgiving-2025'), - ).toMatchObject({ - name: 'Thanksgiving Break', - buffered: { start: '2025-11-16', end: '2025-12-01' }, - deadline: '2025-11-14T23:59:59-08:00', - }) - expect( - SERVICE_PERIODS.find((period) => period.id === 'winter-2025-outbound'), - ).toMatchObject({ - name: 'Winter Break (Outbound)', - buffered: { start: '2025-12-02', end: '2025-12-18' }, - deadline: '2025-12-03T23:59:59-08:00', - }) - expect( - SERVICE_PERIODS.find((period) => period.id === 'winter-2026-return'), - ).toMatchObject({ - name: 'Winter Break (Return)', - buffered: { start: '2026-01-12', end: '2026-01-26' }, - deadline: '2026-01-09T23:59:59-08:00', - }) - expect( - SERVICE_PERIODS.find((period) => period.id === 'spring-2026'), - ).toMatchObject({ - name: 'Spring Break', - buffered: { start: '2026-03-08', end: '2026-03-26' }, - deadline: '2026-03-06T23:59:59-08:00', - }) - expect( - SERVICE_PERIODS.find((period) => period.id === 'summer-2026'), - ).toMatchObject({ - name: 'Summer Break', - buffered: { start: '2026-05-07', end: '2026-05-21' }, - deadline: '2026-05-06T23:59:59-07:00', - }) - expect( - SERVICE_PERIODS.find((period) => period.id === 'fall-arrival-2026'), - ).toMatchObject({ - name: 'International Fall Arrival', - buffered: { start: '2026-08-19', end: '2026-08-19' }, - deadline: '2026-08-19T23:59:59-07:00', - }) + expect(dates.outbound).toEqual(['03-13', '03-14', '03-15']) + + expect(dates.inbound).toEqual(['03-20', '03-21', '03-22']) }) }) -describe('getDerivedCoveredDates', () => { - it('derives outbound and inbound lists from subsidized ranges', () => { - const { outbound, inbound } = getDerivedCoveredDates() - - expect(outbound).toContain('11-25') - expect(outbound).toContain('12-10') - expect(outbound).toContain('03-14') - expect(outbound).toContain('05-12') - expect(outbound).toContain('05-19') - - expect(inbound).toContain('11-30') - expect(inbound).toContain('01-18') - expect(inbound).toContain('03-21') - expect(inbound).toContain('08-19') - expect(inbound).not.toContain('07-27') - expect(inbound).not.toContain('08-10') +describe('getAllowedDirectionsForDate', () => { + it('returns outbound directions', async () => { + expect(await getAllowedDirectionsForDate('2026-03-14')).toEqual([ + 'outbound', + ]) }) - it('normalizes summer dates to zero-padded MM-DD (fixes legacy 5/12 style)', () => { - const { outbound } = getDerivedCoveredDates() - - for (const legacyDate of COVERED_DATES_OUTBOUND) { - const normalized = legacyDate.includes('/') - ? legacyDate.replace('/', '-').replace(/^(\d)-/, '0$1-') - : legacyDate - - if (normalized.startsWith('05-')) { - expect(outbound).toContain( - normalized.length === 4 ? `0${normalized}` : normalized, - ) - } - } + it('returns inbound directions', async () => { + expect(await getAllowedDirectionsForDate('2026-03-21')).toEqual(['inbound']) + }) - expect(outbound).toContain('05-12') - expect(outbound).not.toContain('5/12') + it('returns empty array for uncovered dates', async () => { + expect(await getAllowedDirectionsForDate('2026-03-18')).toEqual([]) }) - it('matches legacy subsidyConfig lists after normalization', () => { - const { outbound, inbound } = getDerivedCoveredDates() - const normalize = (value: string) => - value.includes('/') - ? value - .split('/') - .map((part, index) => (index === 0 ? part.padStart(2, '0') : part)) - .join('-') - : value - - for (const date of COVERED_DATES_OUTBOUND) { - expect(outbound).toContain(normalize(date)) - } - - for (const date of COVERED_DATES_INBOUND) { - if (date === '06-30') { - continue - } - expect(inbound).toContain(date) - } + it('returns empty array for blank dates', async () => { + expect(await getAllowedDirectionsForDate('')).toEqual([]) }) }) -describe('isDateCovered / isInSubsidizedWindow', () => { - it.each([ - ['2025-11-25', true, true], - ['2025-11-25', false, false], - ['2025-11-30', true, false], - ['2025-11-30', false, true], - ['2025-12-10', true, true], - ['2025-12-10', false, false], - ['2026-01-18', true, false], - ['2026-01-18', false, true], - ['2026-03-14', true, true], - ['2026-03-14', false, false], - ['2026-03-21', true, false], - ['2026-03-21', false, true], - ['2026-05-15', true, true], - ['2026-05-15', false, false], - ['2026-07-27', true, false], - ['2026-07-27', false, false], - ['2026-08-10', true, false], - ['2026-08-10', false, false], - ['2026-08-19', true, false], - ['2026-08-19', false, true], - ['2026-08-20', true, false], - ['2026-08-20', false, false], - ['2026-06-15', true, false], - ['2026-06-15', false, false], - ])('date %s toAirport=%s covered=%s', (date, toAirport, expected) => { - expect(isDateCovered(date, toAirport)).toBe(expected) - expect(isInSubsidizedWindow(date, toAirport)).toBe(expected) +describe('isDateCovered', () => { + it('recognizes outbound coverage', async () => { + expect(await isDateCovered('2026-03-14', true)).toBe(true) + + expect(await isDateCovered('2026-03-14', false)).toBe(false) }) -}) -describe('getAllowedDirectionsForDate', () => { - it.each([ - ['2026-03-14', ['outbound']], - ['2026-03-21', ['inbound']], - ['2026-03-18', []], - ['2026-05-15', ['outbound']], - ['2026-07-27', []], - ['2026-08-10', []], - ['2026-08-19', ['inbound']], - ['2026-08-20', []], - ['2025-11-25', ['outbound']], - ['2025-11-30', ['inbound']], - ['2025-12-10', ['outbound']], - ['2026-01-18', ['inbound']], - ])('date %s allows %j', (date, expected) => { - expect(getAllowedDirectionsForDate(date)).toEqual(expected) + it('recognizes inbound coverage', async () => { + expect(await isDateCovered('2026-03-21', false)).toBe(true) + + expect(await isDateCovered('2026-03-21', true)).toBe(false) + }) + + it('returns false for uncovered dates', async () => { + expect(await isDateCovered('2026-03-18', true)).toBe(false) + + expect(await isDateCovered('2026-03-18', false)).toBe(false) }) }) describe('isDirectionAllowedForDate', () => { - it('maps to_airport boolean to outbound/inbound policy', () => { - expect(isDirectionAllowedForDate('2026-05-15', true)).toBe(true) - expect(isDirectionAllowedForDate('2026-05-15', false)).toBe(false) - expect(isDirectionAllowedForDate('2026-07-27', false)).toBe(false) - expect(isDirectionAllowedForDate('2026-07-27', true)).toBe(false) - expect(isDirectionAllowedForDate('2026-08-19', false)).toBe(true) - expect(isDirectionAllowedForDate('2026-08-19', true)).toBe(false) - expect(isDirectionAllowedForDate('2026-03-21', false)).toBe(true) - expect(isDirectionAllowedForDate('2026-03-21', true)).toBe(false) - expect(isDirectionAllowedForDate('2026-03-18', true)).toBe(false) - expect(isDirectionAllowedForDate('2026-03-18', false)).toBe(false) + it('maps toAirport=true to outbound', async () => { + expect(await isDirectionAllowedForDate('2026-03-14', true)).toBe(true) + + expect(await isDirectionAllowedForDate('2026-03-14', false)).toBe(false) + }) + + it('maps toAirport=false to inbound', async () => { + expect(await isDirectionAllowedForDate('2026-03-21', false)).toBe(true) + + expect(await isDirectionAllowedForDate('2026-03-21', true)).toBe(false) }) }) describe('isFlightPastDeadline', () => { - it('returns not past before the spring deadline', () => { - const result = isFlightPastDeadline( + it('returns false before deadline', async () => { + const result = await isFlightPastDeadline( '2026-03-14', new Date('2026-03-05T12:00:00-08:00'), ) @@ -236,8 +128,8 @@ describe('isFlightPastDeadline', () => { }) }) - it('returns past after the spring deadline', () => { - const result = isFlightPastDeadline( + it('returns true after deadline', async () => { + const result = await isFlightPastDeadline( '2026-03-14', new Date('2026-03-07T12:00:00-08:00'), ) @@ -246,127 +138,46 @@ describe('isFlightPastDeadline', () => { expect(result.periodName).toBe('Spring Break') }) - it('applies winter outbound and return deadlines independently', () => { - const beforeWinterOutboundDeadline = isFlightPastDeadline( - '2025-12-10', - new Date('2025-12-03T12:00:00-08:00'), - ) - const afterWinterOutboundDeadline = isFlightPastDeadline( - '2025-12-10', - new Date('2025-12-04T12:00:00-08:00'), - ) - const beforeWinterReturnDeadline = isFlightPastDeadline( - '2026-01-18', - new Date('2026-01-08T12:00:00-08:00'), - ) - const afterWinterReturnDeadline = isFlightPastDeadline( - '2026-01-18', - new Date('2026-01-10T12:00:00-08:00'), - ) - - expect(beforeWinterOutboundDeadline.isPastDeadline).toBe(false) - expect(beforeWinterOutboundDeadline.periodName).toBe( - 'Winter Break (Outbound)', - ) - expect(afterWinterOutboundDeadline.isPastDeadline).toBe(true) - expect(beforeWinterReturnDeadline.isPastDeadline).toBe(false) - expect(beforeWinterReturnDeadline.periodName).toBe('Winter Break (Return)') - expect(afterWinterReturnDeadline.isPastDeadline).toBe(true) - }) - - it('uses the summer PDT deadline offset', () => { - const beforeSummerDeadline = isFlightPastDeadline( - '2026-05-15', - new Date('2026-05-06T20:00:00-07:00'), - ) - const afterSummerDeadline = isFlightPastDeadline( - '2026-05-15', - new Date('2026-05-07T08:00:00-07:00'), - ) - - expect(beforeSummerDeadline.isPastDeadline).toBe(false) - expect(afterSummerDeadline.isPastDeadline).toBe(true) - expect(afterSummerDeadline.periodName).toBe('Summer Break') - }) - - it('uses the fall arrival PDT deadline', () => { - const beforeFallArrivalDeadline = isFlightPastDeadline( - '2026-08-19', - new Date('2026-08-19T20:00:00-07:00'), - ) - const afterFallArrivalDeadline = isFlightPastDeadline( - '2026-08-19', - new Date('2026-08-20T08:00:00-07:00'), - ) - - expect(beforeFallArrivalDeadline.isPastDeadline).toBe(false) - expect(afterFallArrivalDeadline.isPastDeadline).toBe(true) - expect(afterFallArrivalDeadline.periodName).toBe( - 'International Fall Arrival', - ) + it('does not enforce deadlines outside coverage windows', async () => { + expect(await isFlightPastDeadline('2026-02-01', new Date())).toEqual({ + isPastDeadline: false, + }) }) - it('does not enforce deadlines for dates outside buffered windows', () => { - expect( - isFlightPastDeadline('2026-02-01', new Date('2026-02-01T12:00:00-08:00')), - ).toEqual({ isPastDeadline: false }) - expect(isFlightPastDeadline('', new Date())).toEqual({ + it('returns false for blank dates', async () => { + expect(await isFlightPastDeadline('')).toEqual({ isPastDeadline: false, }) }) - it('treats the exact deadline instant as not past', () => { - const atDeadline = isFlightPastDeadline( + it('treats the exact deadline instant as not past', async () => { + const result = await isFlightPastDeadline( '2026-03-14', new Date('2026-03-06T23:59:59-08:00'), ) - expect(atDeadline.isPastDeadline).toBe(false) + expect(result.isPastDeadline).toBe(false) }) }) describe('formatDeadlineForDisplay', () => { - it('formats summer deadline in PT', () => { - expect(formatDeadlineForDisplay('2026-05-06T23:59:59-07:00')).toBe( - 'Wednesday, May 6, 2026 at 11:59 PM PT', - ) - }) - - it('formats winter deadline in PT', () => { - expect(formatDeadlineForDisplay('2025-12-03T23:59:59-08:00')).toBe( - 'Wednesday, December 3, 2025 at 11:59 PM PT', + it('formats deadlines in PT', () => { + expect(formatDeadlineForDisplay('2026-03-06T23:59:59-08:00')).toBe( + 'Friday, March 6, 2026 at 11:59 PM PT', ) }) }) -describe('formatSubsidizedWindowsForDisplay', () => { - it('renders summer departures only', () => { - expect(formatSubsidizedWindowsForDisplay(summerPeriod)).toEqual([ - 'Departures: May 12-19', +describe('formatCoverageWindowForDisplay', () => { + it('formats outbound coverage windows', () => { + expect(formatCoverageWindowForDisplay(mockPeriods[0])).toEqual([ + 'Outbound: March 13-15', ]) }) - it('renders spring departures and returns', () => { - expect(formatSubsidizedWindowsForDisplay(springPeriod)).toEqual([ - 'Departures: March 13-15', - 'Returns: March 20-22', - ]) - }) - - it('renders fall arrival returns only', () => { - expect(formatSubsidizedWindowsForDisplay(fallArrivalPeriod)).toEqual([ - 'Returns: August 19', - ]) - }) - - it('renders thanksgiving cross-month return range', () => { - const thanksgiving = SERVICE_PERIODS.find( - (period) => period.id === 'thanksgiving-2025', - )! - - expect(formatSubsidizedWindowsForDisplay(thanksgiving)).toEqual([ - 'Departures: November 21-26', - 'Returns: November 29-December 1', + it('formats inbound coverage windows', () => { + expect(formatCoverageWindowForDisplay(mockPeriods[1])).toEqual([ + 'Inbound: March 20-22', ]) }) }) diff --git a/frontend/src/config/servicePeriodHelpers.ts b/frontend/src/config/servicePeriodHelpers.ts index 8edbe72..4af3ecd 100644 --- a/frontend/src/config/servicePeriodHelpers.ts +++ b/frontend/src/config/servicePeriodHelpers.ts @@ -1,9 +1,8 @@ +import { type DateRange, type TripDirection } from '@/config/servicePeriods' import { - SERVICE_PERIODS, - type DateRange, + getServicePeriods, type ServicePeriod, - type TripDirection, -} from '@/config/servicePeriods' +} from '@/lib/server/getServicePeriods' function parseCalendarDate(date: string): Date { const [year, month, day] = date.split('-').map(Number) @@ -37,23 +36,29 @@ function expandDateRangeToMMDD(range: DateRange): string[] { return dates } -export function getDerivedCoveredDates(): { +export async function getDerivedCoveredDates(): Promise<{ outbound: string[] inbound: string[] -} { +}> { + const periods = await getServicePeriods() + const outbound = new Set() const inbound = new Set() - for (const period of SERVICE_PERIODS) { - if (period.subsidized.outbound) { - for (const date of expandDateRangeToMMDD(period.subsidized.outbound)) { - outbound.add(date) - } + for (const period of periods) { + const range = { + start: period.coverage_start, + end: period.coverage_end, + } + + const dates = expandDateRangeToMMDD(range) + + if (period.outbound) { + dates.forEach((date) => outbound.add(date)) } - if (period.subsidized.inbound) { - for (const date of expandDateRangeToMMDD(period.subsidized.inbound)) { - inbound.add(date) - } + + if (period.inbound) { + dates.forEach((date) => inbound.add(date)) } } @@ -63,18 +68,31 @@ export function getDerivedCoveredDates(): { } } -export function isDateCovered(date: string, toAirport: boolean): boolean { - // Subsidy eligibility is tied to the configured service period year. The - // derived MM-DD lists remain available for legacy year-agnostic consumers. - return isDirectionAllowedForDate(date, toAirport) +export async function isDateCovered( + date: string, + toAirport: boolean, +): Promise { + // Subsidy eligibility is tied to the configured service period year. + // The derived MM-DD lists remain available for legacy year-agnostic consumers. + + return await isDirectionAllowedForDate(date, toAirport) } -function getPeriodForBufferedDate(date: string): ServicePeriod | undefined { +export async function getPeriodForDate( + date: string, +): Promise { if (!date) { return undefined } - return SERVICE_PERIODS.find((period) => isDateInRange(date, period.buffered)) + const periods = await getServicePeriods() + + return periods.find((period: ServicePeriod) => + isDateInRange(date, { + start: period.coverage_start, + end: period.coverage_end, + }), + ) } function getAllowedDirectionsForPeriodAndDate( @@ -83,31 +101,38 @@ function getAllowedDirectionsForPeriodAndDate( ): TripDirection[] { const directions: TripDirection[] = [] - if ( - period.allowedDirections.includes('outbound') && - isDateInRange(date, period.subsidized.outbound) - ) { + const isCovered = isDateInRange(date, { + start: period.coverage_start, + end: period.coverage_end, + }) + + if (!isCovered) { + return directions + } + + if (period.outbound) { directions.push('outbound') } - if ( - period.allowedDirections.includes('inbound') && - isDateInRange(date, period.subsidized.inbound) - ) { + if (period.inbound) { directions.push('inbound') } return directions } -export function getAllowedDirectionsForDate(date: string): TripDirection[] { +export async function getAllowedDirectionsForDate( + date: string, +): Promise { if (!date) { return [] } + const periods = await getServicePeriods() + const directions = new Set() - for (const period of SERVICE_PERIODS) { + for (const period of periods) { for (const direction of getAllowedDirectionsForPeriodAndDate( date, period, @@ -121,34 +146,38 @@ export function getAllowedDirectionsForDate(date: string): TripDirection[] { ) as TripDirection[] } -export function isDirectionAllowedForDate( +export async function isDirectionAllowedForDate( date: string, toAirport: boolean, -): boolean { +): Promise { const direction: TripDirection = toAirport ? 'outbound' : 'inbound' - return getAllowedDirectionsForDate(date).includes(direction) + + const allowedDirections = await getAllowedDirectionsForDate(date) + + return allowedDirections.includes(direction) } -export function isInSubsidizedWindow( +export async function isInSubsidizedWindow( date: string, toAirport: boolean, -): boolean { +): Promise { return isDateCovered(date, toAirport) } -export function isFlightPastDeadline( +export async function isFlightPastDeadline( flightDate: string, now: Date = new Date(), -): { +): Promise<{ isPastDeadline: boolean periodName?: string deadline?: Date -} { +}> { if (!flightDate) { return { isPastDeadline: false } } - const period = getPeriodForBufferedDate(flightDate) + const period = await getPeriodForDate(flightDate) + if (!period) { return { isPastDeadline: false } } @@ -203,20 +232,20 @@ function formatShortDateRange(range: DateRange): string { return `${startMonth} ${startDay}-${endMonth} ${endDay}` } -export function formatSubsidizedWindowsForDisplay( +export function formatCoverageWindowForDisplay( period: ServicePeriod, ): string[] { - const lines: string[] = [] - - if (period.subsidized.outbound) { - lines.push( - `Departures: ${formatShortDateRange(period.subsidized.outbound)}`, - ) - } - - if (period.subsidized.inbound) { - lines.push(`Returns: ${formatShortDateRange(period.subsidized.inbound)}`) - } - - return lines + const directions = [ + period.outbound && 'Outbound', + period.inbound && 'Inbound', + ] + .filter(Boolean) + .join(', ') + + return [ + `${directions}: ${formatShortDateRange({ + start: period.coverage_start, + end: period.coverage_end, + })}`, + ] } diff --git a/frontend/src/config/servicePeriods.ts b/frontend/src/config/servicePeriods.ts index 6cf76d3..683b0d6 100644 --- a/frontend/src/config/servicePeriods.ts +++ b/frontend/src/config/servicePeriods.ts @@ -4,105 +4,3 @@ export interface DateRange { start: string end: string } - -export interface ServicePeriod { - id: string - name: string - allowedDirections: TripDirection[] - subsidized: { - outbound?: DateRange - inbound?: DateRange - } - buffered: DateRange - deadline: string -} - -/** - * Canonical service-period config. Edit this file when break dates or deadlines change. - */ -export const SERVICE_PERIODS: ServicePeriod[] = [ - { - id: 'thanksgiving-2025', - name: 'Thanksgiving Break', - allowedDirections: ['outbound', 'inbound'], - subsidized: { - outbound: { start: '2025-11-21', end: '2025-11-26' }, - inbound: { start: '2025-11-29', end: '2025-12-01' }, - }, - buffered: { start: '2025-11-16', end: '2025-12-01' }, - deadline: '2025-11-14T23:59:59-08:00', - }, - { - id: 'winter-2025-outbound', - name: 'Winter Break (Outbound)', - allowedDirections: ['outbound'], - subsidized: { - outbound: { start: '2025-12-09', end: '2025-12-13' }, - }, - buffered: { start: '2025-12-02', end: '2025-12-18' }, - deadline: '2025-12-03T23:59:59-08:00', - }, - { - id: 'winter-2026-return', - name: 'Winter Break (Return)', - allowedDirections: ['inbound'], - subsidized: { - inbound: { start: '2026-01-17', end: '2026-01-21' }, - }, - buffered: { start: '2026-01-12', end: '2026-01-26' }, - deadline: '2026-01-09T23:59:59-08:00', - }, - { - id: 'spring-2026', - name: 'Spring Break', - allowedDirections: ['outbound', 'inbound'], - subsidized: { - outbound: { start: '2026-03-13', end: '2026-03-15' }, - inbound: { start: '2026-03-20', end: '2026-03-22' }, - }, - buffered: { start: '2026-03-08', end: '2026-03-26' }, - deadline: '2026-03-06T23:59:59-08:00', - }, - { - id: 'summer-2026', - name: 'Summer Break', - allowedDirections: ['outbound'], - subsidized: { - outbound: { start: '2026-05-12', end: '2026-05-19' }, - }, - buffered: { start: '2026-05-07', end: '2026-05-21' }, - deadline: '2026-05-06T23:59:59-07:00', - }, - { - id: 'fall-arrival-2026', - name: 'International Fall Arrival', - allowedDirections: ['inbound'], - subsidized: { - inbound: { start: '2026-08-19', end: '2026-08-19' }, - }, - buffered: { start: '2026-08-19', end: '2026-08-19' }, - deadline: '2026-08-19T23:59:59-07:00', - }, - { - id: 'fall-break-2026', - name: 'Fall Break', - allowedDirections: ['outbound', 'inbound'], - subsidized: { - outbound: { start: '2026-10-13', end: '2026-10-16' }, - inbound: { start: '2026-10-16', end: '2026-10-20' }, - }, - buffered: { start: '2026-10-20', end: '2026-10-26' }, - deadline: '2026-10-12T23:59:59-07:00', - }, - { - id: 'thanksgiving-2026', - name: 'Thanksgiving Break', - allowedDirections: ['outbound', 'inbound'], - subsidized: { - outbound: { start: '2026-11-23', end: '2026-11-30' }, - inbound: { start: '2026-11-23', end: '2026-11-30' }, - }, - buffered: { start: '2026-11-23', end: '2026-11-30' }, - deadline: '2026-11-20T17:30:59-08:00', - }, -] diff --git a/frontend/src/config/subsidyConfig.ts b/frontend/src/config/subsidyConfig.ts index ddf8be0..f57ad91 100644 --- a/frontend/src/config/subsidyConfig.ts +++ b/frontend/src/config/subsidyConfig.ts @@ -4,17 +4,15 @@ * Keep ML backend (e.g. config.py) in sync when breaks change. */ -import { getDerivedCoveredDates } from '@/config/servicePeriodHelpers' - export const COVERED_DATES_EXPLICIT = true -const derivedCoveredDates = getDerivedCoveredDates() +//const derivedCoveredDates = getDerivedCoveredDates() /** Allowed dates for outbound rides (to_airport true), MM-DD year-agnostic */ -export const COVERED_DATES_OUTBOUND: string[] = derivedCoveredDates.outbound +//export const COVERED_DATES_OUTBOUND: string[] = derivedCoveredDates.outbound /** Allowed dates for inbound rides (to_airport false), MM-DD year-agnostic */ -export const COVERED_DATES_INBOUND: string[] = derivedCoveredDates.inbound +//export const COVERED_DATES_INBOUND: string[] = derivedCoveredDates.inbound /** Min riders for subsidy by airport */ export const AIRPORT_MIN_RIDERS: Record = { diff --git a/frontend/src/lib/database.types.ts b/frontend/src/lib/database.types.ts index 836de4e..7580755 100644 --- a/frontend/src/lib/database.types.ts +++ b/frontend/src/lib/database.types.ts @@ -10,7 +10,32 @@ export type Database = { // Allows to automatically instantiate createClient with right options // instead of createClient(URL, KEY) __InternalSupabase: { - PostgrestVersion: '12.2.12 (cd3cf9e)' + PostgrestVersion: '12.2.12' + } + graphql_public: { + Tables: { + [_ in never]: never + } + Views: { + [_ in never]: never + } + Functions: { + graphql: { + Args: { + extensions?: Json + operationName?: string + query?: string + variables?: Json + } + Returns: Json + } + } + Enums: { + [_ in never]: never + } + CompositeTypes: { + [_ in never]: never + } } public: { Tables: { @@ -210,8 +235,8 @@ export type Database = { max_dropoff: number | null max_price: number | null opt_in: boolean | null - phone_works_in_us: string | null original_unmatched: boolean | null + phone_works_in_us: string | null terminal: string | null to_airport: boolean | null unmatched_email_sent: boolean | null @@ -242,8 +267,8 @@ export type Database = { max_dropoff?: number | null max_price?: number | null opt_in?: boolean | null - phone_works_in_us?: string | null original_unmatched?: boolean | null + phone_works_in_us?: string | null terminal?: string | null to_airport?: boolean | null unmatched_email_sent?: boolean | null @@ -274,8 +299,8 @@ export type Database = { max_dropoff?: number | null max_price?: number | null opt_in?: boolean | null - phone_works_in_us?: string | null original_unmatched?: boolean | null + phone_works_in_us?: string | null terminal?: string | null to_airport?: boolean | null unmatched_email_sent?: boolean | null @@ -582,6 +607,39 @@ export type Database = { } Relationships: [] } + ServicePeriod: { + Row: { + coverage_end: string | null + coverage_start: string | null + created_at: string | null + deadline: string | null + id: string + inbound: boolean | null + name: string | null + outbound: boolean | null + } + Insert: { + coverage_end?: string | null + coverage_start?: string | null + created_at?: string | null + deadline?: string | null + id: string + inbound?: boolean | null + name?: string | null + outbound?: boolean | null + } + Update: { + coverage_end?: string | null + coverage_start?: string | null + created_at?: string | null + deadline?: string | null + id?: string + inbound?: boolean | null + name?: string | null + outbound?: boolean | null + } + Relationships: [] + } Users: { Row: { admin_scope: string | null @@ -1023,6 +1081,9 @@ export type CompositeTypes< : never export const Constants = { + graphql_public: { + Enums: {}, + }, public: { Enums: {}, }, diff --git a/frontend/src/lib/server/getServicePeriods.ts b/frontend/src/lib/server/getServicePeriods.ts new file mode 100644 index 0000000..feb9abe --- /dev/null +++ b/frontend/src/lib/server/getServicePeriods.ts @@ -0,0 +1,39 @@ +// lib/server/getservicePeriods.ts + +import { createServiceRoleClient } from '@/lib/server/serviceRole' +import { cache } from 'react' + +export interface ServicePeriod { + id: string + name: string + outbound: boolean + inbound: boolean + coverage_start: string + coverage_end: string + deadline: string +} + +export const getServicePeriods = cache(async () => { + const supabase = createServiceRoleClient() + + const { data, error } = await supabase + .from('ServicePeriod') + .select( + ` + id, + name, + outbound, + inbound, + coverage_start, + coverage_end, + deadline + `, + ) + .order('coverage_start', { ascending: false }) + + if (error) { + throw error + } + + return data +}) diff --git a/frontend/src/lib/servicePeriodUtils.ts b/frontend/src/lib/servicePeriodUtils.ts new file mode 100644 index 0000000..d0e4299 --- /dev/null +++ b/frontend/src/lib/servicePeriodUtils.ts @@ -0,0 +1,165 @@ +// lib/servicePeriodUtils.ts + +import type { ServicePeriod, TripDirection } from '@/types/servicePeriod' + +export interface DateRange { + start: string + end: string +} + +function parseCalendarDate(date: string): Date { + const [year, month, day] = date.split('-').map(Number) + return new Date(year, month - 1, day) +} + +export function isDateInRange( + date: string, + range: { + start: string + end: string + }, +): boolean { + return date >= range.start && date <= range.end +} + +export function getPeriodForDate( + date: string, + periods: ServicePeriod[], +): ServicePeriod | undefined { + if (!date) { + return undefined + } + + return periods.find((period) => + isDateInRange(date, { + start: period.coverage_start, + end: period.coverage_end, + }), + ) +} + +export function getAllowedDirectionsForDate( + date: string, + periods: ServicePeriod[], +): TripDirection[] { + const period = getPeriodForDate(date, periods) + + if (!period) { + return [] + } + + const directions: TripDirection[] = [] + + if (period.outbound) { + directions.push('outbound') + } + + if (period.inbound) { + directions.push('inbound') + } + + return directions +} + +export function isDirectionAllowedForDate( + date: string, + toAirport: boolean, + periods: ServicePeriod[], +): boolean { + const direction: TripDirection = toAirport ? 'outbound' : 'inbound' + + return getAllowedDirectionsForDate(date, periods).includes(direction) +} + +export function isInSubsidizedWindow( + date: string, + toAirport: boolean, + periods: ServicePeriod[], +): boolean { + return isDirectionAllowedForDate(date, toAirport, periods) +} + +export function isFlightPastDeadline( + flightDate: string, + periods: ServicePeriod[], + now: Date = new Date(), +): { + isPastDeadline: boolean + periodName?: string + deadline?: Date +} { + const period = getPeriodForDate(flightDate, periods) + + if (!period) { + return { + isPastDeadline: false, + } + } + + const deadline = new Date(period.deadline) + + return { + isPastDeadline: now > deadline, + periodName: period.name, + deadline, + } +} + +export function formatDeadlineForDisplay(deadline: string): string { + const deadlineDate = new Date(deadline) + const weekday = deadlineDate.toLocaleDateString('en-US', { + timeZone: 'America/Los_Angeles', + weekday: 'long', + }) + const datePart = deadlineDate.toLocaleDateString('en-US', { + timeZone: 'America/Los_Angeles', + month: 'long', + day: 'numeric', + year: 'numeric', + }) + const timePart = deadlineDate.toLocaleTimeString('en-US', { + timeZone: 'America/Los_Angeles', + hour: 'numeric', + minute: '2-digit', + hour12: true, + }) + + return `${weekday}, ${datePart} at ${timePart} PT` +} + +function formatShortDateRange(range: DateRange): string { + const start = parseCalendarDate(range.start) + const end = parseCalendarDate(range.end) + const startMonth = start.toLocaleDateString('en-US', { month: 'long' }) + const endMonth = end.toLocaleDateString('en-US', { month: 'long' }) + const startDay = start.getDate() + const endDay = end.getDate() + + if (range.start === range.end) { + return `${startMonth} ${startDay}` + } + + if (startMonth === endMonth) { + return `${startMonth} ${startDay}-${endDay}` + } + + return `${startMonth} ${startDay}-${endMonth} ${endDay}` +} + +export function formatCoverageWindowForDisplay( + period: ServicePeriod, +): string[] { + const directions = [ + period.outbound && 'Outbound', + period.inbound && 'Inbound', + ] + .filter(Boolean) + .join(', ') + + return [ + `${directions}: ${formatShortDateRange({ + start: period.coverage_start, + end: period.coverage_end, + })}`, + ] +} diff --git a/frontend/src/types/servicePeriod.ts b/frontend/src/types/servicePeriod.ts new file mode 100644 index 0000000..98b7b0c --- /dev/null +++ b/frontend/src/types/servicePeriod.ts @@ -0,0 +1,13 @@ +// types/servicePeriod.ts + +export type ServicePeriod = { + id: string + name: string + outbound: boolean + inbound: boolean + coverage_start: string + coverage_end: string + deadline: string +} + +export type TripDirection = 'outbound' | 'inbound' From 49806393f0f5bc36d8905e14740e5757217c7569 Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Wed, 2 Dec 2026 22:17:32 -0800 Subject: [PATCH 2/9] Use supabase api calls for adding service periods and selecting service period for sending batch emails --- .../src/app/api/admin/service-period/route.ts | 32 +++ frontend/src/app/api/service-periods/route.ts | 42 +++ .../src/components/admin/AddServicePeriod.tsx | 243 ++++++++++++++++++ .../components/admin/AdminDashboard.test.tsx | 125 ++++++--- .../src/components/admin/AdminDashboard.tsx | 193 ++++++-------- .../components/admin/EmailComposerModal.tsx | 30 ++- 6 files changed, 507 insertions(+), 158 deletions(-) create mode 100644 frontend/src/app/api/admin/service-period/route.ts create mode 100644 frontend/src/app/api/service-periods/route.ts create mode 100644 frontend/src/components/admin/AddServicePeriod.tsx diff --git a/frontend/src/app/api/admin/service-period/route.ts b/frontend/src/app/api/admin/service-period/route.ts new file mode 100644 index 0000000..6dc292c --- /dev/null +++ b/frontend/src/app/api/admin/service-period/route.ts @@ -0,0 +1,32 @@ +// /api/admin/service-periods/route.ts + +import { NextResponse } from 'next/server' +import { createServiceRoleClient } from '@/lib/server/serviceRole' +import { withAdminRoute } from '@/lib/server/auth' + +export const GET = withAdminRoute(async () => { + try { + const supabase = createServiceRoleClient() + + const { data, error } = await supabase + .from('ServicePeriod') + .select('id, name') + .order('coverage_start', { ascending: false }) + + if (error) { + throw error + } + + return NextResponse.json(data) + } catch (error) { + return NextResponse.json( + { + message: + error instanceof Error + ? error.message + : 'Failed to load service periods', + }, + { status: 500 }, + ) + } +}) diff --git a/frontend/src/app/api/service-periods/route.ts b/frontend/src/app/api/service-periods/route.ts new file mode 100644 index 0000000..f24b134 --- /dev/null +++ b/frontend/src/app/api/service-periods/route.ts @@ -0,0 +1,42 @@ +import { NextResponse } from 'next/server' +import { createServiceRoleClient } from '@/lib/server/serviceRole' +import { withAuthenticatedRoute } from '@/lib/server/auth' + +export const GET = withAuthenticatedRoute(async (_request) => { + try { + const supabase = createServiceRoleClient() + + const { data, error } = await supabase + .from('ServicePeriod') + .select( + ` + id, + name, + outbound, + inbound, + coverage_start, + coverage_end, + deadline + `, + ) + .order('coverage_start', { + ascending: false, + }) + + if (error) { + throw error + } + + return NextResponse.json(data) + } catch (error) { + return NextResponse.json( + { + message: + error instanceof Error + ? error.message + : 'Failed to load service periods', + }, + { status: 500 }, + ) + } +}) diff --git a/frontend/src/components/admin/AddServicePeriod.tsx b/frontend/src/components/admin/AddServicePeriod.tsx new file mode 100644 index 0000000..3370c12 --- /dev/null +++ b/frontend/src/components/admin/AddServicePeriod.tsx @@ -0,0 +1,243 @@ +'use client' + +import { useState } from 'react' + +interface AddServicePeriodModalProps { + isOpen: boolean + onClose: () => void + onSuccess?: () => void +} + +export function AddServicePeriodModal({ + isOpen, + onClose, + onSuccess, +}: AddServicePeriodModalProps) { + const currentYear = new Date().getFullYear() + + const [name, setName] = useState('') + const [year, setYear] = useState(currentYear) + + const [outbound, setOutbound] = useState(false) + const [inbound, setInbound] = useState(false) + + const [coverageStart, setCoverageStart] = useState('') + const [coverageEnd, setCoverageEnd] = useState('') + + const [deadline, setDeadline] = useState('') + + const [error, setError] = useState(null) + const [successMessage, setSuccessMessage] = useState(null) + const [saving, setSaving] = useState(false) + + async function handleSubmit(e: React.FormEvent) { + e.preventDefault() + + setError(null) + + if (year < currentYear) { + setError(`Year must be ${currentYear} or later.`) + return + } + + if (!outbound && !inbound) { + setError('At least one direction must be selected.') + return + } + + if (coverageStart > coverageEnd) { + setError('Coverage start must be before coverage end.') + return + } + + try { + setSaving(true) + + const response = await fetch('/api/admin/add-service-period', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + name, + year, + outbound, + inbound, + coverageStart, + coverageEnd, + deadline, + }), + }) + + const result = await response.json() + + if (!response.ok) { + throw new Error(result.message ?? 'Failed to create service period') + } + + setSuccessMessage( + `"${name}" was successfully created as a new service period.`, + ) + + setTimeout(() => { + onSuccess?.() + }, 1000) + + setName('') + setYear(currentYear) + setOutbound(false) + setInbound(false) + setCoverageStart('') + setCoverageEnd('') + setDeadline('') + + //onClose(); + } catch (err) { + setError(err instanceof Error ? err.message : 'Unexpected error') + } finally { + setSaving(false) + } + } + + if (!isOpen) return null + + return ( +
+
+
+

Add Service Periods

+ + +
+ +
+
+ + + setName(e.target.value)} + className="w-full rounded border px-3 py-2" + placeholder="Thanksgiving Break" + required + /> +
+ +
+ + + setYear(Number(e.target.value))} + className="w-full rounded border px-3 py-2" + required + /> +
+ +
+ + +
+ + + +
+
+ +
+
+ + + setCoverageStart(e.target.value)} + className="w-full rounded border px-3 py-2" + required + /> +
+ +
+ + + setCoverageEnd(e.target.value)} + className="w-full rounded border px-3 py-2" + required + /> +
+
+ +
+ + + setDeadline(e.target.value)} + className="w-full rounded border px-3 py-2" + required + /> +
+ + {error && ( +
{error}
+ )} + + {successMessage && ( +
+ {successMessage} +
+ )} + +
+ + + +
+
+
+
+ ) +} diff --git a/frontend/src/components/admin/AdminDashboard.test.tsx b/frontend/src/components/admin/AdminDashboard.test.tsx index 9c4de52..6ea59fe 100644 --- a/frontend/src/components/admin/AdminDashboard.test.tsx +++ b/frontend/src/components/admin/AdminDashboard.test.tsx @@ -6,6 +6,7 @@ const postJsonMock = jest.fn() const requestJsonMock = jest.fn() const pushMock = jest.fn() const createBrowserClientMock = jest.fn() +global.fetch = jest.fn() jest.mock('@/utils/api', () => ({ postJson: (...args: unknown[]) => postJsonMock(...args), @@ -139,6 +140,15 @@ const createSupabaseMock = ( describe('AdminDashboard', () => { beforeEach(() => { jest.clearAllMocks() + ;(global.fetch as jest.Mock).mockResolvedValue({ + ok: true, + json: async () => [ + { + id: 'fall-2026', + name: 'Fall 2026', + }, + ], + }) requestJsonMock.mockImplementation((url: string) => { if (url.includes('kind=no-shows')) { return Promise.resolve({ @@ -235,6 +245,19 @@ describe('AdminDashboard', () => { jest.restoreAllMocks() }) + const selectServicePeriod = async () => { + const select = await screen.findByLabelText('Service Period') + + await waitFor(() => + expect( + screen.getByRole('option', { + name: 'fall-2026', + }), + ).toBeInTheDocument(), + ) + + await userEvent.selectOptions(select, 'fall-2026') + } const renderDashboard = () => { const queryLog: Array = [] const supabase = createSupabaseMock((state) => { @@ -415,7 +438,7 @@ describe('AdminDashboard', () => { it('loads and renders the core dashboard metrics', async () => { const { supabase } = renderDashboard() - expect(await screen.findByText('RideLink Dashboard')).toBeInTheDocument() + expect(await screen.findByText('Ridelink Dashboard')).toBeInTheDocument() expect(requestJsonMock).toHaveBeenCalledWith( expect.stringMatching( /^\/api\/admin\/dashboard-summary\?unmatchedStart=\d{4}-\d{2}-\d{2}&unmatchedEnd=\d{4}-\d{2}-\d{2}$/, @@ -432,7 +455,7 @@ describe('AdminDashboard', () => { it('links to groups management from the action button', async () => { renderDashboard() - await screen.findByText('RideLink Dashboard') + await screen.findByText('Ridelink Dashboard') const groupsLink = screen.getByRole('link', { name: /View & Manage Groups/i, }) @@ -440,11 +463,22 @@ describe('AdminDashboard', () => { expect(groupsLink).toHaveAttribute('href', '/admin/groups') }) - const openComposer = async (name: string) => { + const openMatchedComposer = async () => { renderDashboard() - await screen.findByText('RideLink Dashboard') - await userEvent.click(screen.getByRole('button', { name })) - return screen.findByRole('dialog', { name }) + + await screen.findByText('Ridelink Dashboard') + + await selectServicePeriod() + + await userEvent.click( + screen.getByRole('button', { + name: 'Email matched riders', + }), + ) + + return screen.findByRole('dialog', { + name: 'Email matched riders', + }) } const writeEmail = async () => { @@ -459,7 +493,7 @@ describe('AdminDashboard', () => { } it('previews a custom match email and keeps the draft afterwards', async () => { - await openComposer('Email matched riders') + await openMatchedComposer() await writeEmail() await userEvent.click(screen.getByRole('button', { name: 'Preview Email' })) @@ -469,6 +503,7 @@ describe('AdminDashboard', () => { '/api/admin/send-match-emails', expect.objectContaining({ dry_run: true, + serviceperiodID: 'fall-2026', custom_subject: 'Test Subject', custom_body: 'Hello world', }), @@ -490,54 +525,69 @@ describe('AdminDashboard', () => { ) }) - it('sends match emails for real after confirmation, with the recipient filters', async () => { + it('sends match emails for the selected service period', async () => { postJsonMock.mockResolvedValueOnce({ success: true, sent: 2, failed: 0, total: 2, }) - renderDashboard() - await screen.findByText('RideLink Dashboard') - await userEvent.selectOptions(screen.getByLabelText('Airport'), 'ONT') - await userEvent.selectOptions( - screen.getByLabelText('Direction'), - 'From the airport', - ) - await userEvent.click( - screen.getByRole('button', { name: 'Email matched riders' }), - ) + await openMatchedComposer() + await writeEmail() - await userEvent.click(screen.getByRole('button', { name: 'Send Email' })) - expect(window.confirm).toHaveBeenCalledWith( - expect.stringContaining('from ONT'), + await userEvent.click( + screen.getByRole('button', { + name: 'Send Email', + }), ) + await waitFor(() => expect(postJsonMock).toHaveBeenCalledWith( '/api/admin/send-match-emails', expect.objectContaining({ dry_run: false, - airport: 'ONT', - direction: 'FROM', + serviceperiodID: 'fall-2026', custom_subject: 'Test Subject', custom_body: 'Hello world', }), ), ) + screen.debug() expect(await screen.findByText('Sent 2 of 2 emails')).toBeInTheDocument() }) it('does not send when the confirmation is declined', async () => { jest.mocked(window.confirm).mockReturnValueOnce(false) - await openComposer('Email matched riders') - await userEvent.click(screen.getByRole('button', { name: 'Send Email' })) + await openMatchedComposer() + + await userEvent.click( + screen.getByRole('button', { + name: 'Send Email', + }), + ) expect(postJsonMock).not.toHaveBeenCalled() }) + it('requires a service period before emailing matched riders', async () => { + renderDashboard() + + await screen.findByText('Ridelink Dashboard') + + expect( + screen.getByRole('button', { + name: 'Email matched riders', + }), + ).toBeDisabled() + + expect( + screen.getByText('Please select a service period'), + ).toBeInTheDocument() + }) + it('sends custom unmatched emails for the selected flight dates', async () => { postJsonMock.mockResolvedValueOnce({ success: true, @@ -546,7 +596,7 @@ describe('AdminDashboard', () => { total: 1, }) renderDashboard() - await screen.findByText('RideLink Dashboard') + await screen.findByText('Ridelink Dashboard') await userEvent.type(screen.getByLabelText('Flight date to'), '2026-11-30') await userEvent.click( @@ -570,11 +620,24 @@ describe('AdminDashboard', () => { }) it('blocks unmatched email preview until both dates are selected', async () => { - await openComposer('Email unmatched riders') + renderDashboard() - await userEvent.click(screen.getByRole('button', { name: 'Preview Email' })) + await screen.findByText('Ridelink Dashboard') + + await userEvent.click( + screen.getByRole('button', { + name: 'Email unmatched riders', + }), + ) + + await userEvent.click( + screen.getByRole('button', { + name: 'Preview Email', + }), + ) expect(postJsonMock).not.toHaveBeenCalled() + expect(screen.getByRole('alert')).toHaveTextContent( 'Select both flight dates', ) @@ -600,7 +663,7 @@ describe('AdminDashboard', () => { renderDashboard() - await screen.findByText('RideLink Dashboard') + await screen.findByText('Ridelink Dashboard') await userEvent.click( screen.getByRole('button', { name: /Load no-shows/i }), ) @@ -618,7 +681,7 @@ describe('AdminDashboard', () => { it('loads and renders billable cancellation rows on demand', async () => { renderDashboard() - await screen.findByText('RideLink Dashboard') + await screen.findByText('Ridelink Dashboard') await userEvent.click( screen.getByRole('button', { name: /Load billable cancellations/i }), ) @@ -638,7 +701,7 @@ describe('AdminDashboard', () => { it('loads and renders waived cancellation rows on demand', async () => { renderDashboard() - await screen.findByText('RideLink Dashboard') + await screen.findByText('Ridelink Dashboard') await userEvent.click( screen.getByRole('button', { name: /Load waived cancellations/i }), ) diff --git a/frontend/src/components/admin/AdminDashboard.tsx b/frontend/src/components/admin/AdminDashboard.tsx index ab265ac..32a1f0f 100644 --- a/frontend/src/components/admin/AdminDashboard.tsx +++ b/frontend/src/components/admin/AdminDashboard.tsx @@ -9,6 +9,7 @@ import { formatCancellationFee, } from '@/utils/cancellationFees' import EmailComposerModal from '@/components/admin/EmailComposerModal' +import { AddServicePeriodModal } from '@/components/admin/AddServicePeriod' import { useEffect, useState } from 'react' const formatDateTime = (dateString: string): string => { @@ -36,34 +37,6 @@ const formatDateForInput = (date: Date): string => { return `${year}-${month}-${day}` } -type EmailAirport = '' | 'LAX' | 'ONT' -type EmailDirection = '' | 'TO' | 'FROM' - -const describeMatchEmailAudience = ( - dateStart: string, - dateEnd: string, - airport: EmailAirport, - direction: EmailDirection, -) => { - const dates = - dateStart && dateEnd - ? `rides ${dateStart} to ${dateEnd}` - : dateStart - ? `rides from ${dateStart}` - : dateEnd - ? `rides until ${dateEnd}` - : 'all ride dates' - const route = - direction === 'TO' - ? `to ${airport || 'any airport'}` - : direction === 'FROM' - ? `from ${airport || 'any airport'}` - : airport - ? `to and from ${airport}` - : 'all airports and directions' - return `verified matches not yet emailed (${dates}, ${route})` -} - const getDefaultUnmatchedDateWindow = () => { const start = new Date() start.setDate(start.getDate() - 7) @@ -95,14 +68,18 @@ export default function AdminDashboard() { const [unmatchedDateEnd, setUnmatchedDateEnd] = useState( () => getDefaultUnmatchedDateWindow().end, ) - // Match emails: ride date range plus optional airport/direction filters - const [matchEmailDateStart, setMatchEmailDateStart] = useState(() => - formatDateForInput(new Date()), - ) - const [matchEmailDateEnd, setMatchEmailDateEnd] = useState('') - const [matchEmailAirport, setMatchEmailAirport] = useState('') - const [matchEmailDirection, setMatchEmailDirection] = - useState('') + + //service period + const [showAddServiceModal, setShowAddServiceModal] = useState(false) + + //Dropdown for service periods + const [servicePeriods, setServicePeriods] = useState< + { id: string; name: string }[] + >([]) + + const [selectedServicePeriod, setSelectedServicePeriod] = useState('') + + //EmailComposer const [showMatchEmailComposer, setShowMatchEmailComposer] = useState(false) // Unmatched emails state @@ -207,6 +184,22 @@ export default function AdminDashboard() { fetchDashboardData() }, [unmatchedDateStart, unmatchedDateEnd]) + useEffect(() => { + async function loadServicePeriods() { + const response = await fetch('/api/admin/service-period') + + if (!response.ok) { + throw new Error('Failed to load service periods') + } + + const data = await response.json() + + setServicePeriods(data) + } + + loadServicePeriods() + }, []) + const fetchCancellations = async (waived: boolean) => { if (!cancellationsDateStart || !cancellationsDateEnd) return setCancellationsLoading(true) @@ -267,7 +260,7 @@ export default function AdminDashboard() {
{/* Header */}

- RideLink Dashboard + Ridelink Dashboard

{/* Stats Cards - 5 Column Grid */} @@ -376,6 +369,31 @@ export default function AdminDashboard() {
+ {/* Service Period */} +
+
+

Service Periods

+

+ Create a new service period for students. +

+
+
+
+ +
+
+
+ setShowAddServiceModal(false)} + onSuccess={() => setShowAddServiceModal(false)} + /> + {/* Match no-shows */}
@@ -762,84 +780,38 @@ export default function AdminDashboard() {
- setMatchEmailDateStart(e.target.value)} - className="w-full rounded-lg border border-line-strong bg-card px-4 py-2 text-ink focus:border-sage focus:outline-none focus:ring-2 focus:ring-sage/30" - /> -
- -
- - setMatchEmailDateEnd(e.target.value)} - className="w-full rounded-lg border border-line-strong bg-card px-4 py-2 text-ink focus:border-sage focus:outline-none focus:ring-2 focus:ring-sage/30" - /> -
- -
- -
+ -
- -
- + {!selectedServicePeriod && ( +
+ {'Please select a service period'} +
+ )}

If a sufficient group cannot be formed, RideLink will be unable to - cover the ride. However, you may still use RideLink to coordinate + cover the ride. However, you may still use Ridelink to coordinate non-subsidized carpools.

diff --git a/frontend/src/components/admin/GroupsManagement.test.tsx b/frontend/src/components/admin/GroupsManagement.test.tsx index 78abd1e..fcebf45 100644 --- a/frontend/src/components/admin/GroupsManagement.test.tsx +++ b/frontend/src/components/admin/GroupsManagement.test.tsx @@ -1,5 +1,18 @@ import { render, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' +import type { ServicePeriod } from '@/types/servicePeriod' + +const mockServicePeriods: ServicePeriod[] = [ + { + id: 'fall-2026', + name: 'Fall 2026', + outbound: true, + inbound: true, + coverage_start: '2026-08-20', + coverage_end: '2026-12-20', + deadline: '2026-08-01', + }, +] const createBrowserClientMock = jest.fn(() => ({})) const useAuthMock = jest.fn(() => ({ @@ -227,16 +240,33 @@ const adminUser = { const randomUuidMock = jest.fn(() => 'batch-uuid-1') const openCreateGroupPanel = async () => { - await userEvent.click(screen.getByTitle(/Expand sidebar/i)) - const createGroupButtons = screen.getAllByRole('button', { + const expandButton = await screen.findByTitle(/Expand sidebar/i) + + await userEvent.click(expandButton) + + const createGroupButtons = await screen.findAllByRole('button', { name: 'Create Group', }) + await userEvent.click(createGroupButtons[0]) } +const renderGroupsManagement = async () => { + const result = render() + + await screen.findByTitle(/Expand sidebar/i) + + return result +} + describe('GroupsManagement', () => { beforeEach(() => { jest.clearAllMocks() + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + json: async (): Promise => mockServicePeriods, + }) + Object.defineProperty(globalThis, 'crypto', { value: { randomUUID: randomUuidMock, @@ -250,8 +280,7 @@ describe('GroupsManagement', () => { }) it('shows a validation error when creating a group with too few riders', async () => { - render() - + await renderGroupsManagement() await openCreateGroupPanel() await userEvent.click( screen.getByRole('button', { name: /Trigger Create Group/i }), @@ -264,8 +293,7 @@ describe('GroupsManagement', () => { }) it('shows a validation error when the group date is missing', async () => { - render() - + await renderGroupsManagement() await openCreateGroupPanel() await userEvent.click( screen.getByRole('button', { name: /Add Rider One/i }), @@ -284,8 +312,7 @@ describe('GroupsManagement', () => { }) it('creates a group and logs the create-group change on success', async () => { - render() - + await renderGroupsManagement() await openCreateGroupPanel() await userEvent.click( screen.getByRole('button', { name: /Add Rider One/i }), diff --git a/frontend/src/components/admin/GroupsManagement.tsx b/frontend/src/components/admin/GroupsManagement.tsx index 19e4853..ae37a6e 100644 --- a/frontend/src/components/admin/GroupsManagement.tsx +++ b/frontend/src/components/admin/GroupsManagement.tsx @@ -66,12 +66,42 @@ import { validateTimeCompatibility, } from './groups-management/utils' import UnmatchedRidersPanel from './groups-management/UnmatchedRidersPanel' +import { ServicePeriod } from '@/types/servicePeriod' export default function GroupsManagement() { const supabase = useMemo(() => createBrowserClient(), []) const { user } = useAuth() - const { computeGroupSubsidized } = useSubsidyLogic() const [, setAdminScope] = useState(null) + + //Load service period + const [servicePeriods, setServicePeriods] = useState([]) + const [servicePeriodsLoading, setServicePeriodsLoading] = useState(true) + + useEffect(() => { + async function loadServicePeriods() { + try { + const response = await fetch('/api/service-periods') + + if (!response.ok) { + throw new Error('Failed to load service periods') + } + + const periods: ServicePeriod[] = await response.json() + + setServicePeriods(periods) + } catch (error) { + console.error('Failed to load service periods', error) + } finally { + setServicePeriodsLoading(false) + } + } + + loadServicePeriods() + }, []) + + //Determin whether a group can be subsidized + const { computeGroupSubsidized } = useSubsidyLogic(servicePeriods) + const [activeTab, setActiveTab] = useState<'matched' | 'unmatched'>('matched') const [selectedAirports, setSelectedAirports] = useState([]) const [filterDirectionTo, setFilterDirectionTo] = useState(true) @@ -2690,6 +2720,14 @@ export default function GroupsManagement() { } } + if (servicePeriodsLoading) { + return ( +
+ Loading service periods... +
+ ) + } + return (
{/* Header */} diff --git a/frontend/src/components/forms/FlightForm.tsx b/frontend/src/components/forms/FlightForm.tsx index 68d3330..0a52f6a 100644 --- a/frontend/src/components/forms/FlightForm.tsx +++ b/frontend/src/components/forms/FlightForm.tsx @@ -18,13 +18,13 @@ import { MAX_TERMINAL_LENGTH, validateAirlineCode, validateFlightNumber, - isFlightPastDeadline, } from '@/utils/flightValidation' import { getAllowedDirectionsForDate, isDirectionAllowedForDate, - isInSubsidizedWindow, -} from '@/config/servicePeriodHelpers' + isFlightPastDeadline, +} from '@/lib/servicePeriodUtils' +import type { ServicePeriod } from '@/types/servicePeriod' import { Tooltip, TooltipContent, @@ -133,6 +133,8 @@ export default function FlightForm({ const [duplicateErrorMessage, setDuplicateErrorMessage] = useState('') const [deadlineErrorMessage, setDeadlineErrorMessage] = useState('') const [isDuplicateError, setIsDuplicateError] = useState(false) + const [servicePeriods, setServicePeriods] = useState([]) + const [servicePeriodsLoading, setServicePeriodsLoading] = useState(true) const [isPastDeadline, setIsPastDeadline] = useState(false) const [isProfileComplete, setIsProfileComplete] = useState(true) const [profileCheckComplete, setProfileCheckComplete] = useState(false) @@ -170,10 +172,36 @@ export default function FlightForm({ const checkedLuggageTooltip = useClickTooltip() const timeRangeTooltip = useClickTooltip() + useEffect(() => { + async function loadServicePeriods() { + try { + const response = await fetch('/api/service-periods') + + if (!response.ok) { + throw new Error('Failed to load service periods') + } + + const periods: ServicePeriod[] = await response.json() + + setServicePeriods(periods) + } catch (error) { + console.error('Failed to load service periods', error) + } finally { + setServicePeriodsLoading(false) + } + } + + loadServicePeriods() + }, []) + const allowedDirections = useMemo( - () => (dateOfFlight ? getAllowedDirectionsForDate(dateOfFlight) : []), - [dateOfFlight], + () => + dateOfFlight + ? getAllowedDirectionsForDate(dateOfFlight, servicePeriods) + : [], + [dateOfFlight, servicePeriods], ) + const flightDateBounds = useMemo(() => getFlightDateBounds(), []) const hasSubsidizedDirections = allowedDirections.length > 0 const outboundAllowed = allowedDirections.includes('outbound') @@ -303,7 +331,7 @@ export default function FlightForm({ return } - const deadlineCheck = isFlightPastDeadline(dateOfFlight) + const deadlineCheck = isFlightPastDeadline(dateOfFlight, servicePeriods) if (deadlineCheck.isPastDeadline) { setDeadlineErrorMessage( `Sorry! The deadline for ${deadlineCheck.periodName} has passed. Request deadline was ${deadlineCheck.deadline?.toLocaleString('en-US', { timeZone: 'America/Los_Angeles', month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit', timeZoneName: 'short' })}.`, @@ -313,7 +341,7 @@ export default function FlightForm({ setDeadlineErrorMessage('') setIsPastDeadline(false) } - }, [dateOfFlight]) + }, [dateOfFlight, servicePeriods]) // Clear direction when ride date no longer supports the prior selection useEffect(() => { @@ -321,14 +349,15 @@ export default function FlightForm({ return } - const directions = getAllowedDirectionsForDate(dateOfFlight) + const directions = getAllowedDirectionsForDate(dateOfFlight, servicePeriods) + if ( directions.length > 0 && - !isDirectionAllowedForDate(dateOfFlight, tripType) + !isDirectionAllowedForDate(dateOfFlight, tripType, servicePeriods) ) { setTripType(null) } - }, [dateOfFlight, tripType]) + }, [dateOfFlight, tripType, servicePeriods]) // Check for duplicate flights in real-time when date, airport, or trip type changes useEffect(() => { @@ -395,8 +424,8 @@ export default function FlightForm({ const isWithinOperationalPeriod = tripType !== null - ? isInSubsidizedWindow(dateOfFlight, tripType) - : getAllowedDirectionsForDate(dateOfFlight).length > 0 + ? isDirectionAllowedForDate(dateOfFlight, tripType, servicePeriods) + : getAllowedDirectionsForDate(dateOfFlight, servicePeriods).length > 0 if (isAugust19RideDate) { setAspcWarningMessage( @@ -443,6 +472,7 @@ export default function FlightForm({ isAugust19RideDate, tripType, userSchool, + servicePeriods, ]) // Check ASPC subsidy eligibility when date, airport, or times change @@ -618,8 +648,8 @@ export default function FlightForm({ } if ( - getAllowedDirectionsForDate(dateOfFlight).length > 0 && - !isDirectionAllowedForDate(dateOfFlight, tripType) + getAllowedDirectionsForDate(dateOfFlight, servicePeriods).length > 0 && + !isDirectionAllowedForDate(dateOfFlight, tripType, servicePeriods) ) { setMessage( 'The selected trip direction is not available for this ride date.', @@ -681,8 +711,8 @@ export default function FlightForm({ } if ( - getAllowedDirectionsForDate(dateOfFlight).length > 0 && - !isDirectionAllowedForDate(dateOfFlight, tripType) + getAllowedDirectionsForDate(dateOfFlight, servicePeriods).length > 0 && + !isDirectionAllowedForDate(dateOfFlight, tripType, servicePeriods) ) { setMessage( 'The selected trip direction is not available for this ride date.', @@ -983,7 +1013,7 @@ export default function FlightForm({ } if ( hasSubsidizedDirections && - !isDirectionAllowedForDate(dateOfFlight, tripType) + !isDirectionAllowedForDate(dateOfFlight, tripType, servicePeriods) ) { setMessage( 'The selected trip direction is not available for this ride date.', @@ -1121,6 +1151,14 @@ export default function FlightForm({ ) } + if (servicePeriodsLoading) { + return ( +
+ Loading service periods... +
+ ) + } + return (
diff --git a/frontend/src/hooks/useSubsidyLogic.ts b/frontend/src/hooks/useSubsidyLogic.ts index 9542fd1..3d2094a 100644 --- a/frontend/src/hooks/useSubsidyLogic.ts +++ b/frontend/src/hooks/useSubsidyLogic.ts @@ -1,14 +1,15 @@ 'use client' -import { isDateCovered as isDateCoveredForPeriod } from '@/config/servicePeriodHelpers' import { AIRPORT_MIN_RIDERS, ALLOWED_SCHOOL, - COVERED_DATES_EXPLICIT, - COVERED_DATES_INBOUND, - COVERED_DATES_OUTBOUND, DEFAULT_AIRPORT_MIN_RIDERS, } from '@/config/subsidyConfig' + +import { isInSubsidizedWindow } from '@/lib/servicePeriodUtils' + +import type { ServicePeriod } from '@/types/servicePeriod' + import { useCallback, useMemo } from 'react' export interface ComputeSubsidyInput { @@ -44,13 +45,12 @@ export interface ComputeSubsidyResult { * 3. Covered: ride date + direction in allowed list * Connect rides never get vouchers. */ -export function useSubsidyLogic() { - const isDateCoveredFn = useCallback((date: string, toAirport: boolean) => { - if (!COVERED_DATES_EXPLICIT) { - return true - } - return isDateCoveredForPeriod(date, toAirport) - }, []) +export function useSubsidyLogic(servicePeriods: ServicePeriod[]) { + const isDateCoveredFn = useCallback( + (date: string, toAirport: boolean) => + isInSubsidizedWindow(date, toAirport, servicePeriods), + [servicePeriods], + ) const computeGroupSubsidized = useCallback( (input: ComputeSubsidyInput): ComputeSubsidyResult => { @@ -61,6 +61,7 @@ export function useSubsidyLogic() { const minRiders = AIRPORT_MIN_RIDERS[airport] ?? DEFAULT_AIRPORT_MIN_RIDERS + const meetsThreshold = riderCount >= minRiders const allAllowedSchool = riderSchools.every( @@ -70,30 +71,36 @@ export function useSubsidyLogic() { const subsidized = meetsThreshold && allAllowedSchool && covered const isConnect = uberType?.toLowerCase() === 'connect' + const assignVoucher = subsidized && covered && !isConnect const voucherBlockers: string[] = [] + if (!assignVoucher) { if (isConnect) { voucherBlockers.push( 'Contingency vouchers are not applied to Uber Connect rides.', ) } + if (!allAllowedSchool) { const schoolLabel = - riderSchools.map((s) => (s ?? '').trim()).find(Boolean) || + riderSchools.map((s) => (s ?? '').trim()).find(Boolean) ?? 'not on file' + voucherBlockers.push( `ASPC subsidy vouchers are only for ${ALLOWED_SCHOOL} riders (your school: ${schoolLabel}).`, ) } - if (COVERED_DATES_EXPLICIT && !covered) { + + if (!covered) { voucherBlockers.push( toAirport ? 'Your new ride date is outside the subsidized travel dates for trips to the airport.' : 'Your new ride date is outside the subsidized travel dates for trips from the airport.', ) } + if (!meetsThreshold) { voucherBlockers.push( `Subsidized rides need at least ${minRiders} rider(s) in the same Uber at ${airport}; after this delay you are solo until you join a group.`, @@ -101,7 +108,12 @@ export function useSubsidyLogic() { } } - return { subsidized, covered, assignVoucher, voucherBlockers } + return { + subsidized, + covered, + assignVoucher, + voucherBlockers, + } }, [isDateCoveredFn], ) @@ -111,9 +123,6 @@ export function useSubsidyLogic() { isDateCovered: isDateCoveredFn, computeGroupSubsidized, config: { - COVERED_DATES_EXPLICIT, - COVERED_DATES_OUTBOUND, - COVERED_DATES_INBOUND, AIRPORT_MIN_RIDERS, ALLOWED_SCHOOL, }, diff --git a/frontend/src/utils/flightValidation.test.ts b/frontend/src/utils/flightValidation.test.ts index c16f4e9..a20e8d6 100644 --- a/frontend/src/utils/flightValidation.test.ts +++ b/frontend/src/utils/flightValidation.test.ts @@ -1,6 +1,47 @@ /** @jest-environment node */ -import { canEditFlight, isFlightPastDeadline } from '@/utils/flightValidation' +import { canEditFlight } from '@/utils/flightValidation' +import { isFlightPastDeadline } from '@/lib/servicePeriodUtils' +import type { ServicePeriod } from '@/types/servicePeriod' + +const SERVICE_PERIODS: ServicePeriod[] = [ + { + id: 'spring-2026', + name: 'Spring Break', + outbound: true, + inbound: true, + coverage_start: '2026-03-08', + coverage_end: '2026-03-26', + deadline: '2026-03-06T23:59:59-08:00', + }, + { + id: 'winter-2025-outbound', + name: 'Winter Break (Outbound)', + outbound: true, + inbound: false, + coverage_start: '2025-12-09', + coverage_end: '2025-12-13', + deadline: '2025-12-03T23:59:59-08:00', + }, + { + id: 'winter-2026-return', + name: 'Winter Break (Return)', + outbound: false, + inbound: true, + coverage_start: '2026-01-17', + coverage_end: '2026-01-21', + deadline: '2026-01-09T23:59:59-08:00', + }, + { + id: 'summer-2026', + name: 'Summer Break', + outbound: true, + inbound: false, + coverage_start: '2026-05-12', + coverage_end: '2026-05-19', + deadline: '2026-05-06T23:59:59-07:00', + }, +] describe('isFlightPastDeadline (flightValidation parity)', () => { beforeEach(() => { @@ -14,7 +55,7 @@ describe('isFlightPastDeadline (flightValidation parity)', () => { it('allows spring flights before the Mar 6 deadline', () => { jest.setSystemTime(new Date('2026-03-05T12:00:00-08:00')) - expect(isFlightPastDeadline('2026-03-14')).toEqual({ + expect(isFlightPastDeadline('2026-03-14', SERVICE_PERIODS)).toEqual({ isPastDeadline: false, periodName: 'Spring Break', deadline: new Date('2026-03-06T23:59:59-08:00'), @@ -24,7 +65,7 @@ describe('isFlightPastDeadline (flightValidation parity)', () => { it('blocks spring flights after the Mar 6 deadline', () => { jest.setSystemTime(new Date('2026-03-07T12:00:00-08:00')) - const result = isFlightPastDeadline('2026-03-14') + const result = isFlightPastDeadline('2026-03-14', SERVICE_PERIODS) expect(result.isPastDeadline).toBe(true) expect(result.periodName).toBe('Spring Break') @@ -32,22 +73,30 @@ describe('isFlightPastDeadline (flightValidation parity)', () => { it('uses distinct winter outbound and return deadlines', () => { jest.setSystemTime(new Date('2025-12-04T12:00:00-08:00')) - expect(isFlightPastDeadline('2025-12-10').isPastDeadline).toBe(true) + expect( + isFlightPastDeadline('2025-12-10', SERVICE_PERIODS).isPastDeadline, + ).toBe(true) jest.setSystemTime(new Date('2026-01-08T12:00:00-08:00')) - expect(isFlightPastDeadline('2026-01-18').isPastDeadline).toBe(false) + expect( + isFlightPastDeadline('2026-01-18', SERVICE_PERIODS).isPastDeadline, + ).toBe(false) jest.setSystemTime(new Date('2026-01-10T12:00:00-08:00')) - expect(isFlightPastDeadline('2026-01-18').isPastDeadline).toBe(true) + expect( + isFlightPastDeadline('2026-01-18', SERVICE_PERIODS).isPastDeadline, + ).toBe(true) }) it('does not enforce deadlines outside buffered windows', () => { jest.setSystemTime(new Date('2026-06-01T12:00:00-07:00')) - expect(isFlightPastDeadline('2026-02-01')).toEqual({ + expect(isFlightPastDeadline('2026-02-01', SERVICE_PERIODS)).toEqual({ + isPastDeadline: false, + }) + expect(isFlightPastDeadline('', SERVICE_PERIODS)).toEqual({ isPastDeadline: false, }) - expect(isFlightPastDeadline('')).toEqual({ isPastDeadline: false }) }) }) @@ -62,14 +111,14 @@ describe('canEditFlight (flightValidation parity)', () => { it('returns true before deadline and false after', () => { jest.setSystemTime(new Date('2026-05-05T12:00:00-07:00')) - expect(canEditFlight('2026-05-15')).toBe(true) + expect(canEditFlight('2026-05-15', SERVICE_PERIODS)).toBe(true) jest.setSystemTime(new Date('2026-05-07T08:00:00-07:00')) - expect(canEditFlight('2026-05-15')).toBe(false) + expect(canEditFlight('2026-05-15', SERVICE_PERIODS)).toBe(false) }) it('returns true for dates outside service periods', () => { jest.setSystemTime(new Date('2026-06-01T12:00:00-07:00')) - expect(canEditFlight('2026-02-01')).toBe(true) + expect(canEditFlight('2026-02-01', SERVICE_PERIODS)).toBe(true) }) }) diff --git a/frontend/src/utils/flightValidation.ts b/frontend/src/utils/flightValidation.ts index f5b7cb6..b1a2437 100644 --- a/frontend/src/utils/flightValidation.ts +++ b/frontend/src/utils/flightValidation.ts @@ -2,6 +2,9 @@ * Flight validation utilities for separate airline code and flight number inputs */ +import { ServicePeriod } from '@/types/servicePeriod' +import { isFlightPastDeadline } from '@/lib/servicePeriodUtils' + export interface AirlineCodeValidationResult { isValid: boolean errorMessage?: string @@ -112,27 +115,16 @@ export function validateFlightNumber( } } -import { isFlightPastDeadline as isFlightPastDeadlineFromPeriods } from '@/config/servicePeriodHelpers' - -/** - * Check if a flight date is past its deadline for requests - * @param flightDate - Flight date in YYYY-MM-DD format - * @returns Object with isPastDeadline boolean and optional deadline info - */ -export function isFlightPastDeadline(flightDate: string): { - isPastDeadline: boolean - periodName?: string - deadline?: Date -} { - return isFlightPastDeadlineFromPeriods(flightDate) -} - /** * Check if any flight in a list can still be edited based on its deadline * @param flightDate - Flight date in YYYY-MM-DD format * @returns true if the flight can still be edited */ -export function canEditFlight(flightDate: string): boolean { - const result = isFlightPastDeadline(flightDate) +export function canEditFlight( + flightDate: string, + periods: ServicePeriod[], +): boolean { + const result = isFlightPastDeadline(flightDate, periods) + return !result.isPastDeadline } From 5f6747b0ad84670f25a30af808ee8e33433d2155 Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Wed, 2 Dec 2026 22:55:03 -0800 Subject: [PATCH 4/9] Update test suites for them to account for the new table ServicePeriod and make the questionnaire form to fetch service periods from supabase --- frontend/src/app/questionnaires/page.tsx | 29 +++- frontend/src/config/routeAccess.test.ts | 13 +- .../server/apiAuthorizationCoverage.test.ts | 3 +- .../src/lib/server/databaseContract.test.ts | 27 ++-- .../server/studentCommands.deadline.test.ts | 4 + .../src/lib/server/studentCommands.test.ts | 124 +++++++++++++++++- frontend/src/lib/server/studentCommands.ts | 18 ++- 7 files changed, 191 insertions(+), 27 deletions(-) diff --git a/frontend/src/app/questionnaires/page.tsx b/frontend/src/app/questionnaires/page.tsx index b96a564..a5e0fbb 100644 --- a/frontend/src/app/questionnaires/page.tsx +++ b/frontend/src/app/questionnaires/page.tsx @@ -21,6 +21,7 @@ import { type MatchingStatus, } from '@/utils/matchingStatus' import { validateUserProfile } from '@/utils/profileValidation' +import { ServicePeriod } from '@/types/servicePeriod' interface MatchForm { flight_id: string @@ -44,6 +45,30 @@ export default function Questionnaires() { const [modalFlightId, setModalFlightId] = useState(null) const [loading, setLoading] = useState(true) const [profileBannerDismissed, setProfileBannerDismissed] = useState(false) + const [servicePeriods, setServicePeriods] = useState([]) + const [servicePeriodsLoading, setServicePeriodsLoading] = useState(true) + + useEffect(() => { + async function loadServicePeriods() { + try { + const response = await fetch('/api/service-periods') + + if (!response.ok) { + throw new Error('Failed to load service periods') + } + + const periods: ServicePeriod[] = await response.json() + + setServicePeriods(periods) + } catch (error) { + console.error('Failed to load service periods', error) + } finally { + setServicePeriodsLoading(false) + } + } + + loadServicePeriods() + }, []) // Function to convert 24-hour time to 12-hour format with AM/PM const formatTime12Hour = (time24: string): string => { @@ -170,7 +195,7 @@ export default function Questionnaires() { ) } - if (loading || authLoading) + if (loading || authLoading || servicePeriodsLoading) return (
@@ -247,7 +272,7 @@ export default function Questionnaires() { {upcomingUnmatchedForms.length > 0 ? (
{upcomingUnmatchedForms.map((form) => { - const canEdit = canEditFlight(form.date) + const canEdit = canEditFlight(form.date, servicePeriods) return ( path.join(process.cwd(), 'src/app'), entryPath, ) + const normalizedPath = relativePath.replaceAll(path.sep, '/') const routePath = - relativePath === 'page.tsx' + normalizedPath === 'page.tsx' ? '' - : relativePath.replace(/\/page\.tsx$/, '').replaceAll(path.sep, '/') + : normalizedPath.replace(/\/page\.tsx$/, '').replaceAll(path.sep, '/') const representativePath = routePath.replace(/\[[^/]+\]/g, '__dynamic__') return [representativePath ? `/${representativePath}` : '/'] }) @@ -87,6 +88,14 @@ describe('route access policy', () => { for (const pathname of pageRoutes) { const access = getPageAccess(pathname) + const middleware = matchesMiddleware(pathname) + if (middleware !== (access !== 'public')) { + console.log({ + pathname, + access, + middleware, + }) + } expect(matchesMiddleware(pathname)).toBe(access !== 'public') } }) diff --git a/frontend/src/lib/server/apiAuthorizationCoverage.test.ts b/frontend/src/lib/server/apiAuthorizationCoverage.test.ts index fa3de2b..7e259ab 100644 --- a/frontend/src/lib/server/apiAuthorizationCoverage.test.ts +++ b/frontend/src/lib/server/apiAuthorizationCoverage.test.ts @@ -27,7 +27,8 @@ describe('API authorization coverage', () => { ), (match) => match[1], ) - const expectedWrapper = relativePath.includes('/api/admin/') + const normalizedPath = relativePath.replaceAll('\\', '/') + const expectedWrapper = normalizedPath.includes('/api/admin/') ? 'withAdminRoute' : 'withAuthenticatedRoute' diff --git a/frontend/src/lib/server/databaseContract.test.ts b/frontend/src/lib/server/databaseContract.test.ts index 549c57c..072513a 100644 --- a/frontend/src/lib/server/databaseContract.test.ts +++ b/frontend/src/lib/server/databaseContract.test.ts @@ -236,18 +236,21 @@ describe('generated database contract', () => { (name) => !generatedTableNames.has(name), ) - expect(applicationTableNames).toEqual([ - 'AlgorithmStatus', - 'ChangeLog', - 'Comments', - 'Feedback', - 'Flights', - 'legal_acceptances', - 'match_cancellations', - 'Matches', - 'MatchRequests', - 'Users', - ]) + expect(new Set(applicationTableNames)).toEqual( + new Set([ + 'AlgorithmStatus', + 'ChangeLog', + 'Comments', + 'Feedback', + 'Flights', + 'legal_acceptances', + 'match_cancellations', + 'Matches', + 'MatchRequests', + 'ServicePeriod', + 'Users', + ]), + ) expect(missingTableNames).toEqual([]) }) diff --git a/frontend/src/lib/server/studentCommands.deadline.test.ts b/frontend/src/lib/server/studentCommands.deadline.test.ts index 7eac958..7361ca8 100644 --- a/frontend/src/lib/server/studentCommands.deadline.test.ts +++ b/frontend/src/lib/server/studentCommands.deadline.test.ts @@ -1,6 +1,10 @@ /** @jest-environment node */ jest.mock('server-only', () => ({})) +jest.mock('react', () => ({ + ...jest.requireActual('react'), + cache: (fn: any) => fn, +})) import { createOwnFlight, diff --git a/frontend/src/lib/server/studentCommands.test.ts b/frontend/src/lib/server/studentCommands.test.ts index 7b1e8bc..4f92bab 100644 --- a/frontend/src/lib/server/studentCommands.test.ts +++ b/frontend/src/lib/server/studentCommands.test.ts @@ -5,6 +5,10 @@ jest.mock('@/utils/flightValidation', () => ({ ...jest.requireActual('@/utils/flightValidation'), canEditFlight: jest.fn().mockReturnValue(true), })) +jest.mock('react', () => ({ + ...jest.requireActual('react'), + cache: (fn: any) => fn, +})) import { acceptMatchRequest, @@ -18,8 +22,38 @@ import { sendMatchRequest, updateOwnFlight, } from '@/lib/server/studentCommands' +import { + getServicePeriods, + type ServicePeriod, +} from '@/lib/server/getServicePeriods' import { canEditFlight } from '@/utils/flightValidation' +jest.mock('@/lib/server/getServicePeriods', () => ({ + getServicePeriods: jest.fn(), +})) + +const mockedGetServicePeriods = jest.mocked(getServicePeriods) +const mockedCanEditFlight = jest.mocked(canEditFlight) + +const mockServicePeriods: ServicePeriod[] = [ + { + id: 'spring-2026', + name: 'Spring Break', + outbound: true, + inbound: true, + coverage_start: '2026-03-13', + coverage_end: '2026-03-22', + deadline: '2026-03-06T23:59:59-08:00', + }, +] + +beforeEach(() => { + jest.clearAllMocks() + + mockedGetServicePeriods.mockResolvedValue(mockServicePeriods) + mockedCanEditFlight.mockReturnValue(true) +}) + const createThenableEqChain = (data: T, error: unknown = null) => { const eqCalls: Array<[string, unknown]> = [] const chain: { @@ -155,8 +189,6 @@ describe('acceptMatchRequest', () => { }) describe('cancelOwnMatch', () => { - const mockedCanEditFlight = jest.mocked(canEditFlight) - beforeEach(() => { mockedCanEditFlight.mockReturnValue(true) }) @@ -181,7 +213,10 @@ describe('cancelOwnMatch', () => { success: true, }) - expect(mockedCanEditFlight).toHaveBeenCalledWith('2026-03-14') + expect(mockedCanEditFlight).toHaveBeenCalledWith( + '2026-03-14', + mockServicePeriods, + ) expect(rpc).toHaveBeenCalledWith('cancel_own_match', { p_ride_id: 17, p_cancelled_after_deadline: true, @@ -204,7 +239,10 @@ describe('cancelOwnMatch', () => { rideId: 17, }) - expect(mockedCanEditFlight).toHaveBeenCalledWith('2026-03-14') + expect(mockedCanEditFlight).toHaveBeenCalledWith( + '2026-03-14', + mockServicePeriods, + ) expect(rpc).toHaveBeenCalledWith('cancel_own_match', { p_ride_id: 17, p_cancelled_after_deadline: false, @@ -223,7 +261,7 @@ describe('cancelOwnMatch', () => { rideId: 17, }) - expect(mockedCanEditFlight).toHaveBeenCalledWith('') + expect(mockedCanEditFlight).toHaveBeenCalledWith('', mockServicePeriods) expect(rpc).toHaveBeenCalledWith('cancel_own_match', { p_ride_id: 17, p_cancelled_after_deadline: false, @@ -897,6 +935,21 @@ describe('createOwnFlight', () => { status: 500, }) }) + + it('rejects flight creation after the service period deadline', async () => { + mockedCanEditFlight.mockReturnValue(false) + + await expect( + createOwnFlight({ + supabase: { from: jest.fn() }, + userId: 'student-1', + payload: validPayload(), + }), + ).rejects.toMatchObject({ + message: 'The submission deadline for this service period has passed.', + status: 403, + }) + }) }) describe('updateOwnFlight', () => { @@ -1044,6 +1097,36 @@ describe('updateOwnFlight', () => { status: 409, }) }) + + it('rejects updates after the deadline', async () => { + mockedCanEditFlight.mockReturnValue(false) + + const maybeSingle = jest.fn().mockResolvedValue({ + data: { + flight_id: 77, + user_id: 'student-1', + date: '2026-03-14', + }, + error: null, + }) + + const selectEq = jest.fn(() => ({ maybeSingle })) + const select = jest.fn(() => ({ eq: selectEq })) + + const from = jest.fn().mockReturnValue({ select }) + + await expect( + updateOwnFlight({ + supabase: { from, rpc: jest.fn() }, + userId: 'student-1', + flightId: 77, + payload: { airport: 'LAX' }, + }), + ).rejects.toMatchObject({ + message: 'This flight can no longer be edited.', + status: 403, + }) + }) }) describe('deleteOwnFlight', () => { @@ -1139,4 +1222,35 @@ describe('deleteOwnFlight', () => { status: 409, }) }) + it('rejects deletions after the deadline', async () => { + mockedCanEditFlight.mockReturnValue(false) + + const maybeSingle = jest.fn().mockResolvedValue({ + data: { + flight_id: 88, + user_id: 'student-1', + date: '2026-03-14', + }, + error: null, + }) + + const selectEq = jest.fn(() => ({ maybeSingle })) + const select = jest.fn(() => ({ eq: selectEq })) + const rpc = jest.fn() + + const from = jest.fn().mockReturnValue({ select }) + + await expect( + deleteOwnFlight({ + supabase: { from, rpc }, + userId: 'student-1', + flightId: 88, + }), + ).rejects.toMatchObject({ + message: 'This flight can no longer be deleted.', + status: 403, + }) + + expect(rpc).not.toHaveBeenCalled() + }) }) diff --git a/frontend/src/lib/server/studentCommands.ts b/frontend/src/lib/server/studentCommands.ts index 579ce5d..a014cdf 100644 --- a/frontend/src/lib/server/studentCommands.ts +++ b/frontend/src/lib/server/studentCommands.ts @@ -14,6 +14,7 @@ import { toUnmatchedFlightDto, type UnmatchedGroupDto, } from '@/contracts/readModels' +import { getServicePeriods } from './getServicePeriods' type SupabaseClient = any @@ -349,8 +350,9 @@ export async function cancelOwnMatch({ const flightRecord = getFirst( matchRow?.Flights as { date?: string } | { date?: string }[] | null, ) + const periods = await getServicePeriods() const flightDate = matchRow?.date ?? flightRecord?.date ?? '' - const cancelledAfterDeadline = !canEditFlight(flightDate) + const cancelledAfterDeadline = !canEditFlight(flightDate, periods) const { data, error } = await supabase.rpc('cancel_own_match', { p_ride_id: rideId, @@ -393,11 +395,15 @@ export async function createOwnFlight({ userId: string payload: Record }) { + const periods = await getServicePeriods() const normalizedPayload = normalizeFlightWritePayload(payload, { mode: 'create', }) - if (normalizedPayload.date && !canEditFlight(normalizedPayload.date)) { + if ( + normalizedPayload.date && + !canEditFlight(normalizedPayload.date, periods) + ) { throw createError( 'The submission deadline for this service period has passed.', 403, @@ -444,6 +450,7 @@ export async function updateOwnFlight({ flightId: number payload: Record }) { + const periods = await getServicePeriods() const { data: existingFlight, error: fetchError } = await supabase .from('Flights') .select('flight_id, user_id, date') @@ -458,7 +465,7 @@ export async function updateOwnFlight({ throw createError('Flight not found.', 404) } - if (!canEditFlight(existingFlight.date)) { + if (!canEditFlight(existingFlight.date, periods)) { throw createError('This flight can no longer be edited.', 403) } @@ -471,7 +478,7 @@ export async function updateOwnFlight({ if ( typeof normalizedPayload.date === 'string' && - !canEditFlight(normalizedPayload.date) + !canEditFlight(normalizedPayload.date, periods) ) { throw createError( 'The submission deadline for the updated service period has passed.', @@ -509,6 +516,7 @@ export async function deleteOwnFlight({ userId: string flightId: number }) { + const periods = await getServicePeriods() const { data: existingFlight, error: fetchError } = await supabase .from('Flights') .select('flight_id, user_id, date') @@ -523,7 +531,7 @@ export async function deleteOwnFlight({ throw createError('Flight not found.', 404) } - if (!canEditFlight(existingFlight.date)) { + if (!canEditFlight(existingFlight.date, periods)) { throw createError('This flight can no longer be deleted.', 403) } From 018de9afe54d19892317bad8c8a95d0fab33e405 Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Wed, 2 Dec 2026 23:18:40 -0800 Subject: [PATCH 5/9] Remove unused code from servicePeriod helpers --- frontend/src/config/servicePeriodHelpers.ts | 9 +-------- frontend/src/config/subsidyConfig.ts | 8 -------- frontend/src/lib/servicePeriodUtils.ts | 4 ++-- 3 files changed, 3 insertions(+), 18 deletions(-) diff --git a/frontend/src/config/servicePeriodHelpers.ts b/frontend/src/config/servicePeriodHelpers.ts index 4af3ecd..11b79e1 100644 --- a/frontend/src/config/servicePeriodHelpers.ts +++ b/frontend/src/config/servicePeriodHelpers.ts @@ -78,7 +78,7 @@ export async function isDateCovered( return await isDirectionAllowedForDate(date, toAirport) } -export async function getPeriodForDate( +async function getPeriodForDate( date: string, ): Promise { if (!date) { @@ -157,13 +157,6 @@ export async function isDirectionAllowedForDate( return allowedDirections.includes(direction) } -export async function isInSubsidizedWindow( - date: string, - toAirport: boolean, -): Promise { - return isDateCovered(date, toAirport) -} - export async function isFlightPastDeadline( flightDate: string, now: Date = new Date(), diff --git a/frontend/src/config/subsidyConfig.ts b/frontend/src/config/subsidyConfig.ts index f57ad91..cd11ecb 100644 --- a/frontend/src/config/subsidyConfig.ts +++ b/frontend/src/config/subsidyConfig.ts @@ -1,11 +1,3 @@ -/** - * Subsidy and covered-dates config for matching, vouchers, and persistence. - * Period date ranges live in servicePeriods.ts; lists here are derived at load. - * Keep ML backend (e.g. config.py) in sync when breaks change. - */ - -export const COVERED_DATES_EXPLICIT = true - //const derivedCoveredDates = getDerivedCoveredDates() /** Allowed dates for outbound rides (to_airport true), MM-DD year-agnostic */ diff --git a/frontend/src/lib/servicePeriodUtils.ts b/frontend/src/lib/servicePeriodUtils.ts index d0e4299..c79e2f0 100644 --- a/frontend/src/lib/servicePeriodUtils.ts +++ b/frontend/src/lib/servicePeriodUtils.ts @@ -2,7 +2,7 @@ import type { ServicePeriod, TripDirection } from '@/types/servicePeriod' -export interface DateRange { +interface DateRange { start: string end: string } @@ -12,7 +12,7 @@ function parseCalendarDate(date: string): Date { return new Date(year, month - 1, day) } -export function isDateInRange( +function isDateInRange( date: string, range: { start: string From 3cb68213a8673d9bc4749f17411915ab3766fca8 Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Wed, 2 Dec 2026 23:26:33 -0800 Subject: [PATCH 6/9] Remove unused exports from servicePeriod helpers --- frontend/src/lib/servicePeriodUtils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/lib/servicePeriodUtils.ts b/frontend/src/lib/servicePeriodUtils.ts index c79e2f0..0242189 100644 --- a/frontend/src/lib/servicePeriodUtils.ts +++ b/frontend/src/lib/servicePeriodUtils.ts @@ -22,7 +22,7 @@ function isDateInRange( return date >= range.start && date <= range.end } -export function getPeriodForDate( +function getPeriodForDate( date: string, periods: ServicePeriod[], ): ServicePeriod | undefined { From 551c69d50193682b7f817a9fec5795d2d686d561 Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Wed, 2 Dec 2026 23:37:44 -0800 Subject: [PATCH 7/9] Remove redundant files --- .../src/config/servicePeriodHelpers.test.ts | 183 ------------- frontend/src/config/servicePeriodHelpers.ts | 244 ------------------ frontend/src/config/servicePeriods.ts | 6 - 3 files changed, 433 deletions(-) delete mode 100644 frontend/src/config/servicePeriodHelpers.test.ts delete mode 100644 frontend/src/config/servicePeriodHelpers.ts delete mode 100644 frontend/src/config/servicePeriods.ts diff --git a/frontend/src/config/servicePeriodHelpers.test.ts b/frontend/src/config/servicePeriodHelpers.test.ts deleted file mode 100644 index affc786..0000000 --- a/frontend/src/config/servicePeriodHelpers.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -/** @jest-environment node */ - -import { - formatCoverageWindowForDisplay, - formatDeadlineForDisplay, - getAllowedDirectionsForDate, - getDerivedCoveredDates, - isDateCovered, - isDirectionAllowedForDate, - isFlightPastDeadline, -} from '@/config/servicePeriodHelpers' - -import { - getServicePeriods, - type ServicePeriod, -} from '@/lib/server/getServicePeriods' - -jest.mock('react', () => ({ - ...jest.requireActual('react'), - cache: (fn: any) => fn, -})) - -jest.mock('@/lib/server/getServicePeriods') - -const mockGetServicePeriods = jest.mocked(getServicePeriods) - -const mockPeriods: ServicePeriod[] = [ - { - id: 'spring-2026-outbound', - name: 'Spring Break', - coverage_start: '2026-03-13', - coverage_end: '2026-03-15', - outbound: true, - inbound: false, - deadline: '2026-03-06T23:59:59-08:00', - }, - { - id: 'spring-2026-inbound', - name: 'Spring Break', - coverage_start: '2026-03-20', - coverage_end: '2026-03-22', - outbound: false, - inbound: true, - deadline: '2026-03-06T23:59:59-08:00', - }, -] - -beforeEach(() => { - jest.clearAllMocks() - mockGetServicePeriods.mockResolvedValue(mockPeriods) -}) - -describe('getDerivedCoveredDates', () => { - it('builds outbound and inbound MM-DD lists', async () => { - const dates = await getDerivedCoveredDates() - - expect(dates.outbound).toEqual(['03-13', '03-14', '03-15']) - - expect(dates.inbound).toEqual(['03-20', '03-21', '03-22']) - }) -}) - -describe('getAllowedDirectionsForDate', () => { - it('returns outbound directions', async () => { - expect(await getAllowedDirectionsForDate('2026-03-14')).toEqual([ - 'outbound', - ]) - }) - - it('returns inbound directions', async () => { - expect(await getAllowedDirectionsForDate('2026-03-21')).toEqual(['inbound']) - }) - - it('returns empty array for uncovered dates', async () => { - expect(await getAllowedDirectionsForDate('2026-03-18')).toEqual([]) - }) - - it('returns empty array for blank dates', async () => { - expect(await getAllowedDirectionsForDate('')).toEqual([]) - }) -}) - -describe('isDateCovered', () => { - it('recognizes outbound coverage', async () => { - expect(await isDateCovered('2026-03-14', true)).toBe(true) - - expect(await isDateCovered('2026-03-14', false)).toBe(false) - }) - - it('recognizes inbound coverage', async () => { - expect(await isDateCovered('2026-03-21', false)).toBe(true) - - expect(await isDateCovered('2026-03-21', true)).toBe(false) - }) - - it('returns false for uncovered dates', async () => { - expect(await isDateCovered('2026-03-18', true)).toBe(false) - - expect(await isDateCovered('2026-03-18', false)).toBe(false) - }) -}) - -describe('isDirectionAllowedForDate', () => { - it('maps toAirport=true to outbound', async () => { - expect(await isDirectionAllowedForDate('2026-03-14', true)).toBe(true) - - expect(await isDirectionAllowedForDate('2026-03-14', false)).toBe(false) - }) - - it('maps toAirport=false to inbound', async () => { - expect(await isDirectionAllowedForDate('2026-03-21', false)).toBe(true) - - expect(await isDirectionAllowedForDate('2026-03-21', true)).toBe(false) - }) -}) - -describe('isFlightPastDeadline', () => { - it('returns false before deadline', async () => { - const result = await isFlightPastDeadline( - '2026-03-14', - new Date('2026-03-05T12:00:00-08:00'), - ) - - expect(result).toEqual({ - isPastDeadline: false, - periodName: 'Spring Break', - deadline: new Date('2026-03-06T23:59:59-08:00'), - }) - }) - - it('returns true after deadline', async () => { - const result = await isFlightPastDeadline( - '2026-03-14', - new Date('2026-03-07T12:00:00-08:00'), - ) - - expect(result.isPastDeadline).toBe(true) - expect(result.periodName).toBe('Spring Break') - }) - - it('does not enforce deadlines outside coverage windows', async () => { - expect(await isFlightPastDeadline('2026-02-01', new Date())).toEqual({ - isPastDeadline: false, - }) - }) - - it('returns false for blank dates', async () => { - expect(await isFlightPastDeadline('')).toEqual({ - isPastDeadline: false, - }) - }) - - it('treats the exact deadline instant as not past', async () => { - const result = await isFlightPastDeadline( - '2026-03-14', - new Date('2026-03-06T23:59:59-08:00'), - ) - - expect(result.isPastDeadline).toBe(false) - }) -}) - -describe('formatDeadlineForDisplay', () => { - it('formats deadlines in PT', () => { - expect(formatDeadlineForDisplay('2026-03-06T23:59:59-08:00')).toBe( - 'Friday, March 6, 2026 at 11:59 PM PT', - ) - }) -}) - -describe('formatCoverageWindowForDisplay', () => { - it('formats outbound coverage windows', () => { - expect(formatCoverageWindowForDisplay(mockPeriods[0])).toEqual([ - 'Outbound: March 13-15', - ]) - }) - - it('formats inbound coverage windows', () => { - expect(formatCoverageWindowForDisplay(mockPeriods[1])).toEqual([ - 'Inbound: March 20-22', - ]) - }) -}) diff --git a/frontend/src/config/servicePeriodHelpers.ts b/frontend/src/config/servicePeriodHelpers.ts deleted file mode 100644 index 11b79e1..0000000 --- a/frontend/src/config/servicePeriodHelpers.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { type DateRange, type TripDirection } from '@/config/servicePeriods' -import { - getServicePeriods, - type ServicePeriod, -} from '@/lib/server/getServicePeriods' - -function parseCalendarDate(date: string): Date { - const [year, month, day] = date.split('-').map(Number) - return new Date(year, month - 1, day) -} - -function isDateInRange(date: string, range?: DateRange): boolean { - if (!date || !range) { - return false - } - - const target = parseCalendarDate(date) - const start = parseCalendarDate(range.start) - const end = parseCalendarDate(range.end) - - return target >= start && target <= end -} - -function expandDateRangeToMMDD(range: DateRange): string[] { - const dates: string[] = [] - const cursor = parseCalendarDate(range.start) - const end = parseCalendarDate(range.end) - - while (cursor <= end) { - const month = String(cursor.getMonth() + 1).padStart(2, '0') - const day = String(cursor.getDate()).padStart(2, '0') - dates.push(`${month}-${day}`) - cursor.setDate(cursor.getDate() + 1) - } - - return dates -} - -export async function getDerivedCoveredDates(): Promise<{ - outbound: string[] - inbound: string[] -}> { - const periods = await getServicePeriods() - - const outbound = new Set() - const inbound = new Set() - - for (const period of periods) { - const range = { - start: period.coverage_start, - end: period.coverage_end, - } - - const dates = expandDateRangeToMMDD(range) - - if (period.outbound) { - dates.forEach((date) => outbound.add(date)) - } - - if (period.inbound) { - dates.forEach((date) => inbound.add(date)) - } - } - - return { - outbound: Array.from(outbound).sort(), - inbound: Array.from(inbound).sort(), - } -} - -export async function isDateCovered( - date: string, - toAirport: boolean, -): Promise { - // Subsidy eligibility is tied to the configured service period year. - // The derived MM-DD lists remain available for legacy year-agnostic consumers. - - return await isDirectionAllowedForDate(date, toAirport) -} - -async function getPeriodForDate( - date: string, -): Promise { - if (!date) { - return undefined - } - - const periods = await getServicePeriods() - - return periods.find((period: ServicePeriod) => - isDateInRange(date, { - start: period.coverage_start, - end: period.coverage_end, - }), - ) -} - -function getAllowedDirectionsForPeriodAndDate( - date: string, - period: ServicePeriod, -): TripDirection[] { - const directions: TripDirection[] = [] - - const isCovered = isDateInRange(date, { - start: period.coverage_start, - end: period.coverage_end, - }) - - if (!isCovered) { - return directions - } - - if (period.outbound) { - directions.push('outbound') - } - - if (period.inbound) { - directions.push('inbound') - } - - return directions -} - -export async function getAllowedDirectionsForDate( - date: string, -): Promise { - if (!date) { - return [] - } - - const periods = await getServicePeriods() - - const directions = new Set() - - for (const period of periods) { - for (const direction of getAllowedDirectionsForPeriodAndDate( - date, - period, - )) { - directions.add(direction) - } - } - - return ['outbound', 'inbound'].filter((direction) => - directions.has(direction as TripDirection), - ) as TripDirection[] -} - -export async function isDirectionAllowedForDate( - date: string, - toAirport: boolean, -): Promise { - const direction: TripDirection = toAirport ? 'outbound' : 'inbound' - - const allowedDirections = await getAllowedDirectionsForDate(date) - - return allowedDirections.includes(direction) -} - -export async function isFlightPastDeadline( - flightDate: string, - now: Date = new Date(), -): Promise<{ - isPastDeadline: boolean - periodName?: string - deadline?: Date -}> { - if (!flightDate) { - return { isPastDeadline: false } - } - - const period = await getPeriodForDate(flightDate) - - if (!period) { - return { isPastDeadline: false } - } - - const deadlineDate = new Date(period.deadline) - - return { - isPastDeadline: now > deadlineDate, - periodName: period.name, - deadline: deadlineDate, - } -} - -export function formatDeadlineForDisplay(deadline: string): string { - const deadlineDate = new Date(deadline) - const weekday = deadlineDate.toLocaleDateString('en-US', { - timeZone: 'America/Los_Angeles', - weekday: 'long', - }) - const datePart = deadlineDate.toLocaleDateString('en-US', { - timeZone: 'America/Los_Angeles', - month: 'long', - day: 'numeric', - year: 'numeric', - }) - const timePart = deadlineDate.toLocaleTimeString('en-US', { - timeZone: 'America/Los_Angeles', - hour: 'numeric', - minute: '2-digit', - hour12: true, - }) - - return `${weekday}, ${datePart} at ${timePart} PT` -} - -function formatShortDateRange(range: DateRange): string { - const start = parseCalendarDate(range.start) - const end = parseCalendarDate(range.end) - const startMonth = start.toLocaleDateString('en-US', { month: 'long' }) - const endMonth = end.toLocaleDateString('en-US', { month: 'long' }) - const startDay = start.getDate() - const endDay = end.getDate() - - if (range.start === range.end) { - return `${startMonth} ${startDay}` - } - - if (startMonth === endMonth) { - return `${startMonth} ${startDay}-${endDay}` - } - - return `${startMonth} ${startDay}-${endMonth} ${endDay}` -} - -export function formatCoverageWindowForDisplay( - period: ServicePeriod, -): string[] { - const directions = [ - period.outbound && 'Outbound', - period.inbound && 'Inbound', - ] - .filter(Boolean) - .join(', ') - - return [ - `${directions}: ${formatShortDateRange({ - start: period.coverage_start, - end: period.coverage_end, - })}`, - ] -} diff --git a/frontend/src/config/servicePeriods.ts b/frontend/src/config/servicePeriods.ts deleted file mode 100644 index 683b0d6..0000000 --- a/frontend/src/config/servicePeriods.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type TripDirection = 'outbound' | 'inbound' - -export interface DateRange { - start: string - end: string -} From 1cf481f0c663e2010c0345ebddf120d04ee42421 Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Wed, 2 Dec 2026 23:41:49 -0800 Subject: [PATCH 8/9] Remove unused servicePeriod interface from getServicePeriods --- frontend/src/lib/server/getServicePeriods.ts | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/frontend/src/lib/server/getServicePeriods.ts b/frontend/src/lib/server/getServicePeriods.ts index feb9abe..b146698 100644 --- a/frontend/src/lib/server/getServicePeriods.ts +++ b/frontend/src/lib/server/getServicePeriods.ts @@ -3,16 +3,6 @@ import { createServiceRoleClient } from '@/lib/server/serviceRole' import { cache } from 'react' -export interface ServicePeriod { - id: string - name: string - outbound: boolean - inbound: boolean - coverage_start: string - coverage_end: string - deadline: string -} - export const getServicePeriods = cache(async () => { const supabase = createServiceRoleClient() From f2acbf39973e80409604f6056bf2de2b1c284198 Mon Sep 17 00:00:00 2001 From: "nowt2108@gmail.com" Date: Thu, 3 Dec 2026 00:07:32 -0800 Subject: [PATCH 9/9] Modify student deadline test to mock fetching service periods --- .../server/studentCommands.deadline.test.ts | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/frontend/src/lib/server/studentCommands.deadline.test.ts b/frontend/src/lib/server/studentCommands.deadline.test.ts index 7361ca8..4c3d198 100644 --- a/frontend/src/lib/server/studentCommands.deadline.test.ts +++ b/frontend/src/lib/server/studentCommands.deadline.test.ts @@ -6,12 +6,58 @@ jest.mock('react', () => ({ cache: (fn: any) => fn, })) +jest.mock('@/lib/server/getServicePeriods', () => ({ + getServicePeriods: jest.fn(), +})) + import { createOwnFlight, deleteOwnFlight, updateOwnFlight, } from '@/lib/server/studentCommands' +import { ServicePeriod } from '@/types/servicePeriod' +import { getServicePeriods } from '@/lib/server/getServicePeriods' + +const mockServicePeriods: ServicePeriod[] = [ + { + id: 'spring-2026', + name: 'Spring Break', + outbound: true, + inbound: true, + coverage_start: '2026-03-13', + coverage_end: '2026-03-22', + deadline: '2026-03-06T23:59:59-08:00', + }, + { + id: 'winter-2025-outbound', + name: 'Winter Break (Outbound)', + outbound: true, + inbound: false, + coverage_start: '2025-12-09', + coverage_end: '2025-12-13', + deadline: '2025-12-03T23:59:59-08:00', + }, + { + id: 'winter-2026-return', + name: 'Winter Break (Return)', + outbound: false, + inbound: true, + coverage_start: '2026-01-17', + coverage_end: '2026-01-21', + deadline: '2026-01-09T23:59:59-08:00', + }, + { + id: 'summer-2026', + name: 'Summer Break', + outbound: true, + inbound: false, + coverage_start: '2026-05-12', + coverage_end: '2026-05-19', + deadline: '2026-05-06T23:59:59-07:00', + }, +] + const completeProfile = { firstname: 'Taylor', lastname: 'Student', @@ -67,7 +113,10 @@ const createClient = () => { } describe('student flight deadline enforcement at the server boundary', () => { + const mockedGetServicePeriods = jest.mocked(getServicePeriods) + beforeEach(() => { + mockedGetServicePeriods.mockResolvedValue(mockServicePeriods) jest.useFakeTimers() })