Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/lib/api/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,72 @@ describe('API calls that moved to new paths', () => {
});
});

describe('registration endpoints', () => {
const base = 'https://calendar.example.test/api';
const request = { term_uid: 202720, courses: [{ codes: ['COMP 3350'] }] };
const busy = () =>
new Response(JSON.stringify({ error: 'Busy', code: 'SCHEDULE_BUILDER_BUSY', retry_after: 1 }), {
status: 503,
headers: { 'Content-Type': 'application/json', 'Retry-After': '1' }
});

it('reads a saved plan with CRNs as strings, and null only for a missing plan', async () => {
fetchMock.mockResolvedValueOnce(
json({
term: { uid: 202720, name: 'Spring 2027' },
courses: [{ code: 'PSYC 1500', crns: ['20620'], fills: null }],
preferences: {},
crns: ['20620'],
updated_at: '2026-11-12T12:00:00Z',
schedule_check: {
sections: [],
not_found: [20999],
cancelled: [],
conflicts: [],
link_problems: [],
duplicates: [],
totals: { days: [] }
}
})
);
const saved = await API.getRegistrationPlan('202720');
expect(fetchMock.mock.calls[0][0]).toBe(`${base}/user/registration_plans/202720`);
expect(saved?.schedule_check.not_found).toEqual(['20999']);
expect(saved?.updated_at).toBe('2026-11-12T12:00:00Z');
fetchMock.mockResolvedValueOnce(json({ error: 'Registration plan not found' }, 404));
expect(await API.getRegistrationPlan('202720')).toBeNull();
fetchMock.mockResolvedValueOnce(json({ error: 'Term not found' }, 404));
await expect(API.getRegistrationPlan('1')).rejects.toMatchObject({ status: 404 });
});

it('retries the builder once after Retry-After, then reports it busy', async () => {
vi.useFakeTimers();
try {
fetchMock
.mockResolvedValueOnce(busy())
.mockResolvedValueOnce(json({ data: { count: 3, capped: false } }));
const counted = API.countScheduleOptions(request);
await vi.advanceTimersByTimeAsync(999);
expect(fetchMock).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
expect(await counted).toEqual({ count: 3, capped: false });
expect(fetchMock.mock.calls[0][0]).toBe(`${base}/v1/catalog/schedule_options/count`);

fetchMock.mockReset();
fetchMock.mockImplementation(async () => busy());
const failed = expect(API.scheduleOptions(request)).rejects.toMatchObject({
status: 503,
code: 'SCHEDULE_BUILDER_BUSY'
});
await vi.advanceTimersByTimeAsync(1000);
await failed;
expect(fetchMock).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
}
});
});

