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
8 changes: 6 additions & 2 deletions api/_lib/mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ export function docToTables(d: Db): Record<string, Row[]> {
for (const g of d.gradeNotes) t.grade_notes.push({ schedule_no: g.scheduleNo, at: g.at, by: g.by, text: g.text });
for (const x of d.transactions) t.transactions.push({ at: x.at, by: x.by, subsystem: x.subsystem, text: x.text });
for (const [field, values] of Object.entries(d.valueLists ?? {})) values.forEach((value, position) => t.value_lists.push({ field, value, position }));
for (const [key, h] of Object.entries(d.helpTopics ?? {})) t.help_topics.push({ key, title: h.title, summary: h.summary, fields: JSON.stringify(h.fields) });
// fields holds the field notes; an edited topic also records who edited it and when, in the same JSON column.
for (const [key, h] of Object.entries(d.helpTopics ?? {})) t.help_topics.push({ key, title: h.title, summary: h.summary, fields: JSON.stringify(h.editedAt ? { fields: h.fields, editedBy: h.editedBy, editedAt: h.editedAt } : h.fields) });
return t;
}

Expand Down Expand Up @@ -140,7 +141,10 @@ export function tablesToDoc(t: Record<string, Row[]>): Db {
const valueLists: Record<string, string[]> = {};
for (const r of rows('value_lists')) (valueLists[S(r.field)] ??= []).push(S(r.value));
const helpTopics: Record<string, HelpTopic> = {};
for (const r of rows('help_topics')) helpTopics[S(r.key)] = { title: S(r.title), summary: S(r.summary), fields: (typeof r.fields === 'string' ? JSON.parse(r.fields) : r.fields) as [string, string][] };
for (const r of rows('help_topics')) {
const raw = (typeof r.fields === 'string' ? JSON.parse(r.fields) : r.fields) as [string, string][] | { fields: [string, string][]; editedBy?: string; editedAt?: string };
helpTopics[S(r.key)] = Array.isArray(raw) ? { title: S(r.title), summary: S(r.summary), fields: raw } : { title: S(r.title), summary: S(r.summary), ...raw };
}

return {
term: term ? S(term.id) : '',
Expand Down
11 changes: 11 additions & 0 deletions api/_lib/permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ 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', () => {
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 });
});

