Skip to content
Merged
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
12 changes: 10 additions & 2 deletions api/_lib/permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,23 @@ describe('object-based security', () => {
expect(check(MARIA, { ...db, transactions: db.transactions.slice(1) }).ok).toBe(false);
});

it('refuses a student registering after the deadline, but not a drop or a staff registration', () => {
it('refuses a student registering or dropping after the deadline, but not the registrar', () => {
const open = db.offerings.find((o) => !db.registrations.some((r) => r.studentId === MARIA && r.scheduleNo === o.scheduleNo))!;
const late = '2026-10-28';
const closed = { ...db, registrationCloses: '2026-09-26' };
const add = { ...register(MARIA, open.scheduleNo), registrationCloses: '2026-09-26' };
expect(checkObjectPermissions(email(MARIA), closed, add, [], late).ok).toBe(false);
expect(checkObjectPermissions(email(ROSA), closed, add, [], late)).toEqual({ ok: true });
const mine = db.registrations.find((r) => r.studentId === MARIA && !r.grade)!;
expect(checkObjectPermissions(email(MARIA), closed, { ...closed, registrations: closed.registrations.filter((r) => r !== mine) }, [], late)).toEqual({ ok: true });
const dropped = { ...closed, registrations: closed.registrations.filter((r) => r !== mine) };
expect(checkObjectPermissions(email(MARIA), closed, dropped, [], late).ok).toBe(false);
expect(checkObjectPermissions(email(ADMIN), closed, dropped, [], late)).toEqual({ ok: true });
expect(checkObjectPermissions(email(MARIA), closed, dropped, [], '2026-09-26')).toEqual({ ok: true }); // the deadline day itself is still open
});

it('lets a student send a request to their own record only, stamped with their own ID', () => {
expect(check(MARIA, addNote(MARIA, MARIA))).toEqual({ ok: true });
expect(check(MARIA, addNote(TOMAS, MARIA)).ok).toBe(false);
});

it('lets a student register and drop only for themself', () => {
Expand Down
1 change: 1 addition & 0 deletions api/_lib/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ function refusal(c: Change, { user: me, isNew }: Actor, before: Db, after: Db, t
}
if (GRADE_COLS.some((k) => (c.before ?? c.after)![k] != null) && !canGrade) return 'A graded registration can be changed only by the instructor or a user with grade update privileges.';
if (!c.before && !staff && before.registrationCloses && today > before.registrationCloses) return `Registration for ${before.term} closed on ${before.registrationCloses}. Ask the registrar to register you.`;
if (!c.after && !staff && before.registrationCloses && today > before.registrationCloses) return `The add/drop deadline for ${before.term} passed on ${before.registrationCloses}. Send a drop request to your advisor; the registrar drops the course once it is approved.`;
return ownStudent || (staff && has('REG')) ? null : 'You can register or drop courses only for yourself.';
}

Expand Down
78 changes: 78 additions & 0 deletions src/components/RequestPanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { useState } from 'react';
import { useStore } from '../data/store';
import type { Student } from '../data/types';
import { useToast } from './Shell';
import { Banner, FieldError } from './ui';
import { X } from './icons';
import { useEscapeToCancel } from './draft';
import { courseOf, currentRegistrations, offeringOf } from '../lib/rules';
import { formatDate } from '../lib/format';
import { MESSAGE_MAX, REQUEST_KINDS, requestRecipients, type RequestField, type RequestKind, type StudentRequest } from '../lib/requests';

/**
* Side panel where a student sends a request to their major advisor, an instructor or the registrar.
* `dropAfterDeadline` opens it in place of dropping once the add/drop deadline has passed, so the
* student talks to someone before losing a course they cannot add back.
*/
export function RequestPanel({ student, initial, dropAfterDeadline = false, onClose }: { student: Student; initial?: Partial<StudentRequest>; dropAfterDeadline?: boolean; onClose: () => void }) {
const { db, sendRequest } = useStore();
const toast = useToast();
const recipients = requestRecipients(db, student);
const courses = currentRegistrations(db, student.id).map((r) => offeringOf(db, r.scheduleNo)?.courseId).filter((c): c is string => !!c);
const [req, setReq] = useState<StudentRequest>({ to: recipients[0]?.id ?? '', kind: 'meeting', courseId: '', message: '', ...initial });
const [err, setErr] = useState<{ field: RequestField; reason: string; requirement: string } | null>(null);
useEscapeToCancel(true, onClose);

const set = (change: Partial<StudentRequest>) => { setReq((r) => ({ ...r, ...change })); setErr(null); };
const error = (f: RequestField) => (err?.field === f ? <FieldError reason={err.reason} requirement={err.requirement} /> : null);

function send() {
const r = sendRequest(student.id, req);
if (!r.ok) return setErr(r);
toast(`Request sent to ${recipients.find((x) => x.id === req.to)?.name ?? 'staff'} · added to your student record`);
onClose();
}

return (
<aside className="panel" aria-label={dropAfterDeadline ? 'Drop request' : 'Send a request'}>
<div className="panel-head"><h2>{dropAfterDeadline ? 'Talk to your advisor before dropping' : 'Send a request'}</h2><button className="btn ghost sm icon" onClick={onClose} aria-label="Close"><X /></button></div>
<div className="panel-body">
{dropAfterDeadline && (
<Banner kind="warn"><strong>The add/drop deadline for {db.term} passed on {formatDate(db.registrationCloses)}.</strong> A course dropped now cannot be added back. Send a drop request or ask for a meeting with your major advisor or instructor; the registrar drops the course once it is approved.</Banner>
)}
<div className="field">
<label className="label" htmlFor="rq-to">To <span className="req">*</span></label>
<select id="rq-to" className={`input${err?.field === 'to' ? ' error' : ''}`} value={req.to} onChange={(e) => set({ to: e.target.value })}>
{recipients.map((r) => <option key={r.id} value={r.id}>{r.name} · {r.label}</option>)}
</select>
{error('to')}
</div>
<div className="field">
<label className="label" htmlFor="rq-kind">Request <span className="req">*</span></label>
<select id="rq-kind" className="input" value={req.kind} onChange={(e) => set({ kind: e.target.value as RequestKind })}>
{Object.entries(REQUEST_KINDS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
{error('kind')}
</div>
<div className="field">
<label className="label" htmlFor="rq-course">Course {req.kind === 'drop' && <span className="req">*</span>}</label>
<select id="rq-course" className={`input${err?.field === 'courseId' ? ' error' : ''}`} value={req.courseId} onChange={(e) => set({ courseId: e.target.value })}>
<option value="">{req.kind === 'drop' ? 'Choose a course' : 'None'}</option>
{courses.map((c) => <option key={c} value={c}>{c} {courseOf(db, c)?.title}</option>)}
</select>
{error('courseId')}
</div>
<div className="field">
<label className="label" htmlFor="rq-msg">Message <span className="req">*</span></label>
<textarea id="rq-msg" className={`input${err?.field === 'message' ? ' error' : ''}`} maxLength={MESSAGE_MAX} value={req.message} onChange={(e) => set({ message: e.target.value })} placeholder={req.kind === 'drop' ? 'Why you want to drop the course' : 'What you need'} />
{error('message')}
<div className="sub">Saved to your student record, where your advisors and the registrar read it. It cannot be changed or deleted.</div>
</div>
</div>
<div className="panel-foot">
<button className="btn lg" onClick={send}>Send request</button>
<button className="btn ghost" onClick={onClose}>Cancel and restore</button>
</div>
</aside>
);
}
4 changes: 2 additions & 2 deletions src/components/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ export const HELP: Record<string, HelpTopic> = {
},
dashboard: {
title: 'Student dashboard', summary: 'Your schedule for the current term, your running units total, and the major courses you can register for right now: on your approved outline, prerequisites completed, and seats still open. Register one course at a time.',
fields: [['Register', 'Adds the course after all rules pass: prerequisites, seats, time conflicts, the 18-unit maximum, program restrictions.'], ['Drop', 'Removes a course from your schedule and records who did it.']],
fields: [['Register', 'Adds the course after all rules pass: prerequisites, seats, time conflicts, the 18-unit maximum, program restrictions.'], ['Drop', 'Removes a course from your schedule and records who did it. After the add/drop deadline it opens a drop request instead: a dropped course cannot be added back, so the registrar drops it once your advisor or instructor approves.'], ['Send a request', 'Sends a request to your major advisor, an instructor or the registrar: drop a course, schedule a meeting, or anything else. Mandatory: To, Request and Message (up to 500 characters); Course is mandatory for a drop. It is saved to your student record and cannot be changed or deleted.']],
},
search: {
title: 'Course search & registration', summary: 'Search current offerings by course ID or title, filtered by department and term. Use * for any run of characters and ? for one character. Expand a row for the description and your prerequisite status; select a row to confirm registration in the side panel.',
fields: [['Course ID or title', 'Optional. Wildcards allowed, e.g. CS 3*.'], ['Department', 'Optional. Limits results to one department.'], ['Seats available only', 'Optional. Hides full sections.'], ['Registration type', 'Mandatory on confirm: letter grade, credit/no credit, or audit.']],
},
record: {
title: 'Electronic student record', summary: 'General student information, courses completed here and elsewhere, current enrollment, GPA, and notes. Notes are append-only: each entry is stamped with the date, time and employee ID of its author and can never be deleted.',
fields: [['Edit student information', 'Returns to the student information entry to add optional details (middle name, minor) or change earlier entries. Students may update their own telephone and address, and fill in key information that is still missing. Cancel and restore discards the changes.'], ['Key student information', 'Last name, telephone, address and date of birth. Until all four are entered, registration, major outline changes and course history entry are blocked.'], ['Add completed / transfer course', 'Staff only. Course ID, title, semester (e.g. Fall 2025), units and grade; transfer courses also need the university, its location and, if any, the equivalent course here. Correct fixes an entry; entries are never deleted.'], ['First, middle and last name', 'First and last are mandatory; middle is optional. Hyphenated names are accepted in any part, e.g. Okafor-Reyes.'], ['Telephone', 'Mandatory. 10 digits including area code.'], ['Address', 'Mandatory. Street, city, state and ZIP.'], ['Date of birth', 'Mandatory.'], ['Major', 'Mandatory. Undeclared is allowed.'], ['Minor', 'Optional. Must be outside the major’s department.'], ['Category', 'Mandatory when adding a note.'], ['Note', 'Mandatory. Free text; keep to the facts. Notes are listed oldest first and can never be changed or deleted.'], ['Print record', 'Prints the record with optional course detail, this university only or all courses, and the overall GPA.']],
fields: [['Edit student information', 'Returns to the student information entry to add optional details (middle name, minor) or change earlier entries. Students may update their own telephone and address, and fill in key information that is still missing. Cancel and restore discards the changes.'], ['Key student information', 'Last name, telephone, address and date of birth. Until all four are entered, registration, major outline changes and course history entry are blocked.'], ['Add completed / transfer course', 'Staff only. Course ID, title, semester (e.g. Fall 2025), units and grade; transfer courses also need the university, its location and, if any, the equivalent course here. Correct fixes an entry; entries are never deleted.'], ['First, middle and last name', 'First and last are mandatory; middle is optional. Hyphenated names are accepted in any part, e.g. Okafor-Reyes.'], ['Telephone', 'Mandatory. 10 digits including area code.'], ['Address', 'Mandatory. Street, city, state and ZIP.'], ['Date of birth', 'Mandatory.'], ['Major', 'Mandatory. Undeclared is allowed.'], ['Minor', 'Optional. Must be outside the major’s department.'], ['Category', 'Mandatory when adding a note.'], ['Note', 'Mandatory. Free text; keep to the facts. Notes are listed oldest first and can never be changed or deleted.'], ['Send a request', 'Students only. Sends a request to your major advisor, an instructor or the registrar; it is added to your notes, marked Student request.'], ['Drop', 'Registrar and administrators, Current tab. Drops a course for the student, including after the add/drop deadline once a drop request is approved.'], ['Print record', 'Prints the record with optional course detail, this university only or all courses, and the overall GPA.']],
},
outline: {
title: 'Approved major outline', summary: 'The courses selected from the major for one student, each with a status of approved, dropped or waived and the date of that status. Only a major advisor or authorized department user may change it. Entries are never deleted; every change is added to the history.',
Expand Down
24 changes: 22 additions & 2 deletions src/data/store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { SyncClient } from './sync';
import type { CompletedCourse, Course, Db, HelpTopic, Major, NoteCategory, Offering, OutlineStatus, RegistrationType, Student, Subsystem, TransferCourse, User } from './types';
import { applyCourseSave, canMaintainCatalog, type CourseIssue } from '../lib/catalog';
import { normalizeList, valueListIssue } from '../lib/parameters';
import { applyOfferingRemove, applyOfferingSave, applyTermSave, registrationClosed, registrationClosedIssue, type TermDates } from '../lib/schedule';
import { applyOfferingRemove, applyOfferingSave, applyTermSave, dropClosedIssue, registrationClosed, registrationClosedIssue, type TermDates } from '../lib/schedule';
import { REQUEST_KINDS, requestIssue, requestNoteText, requestRecipients, type RequestField, type StudentRequest } from '../lib/requests';
import { applyMajorSave, type MajorIssue } from '../lib/majors';
import { applyFacultySave, type FacultyEntry, type FacultyIssue } from '../lib/faculty';
import { nowIso } from '../lib/format';
Expand Down Expand Up @@ -66,8 +67,9 @@ interface StoreApi {
signOut(): void;
resetDemo(): void;
register(studentId: string, scheduleNo: string, type: RegistrationType): Result;
drop(studentId: string, scheduleNo: string): void;
drop(studentId: string, scheduleNo: string): Result;
requestWaiver(studentId: string, courseId: string, note: string): void;
sendRequest(studentId: string, request: StudentRequest): { ok: true } | { ok: false; field: RequestField; reason: string; requirement: string };
appendNote(studentId: string, category: NoteCategory, text: string): void;
saveCourseHistory(studentId: string, kind: HistoryKind, entry: CompletedCourse | TransferCourse, originalKey: string | null): { ok: true } | ({ ok: false } & HistoryIssue);
updateStudent(studentId: string, info: StudentInfo): { ok: true } | { ok: false; field: keyof StudentInfo; reason: string; requirement: string };
Expand Down Expand Up @@ -338,7 +340,25 @@ export function StoreProvider({ children }: { children: ReactNode }) {

drop(studentId, scheduleNo) {
const offering = db.offerings.find((o) => o.scheduleNo === scheduleNo);
const staff = user?.role === 'registrar' || user?.role === 'admin'; // after the deadline only staff drop, once a drop request is approved
if (registrationClosed(db) && !staff) return { ok: false, issues: [dropClosedIssue(db)] };
commit((d) => stamp({ ...d, registrations: d.registrations.filter((r) => !(r.studentId === studentId && r.scheduleNo === scheduleNo)) }, 'REG', `Dropped ${offering?.courseId ?? scheduleNo} (${scheduleNo})`));
return { ok: true };
},

sendRequest(studentId, request) {
const student = db.students.find((s) => s.id === studentId);
if (!student || user?.studentId !== studentId) return { ok: false, field: 'to', reason: 'You can send requests only from your own student record.', requirement: 'Sign in as the student making the request.' };
const issue = requestIssue(db, student, request);
if (issue) return { ok: false, ...issue };
const text = requestNoteText(db, student, request);
const to = requestRecipients(db, student).find((r) => r.id === request.to)!;
const at = nowIso();
commit((d) => stamp({
...d,
students: d.students.map((s) => (s.id === studentId ? { ...s, notes: [...s.notes, { at, byEmployeeId: user.id, category: 'advising', text }] } : s)),
}, 'ER', `Sent ${REQUEST_KINDS[request.kind].toLowerCase()} request to ${to.name}`));
return { ok: true };
},

requestWaiver(studentId, courseId, note) {
Expand Down
Loading
Loading