describe('Friends screenshot API compatibility (update scripts/screenshot-data.js on drift)', () => {
const maintenance = 'Friends screenshot contract changed: update scripts/screenshot-data.js';
const classes = [{ title: 'Linear Algebra', meeting_times: [] }];
Expand Down
138 changes: 138 additions & 0 deletions src/lib/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,34 @@ import {
import { getBaseUrl, getJwtToken, readJson, request, requestJson } from './client';
import type { AcademicProfile, StoredAcademicProfile } from '../calendar/academicProfile';
import type { CourseOutcomes, CourseOutcomesResult } from '../calendar/courseOutcomes';
import {
degreeProgress,
nextTermCourses,
savedPlan,
scheduleCheck,
scheduleCount,
scheduleOptions,
sectionPage
} from '../registration/parse';
import type {
DegreeProgress,
NextTermCourses,
RegistrationPlanBody,
SavedRegistrationPlan,
ScheduleCheck,
ScheduleCount,
ScheduleOptionsRequest,
ScheduleOptionsResponse,
SectionPage,
SectionQuery
} from '../registration/types';
import { ApiError } from './client';

export { ApiError } from './client';

const BUILDER_BUSY = 'SCHEDULE_BUILDER_BUSY';
const MAX_RETRY_SECONDS = 10;

const PREFERENCE_VERSION = /^[a-f0-9]{64}$/;

export class API {
Expand Down Expand Up @@ -256,6 +281,119 @@ export class API {
);
}

public static async getDegreeProgress(): Promise<DegreeProgress> {
return degreeProgress(
await requestJson(
'/user/degree_progress?include_planned=true',
'Failed to fetch your degree progress'
)
);
}

public static async getNextTermCourses(term?: string): Promise<NextTermCourses> {
const query = new URLSearchParams({ assume_plans: 'true', include: 'candidates' });
if (term) query.set('term', term);
return nextTermCourses(
await requestJson(`/user/next_term_courses?${query}`, 'Failed to fetch your course plan')
);
}

public static async getRegistrationPlan(termUid: string): Promise<SavedRegistrationPlan | null> {
try {
return savedPlan(
await requestJson(
`/user/registration_plans/${encodeURIComponent(termUid)}`,
'Failed to fetch your saved plan'
)
);
} catch (error) {
if (
error instanceof ApiError &&
error.status === 404 &&
error.message === 'Registration plan not found'
)
return null;
throw error;
}
}

public static async saveRegistrationPlan(
termUid: string,
body: RegistrationPlanBody
): Promise<SavedRegistrationPlan> {
return savedPlan(
await requestJson(
`/user/registration_plans/${encodeURIComponent(termUid)}`,
'Failed to save your plan',
{ method: 'PUT', body }
)
);
}

public static async getSections(params: SectionQuery): Promise<SectionPage> {
const query = new URLSearchParams({ term_uid: String(params.term_uid) });
if (params.subject) query.set('subject', params.subject);
if (params.course_number?.length) query.set('course_number', params.course_number.join(','));
if (params.crn?.length) query.set('crn', params.crn.join(','));
if (params.q) query.set('q', params.q);
if (params.page) query.set('page', String(params.page));
if (params.per_page) query.set('per_page', String(params.per_page));
return sectionPage(
await requestJson(`/v1/catalog/sections?${query}`, 'Failed to fetch sections')
);
}

public static async scheduleCheck(termUid: string, crns: string[]): Promise<ScheduleCheck> {
const query = new URLSearchParams({ term_uid: termUid, crn: crns.join(',') });
return scheduleCheck(
await requestJson(`/v1/catalog/schedule_check?${query}`, 'Failed to check your schedule')
);
}

public static async scheduleOptions(
body: ScheduleOptionsRequest
): Promise<ScheduleOptionsResponse> {
return scheduleOptions(
await this.scheduleBuilder('/v1/catalog/schedule_options', body, 'Failed to build schedules')
);
}

public static async countScheduleOptions(body: ScheduleOptionsRequest): Promise<ScheduleCount> {
return scheduleCount(
await this.scheduleBuilder(
'/v1/catalog/schedule_options/count',
body,
'Failed to count schedules'
)
);
}

private static async scheduleBuilder(
path: string,
body: ScheduleOptionsRequest,
failureMessage: string
): Promise<unknown> {
const response = await request(path, { method: 'POST', body });
const wait = await this.busyDelay(response);
if (wait === undefined) return readJson(response, failureMessage);
await new Promise((resolve) => setTimeout(resolve, wait));
return requestJson(path, failureMessage, { method: 'POST', body });
}

private static async busyDelay(response: Response): Promise<number | undefined> {
if (response.status !== 503) return undefined;
let retryAfter: unknown;
try {
const body = await response.clone().json();
if (body?.code !== BUILDER_BUSY) return undefined;
retryAfter = body.retry_after;
} catch {
return undefined;
}
const seconds = Number(response.headers.get('Retry-After') ?? retryAfter ?? 1);
return Math.min(Math.max(Number.isFinite(seconds) ? seconds : 1, 0), MAX_RETRY_SECONDS) * 1000;
}

public static async getFriends(): Promise<FriendListResponse> {
return friendList(await requestJson<FriendListResponse>('/friends', 'Failed to fetch friends'));
}
Expand Down
7 changes: 7 additions & 0 deletions src/lib/components/panel/PanelShell.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import iconCalendar from '@ktibow/iconset-material-symbols/calendar-month';
import iconSettings from '@ktibow/iconset-material-symbols/settings-outline';
import iconHelp from '@ktibow/iconset-material-symbols/help-outline';
import iconRegistration from '@ktibow/iconset-material-symbols/how-to-reg';

let {
title,
Expand Down Expand Up @@ -37,6 +38,12 @@
value: 'calendar',
icon: iconCalendar,
onselect: () => void goto(resolve('/calendar'))
},
{
name: 'Registration',
value: 'registration',
icon: iconRegistration,
onselect: () => void goto(resolve('/registration'))
}
];
const utilities = [
Expand Down
Loading
Loading