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/app/aspc-policy/page.tsx b/frontend/src/app/aspc-policy/page.tsx index 255ecd0..f470aa1 100644 --- a/frontend/src/app/aspc-policy/page.tsx +++ b/frontend/src/app/aspc-policy/page.tsx @@ -1,3 +1,5 @@ +'use client' + import { Lightbulb } from 'lucide-react' import Link from 'next/link' @@ -6,15 +8,49 @@ import { Card } from '@/components/ui/Card' import { PageContainer, PageHeader } from '@/components/ui/PageHeader' import { formatDeadlineForDisplay, - formatSubsidizedWindowsForDisplay, -} from '@/config/servicePeriodHelpers' -import { SERVICE_PERIODS } from '@/config/servicePeriods' + formatCoverageWindowForDisplay, +} from '@/lib/servicePeriodUtils' +import { ServicePeriod } from '@/types/servicePeriod' +import { useEffect, useState } from 'react' const textLink = 'font-medium text-navy underline underline-offset-2 hover:text-sage' export default function ASPCPolicy() { - const activePeriod = SERVICE_PERIODS[SERVICE_PERIODS.length - 1] + 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() + }, []) + + const activePeriod = servicePeriods[0] + + if (servicePeriodsLoading) { + return ( +
+ Loading service periods... +
+ ) + } return ( @@ -56,7 +92,7 @@ export default function ASPCPolicy() {
Service window:
    - {formatSubsidizedWindowsForDisplay(activePeriod).map( + {formatCoverageWindowForDisplay(activePeriod).map( (line) => (
  • {line}
  • ), @@ -103,7 +139,7 @@ export default function ASPCPolicy() {

    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/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 ( 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'} +
    + )}