diff --git a/api/_lib/mapping.ts b/api/_lib/mapping.ts index 900d87b..dfeafcc 100644 --- a/api/_lib/mapping.ts +++ b/api/_lib/mapping.ts @@ -108,7 +108,8 @@ export function docToTables(d: Db): Record { 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; } @@ -140,7 +141,10 @@ export function tablesToDoc(t: Record): Db { const valueLists: Record = {}; for (const r of rows('value_lists')) (valueLists[S(r.field)] ??= []).push(S(r.value)); const helpTopics: Record = {}; - 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) : '', diff --git a/api/_lib/permissions.test.ts b/api/_lib/permissions.test.ts index f1ccbf3..2128f2c 100644 --- a/api/_lib/permissions.test.ts +++ b/api/_lib/permissions.test.ts @@ -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 }); diff --git a/api/_lib/permissions.ts b/api/_lib/permissions.ts index de68e6d..5ed3e05 100644 --- a/api/_lib/permissions.ts +++ b/api/_lib/permissions.ts @@ -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.'; } diff --git a/api/_lib/state.ts b/api/_lib/state.ts index 915e930..aac516f 100644 --- a/api/_lib/state.ts +++ b/api/_lib/state.ts @@ -39,6 +39,13 @@ async function loadTables(q: Q): Promise> { return out; } +/** A trivial query, so a scheduled call keeps the free Supabase project from pausing for inactivity. */ +export async function ping(): Promise { + const started = Date.now(); + await client().unsafe('select 1'); + return Date.now() - started; +} + export async function readState(): Promise { await ensureSchema(); const s = client(); diff --git a/api/health.ts b/api/health.ts new file mode 100644 index 0000000..9e213ab --- /dev/null +++ b/api/health.ts @@ -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.' }); + } +} diff --git a/src/components/Reports.tsx b/src/components/Reports.tsx new file mode 100644 index 0000000..8f94c6e --- /dev/null +++ b/src/components/Reports.tsx @@ -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): 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 ( + <> + + {open && createPortal( 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>({}); + 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>(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 ( +
+
+
+ {reports.length > 1 && ( + + )} + {params.map((p) => ( + + ))} +
+ {report.sections.length > 1 && ( +
+ Print sections +
+ {report.sections.map((s) => )} +
+
+ )} +
+ + +
+
+ +
+
+
SignMeUp · Course registration
+

{report.title}

+ {report.subtitle &&

{report.subtitle}

} +
+ {report.meta.map(([k, v]) =>
{k}
{v}
)} +
Printed by
{realUser?.name ?? user?.name ?? '—'}
+
Date
{formatDateTime(printedAt)}
+
+
+ {!report.sections.length &&

Nothing to report.

} + {report.sections.length > 0 && !shown.length &&

Every section is unticked. Tick at least one section to print.

} + {shown.map((s) => ( +
+

{s.title}

+ {s.note &&

{s.note}

} + {s.rows.length === 0 + ?

{s.empty ?? 'No entries.'}

+ : ( +
+ + {s.columns.map((c, i) => )} + {s.rows.map((r, ri) => {r.map((cell, ci) => )})} +
{c}
{cell}
+
+ )} + {s.summary &&
{s.summary.map(([k, v]) =>
{k}
{v}
)}
} +
+ ))} +
SignMeUp · {report.title} · printed {formatDateTime(printedAt)}
+
+
+ ); +} diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx new file mode 100644 index 0000000..011d03d --- /dev/null +++ b/src/components/Settings.tsx @@ -0,0 +1,152 @@ +import { useState } from 'react'; +import { useStore } from '../data/store'; +import type { HelpTopic } from '../data/types'; +import { listOf, PARAMETERS } from '../lib/parameters'; +import { formatDateTime } from '../lib/format'; +import { HELP } from './help'; +import { MODULES } from '../modules'; +import { Banner, Chip } from './ui'; +import { Plus, X } from './icons'; +import { useToast } from './Shell'; + +/** + * Value lists and validation parameters (GEN-11, GEN-12), maintained by administrators. Each list + * is edited as a draft; Save stores it and Cancel and restore discards the changes. + */ +export function ValueListsEditor() { + const { db, saveValueList } = useStore(); + const toast = useToast(); + const [key, setKey] = useState(PARAMETERS[0].key); + const def = PARAMETERS.find((p) => p.key === key)!; + const stored = listOf(db, key); + const [draft, setDraft] = useState(stored); + const [adding, setAdding] = useState(''); + const [err, setErr] = useState<{ reason: string; requirement: string } | null>(null); + const dirty = JSON.stringify(draft) !== JSON.stringify(stored); + const choose = (k: string) => { setKey(k); setDraft(listOf(db, k)); setAdding(''); setErr(null); }; + const move = (i: number, d: number) => { const n = [...draft]; const [x] = n.splice(i, 1); n.splice(i + d, 0, x); setDraft(n); }; + function save() { + const r = saveValueList(key, draft); + if (!r.ok) return setErr(r); + setErr(null); + toast(`${def.label} saved`); + } + return ( +
+ +
+

{def.label}

{def.help}
{def.fixed && Fixed}
+
+ {def.kind === 'number' ? ( +
+ { setDraft([e.target.value]); setErr(null); }} />
+ ) : ( + <> +
    + {draft.map((v, i) => ( +
  1. + {v} + {!def.fixed && <> + + + + } +
  2. + ))} +
+ {!def.fixed && ( +
{ e.preventDefault(); if (adding.trim()) { setDraft([...draft, adding.trim()]); setAdding(''); setErr(null); } }}> + setAdding(e.target.value)} placeholder="Add a value" aria-label="New value" /> + +
+ )} + + )} + {err && {err.reason} {err.requirement}} +
+ {!def.fixed && ( +
+
+ + + In any field that uses this list, press F4 or Alt+↓ to pick a value. +
+
+ )} +
+
+ ); +} + +const HELP_KEYS = Object.keys(HELP); +const screenName = (key: string) => HELP[key]?.title ?? key; + +/** On-line help maintenance under security control: administrators edit each screen's help, or restore the built-in text. */ +export function HelpEditor({ initialKey }: { initialKey?: string | null }) { + const { db, saveHelpTopic } = useStore(); + const toast = useToast(); + const [key, setKey] = useState(initialKey && HELP[initialKey] ? initialKey : HELP_KEYS[0]); + const stored = db.helpTopics?.[key]; + const current: HelpTopic = stored?.editedAt ? stored : HELP[key]; + const [draft, setDraft] = useState(current); + const [err, setErr] = useState<{ reason: string; requirement: string } | null>(null); + const dirty = JSON.stringify([draft.title, draft.summary, draft.fields]) !== JSON.stringify([current.title, current.summary, current.fields]); + const choose = (k: string) => { setKey(k); const s = db.helpTopics?.[k]; setDraft(s?.editedAt ? s : HELP[k]); setErr(null); }; + const setField = (i: number, j: 0 | 1, v: string) => setDraft({ ...draft, fields: draft.fields.map((f, n) => (n === i ? (j === 0 ? [v, f[1]] : [f[0], v]) : f)) }); + function save() { + const r = saveHelpTopic(key, draft); + if (!r.ok) return setErr(r); + setErr(null); + toast(`Help for ${screenName(key)} saved`); + } + function restore() { + saveHelpTopic(key, null); + setDraft(HELP[key]); + setErr(null); + toast(`Help for ${screenName(key)} restored to the built-in text`); + } + const usedBy = MODULES.filter((m) => m.home.replace('/', '') === key).map((m) => m.label); + return ( +
+ +
+

Help · {screenName(key)}

{stored?.editedAt ? `Edited by ${stored.editedBy} · ${formatDateTime(stored.editedAt)}` : 'Built-in text'}{usedBy.length ? ` · ${usedBy.join(', ')}` : ''}
+
+
setDraft({ ...draft, title: e.target.value })} />
+