it('lets a student register and drop only for themself', () => {
const open = db.offerings.find((o) => !db.registrations.some((r) => r.studentId === MARIA && r.scheduleNo === o.scheduleNo))!;
expect(check(MARIA, register(MARIA, open.scheduleNo))).toEqual({ ok: true });
Expand Down
1 change: 1 addition & 0 deletions api/_lib/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ function refusal(c: Change, { user: me, isNew }: Actor, before: Db, after: Db, t
return staff && has('REG') ? null : 'You can change only your own registrations.';
}
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.`;
return ownStudent || (staff && has('REG')) ? null : 'You can register or drop courses only for yourself.';
}

Expand Down
7 changes: 7 additions & 0 deletions api/_lib/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ async function loadTables(q: Q): Promise<Record<string, Row[]>> {
return out;
}

/** A trivial query, so a scheduled call keeps the free Supabase project from pausing for inactivity. */
export async function ping(): Promise<number> {
const started = Date.now();
await client().unsafe('select 1');
return Date.now() - started;
}

export async function readState(): Promise<Stored | null> {
await ensureSchema();
const s = client();
Expand Down
18 changes: 18 additions & 0 deletions api/health.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { VercelRequest, VercelResponse } from '@vercel/node';
import { ping, StateError } from './_lib/state.js';

/**
* GET /api/health -> { ok, databaseMs }
*
* Runs a trivial query against the shared database. Vercel Cron calls it daily (vercel.json) so the
* free Supabase project never sits idle long enough to be paused. It returns no data.
*/
export default async function handler(_req: VercelRequest, res: VercelResponse) {
res.setHeader('Cache-Control', 'no-store');
try {
return res.status(200).json({ ok: true, databaseMs: await ping() });
} catch (err) {
const status = err instanceof StateError ? err.status : 503;
return res.status(status).json({ ok: false, reason: err instanceof StateError ? err.message : 'Database unreachable.' });
}
}
109 changes: 109 additions & 0 deletions src/components/Reports.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { useStore } from '../data/store';
import type { Report } from '../lib/reports';
import { formatDateTime, nowIso } from '../lib/format';
import { useEscapeToCancel } from './draft';
import { Print, X } from './icons';

/** One choice on a report, e.g. department or major. The first option is the default. */
export interface ReportParam { key: string; label: string; options: [string, string][]; }
export interface ReportDef { id: string; label: string; params?: ReportParam[]; build(values: Record<string, string>): Report; }

/**
* Report viewer (GEN-18, Reporting Requirements): every report is shown on the workstation before
* printing, with its header information, and can be printed as a whole or in parts by keeping only
* some sections. Printing while the viewer is open prints the report alone.
*/
export function ReportsButton({ reports, label = 'Reports', className = 'btn secondary', initial }: { reports: ReportDef[]; label?: string; className?: string; initial?: string }) {
const [open, setOpen] = useState(false);
if (!reports.length) return null;
return (
<>
<button className={`${className} no-print`} onClick={() => setOpen(true)}>{label}</button>
{open && createPortal(<ReportViewer reports={reports} initial={initial} onClose={() => setOpen(false)} />, document.body)}
</>
);
}

function ReportViewer({ reports, initial, onClose }: { reports: ReportDef[]; initial?: string; onClose(): void }) {
const { user, realUser } = useStore();
const [reportId, setReportId] = useState(initial && reports.some((r) => r.id === initial) ? initial : reports[0].id);
const def = reports.find((r) => r.id === reportId)!;
const [values, setValues] = useState<Record<string, string>>({});
const params = def.params ?? [];
const resolved = Object.fromEntries(params.map((p) => [p.key, values[p.key] ?? p.options[0]?.[0] ?? '']));
const report = useMemo(() => def.build(resolved), [def, JSON.stringify(resolved)]);
const [hidden, setHidden] = useState<Set<string>>(new Set());
const [printedAt] = useState(nowIso);
useEffect(() => { setHidden(new Set()); }, [reportId, JSON.stringify(resolved)]);
useEscapeToCancel(true, onClose);
useEffect(() => {
document.body.classList.add('report-open');
return () => document.body.classList.remove('report-open');
}, []);
const shown = report.sections.filter((s) => !hidden.has(s.id));
const toggle = (id: string) => setHidden((h) => { const n = new Set(h); if (n.has(id)) n.delete(id); else n.add(id); return n; });

return (
<div className="report-overlay" role="dialog" aria-label="Report preview">
<div className="report-toolbar">
<div className="report-controls">
{reports.length > 1 && (
<label className="field"><span className="label">Report</span>
<select className="input" value={reportId} onChange={(e) => { setReportId(e.target.value); setValues({}); }}>{reports.map((r) => <option key={r.id} value={r.id}>{r.label}</option>)}</select></label>
)}
{params.map((p) => (
<label key={p.key} className="field"><span className="label">{p.label}</span>
<select className="input" value={resolved[p.key]} onChange={(e) => setValues({ ...values, [p.key]: e.target.value })}>{p.options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}</select></label>
))}
</div>
{report.sections.length > 1 && (
<div className="report-parts">
<span className="label">Print sections</span>
<div className="cluster" style={{ gap: 6 }}>
{report.sections.map((s) => <label key={s.id} className="check"><input type="checkbox" checked={!hidden.has(s.id)} onChange={() => toggle(s.id)} />{s.title}</label>)}
</div>
</div>
)}
<div className="report-actions">
<button className="btn" onClick={() => window.print()} disabled={!shown.length}><Print />Print</button>
<button className="btn ghost icon" onClick={onClose} aria-label="Close report"><X /></button>
</div>
</div>

<article className="report-doc">
<header className="report-head">
<div className="report-brand">SignMeUp · Course registration</div>
<h1>{report.title}</h1>
{report.subtitle && <p className="sub">{report.subtitle}</p>}
<dl className="report-meta">
{report.meta.map(([k, v]) => <div key={k}><dt>{k}</dt><dd>{v}</dd></div>)}
<div><dt>Printed by</dt><dd>{realUser?.name ?? user?.name ?? '—'}</dd></div>
<div><dt>Date</dt><dd>{formatDateTime(printedAt)}</dd></div>
</dl>
</header>
{!report.sections.length && <p className="sub">Nothing to report.</p>}
{report.sections.length > 0 && !shown.length && <p className="sub no-print">Every section is unticked. Tick at least one section to print.</p>}
{shown.map((s) => (
<section key={s.id} className="report-section">
<h2>{s.title}</h2>
{s.note && <p className="sub">{s.note}</p>}
{s.rows.length === 0
? <p className="sub">{s.empty ?? 'No entries.'}</p>
: (
<div className="report-table-wrap">
<table className="report-table">
<thead><tr>{s.columns.map((c, i) => <th key={c} className={s.numeric?.includes(i) ? 'num' : undefined}>{c}</th>)}</tr></thead>
<tbody>{s.rows.map((r, ri) => <tr key={ri}>{r.map((cell, ci) => <td key={ci} className={s.numeric?.includes(ci) ? 'num' : undefined}>{cell}</td>)}</tr>)}</tbody>
</table>
</div>
)}
{s.summary && <dl className="report-summary">{s.summary.map(([k, v]) => <div key={k}><dt>{k}</dt><dd>{v}</dd></div>)}</dl>}
</section>
))}
<footer className="report-foot">SignMeUp · {report.title} · printed {formatDateTime(printedAt)}</footer>
</article>
</div>
);
}
Loading
Loading