From 8a10a7b04d7985b6c987329eb9d6609675ceacbf Mon Sep 17 00:00:00 2001 From: Miguel Reese Date: Tue, 27 Oct 2026 22:27:26 -0700 Subject: [PATCH 1/4] Add the subsystem reports with an on-screen preview and partial printing src/lib/reports.ts builds every report the requirements list from the shared document: - GRADE: course, department and university grade statistics (registered, passing, average, A-F shares). - FCI: faculty and course lists with short descriptions, for one department or the whole university by department (FCI-07 to FCI-10). - REG: student schedule, courses offered by a department, and courses with seats available by department or for all (REG-10 to REG-12). - MAJOR: required courses for a major, completed required courses, status against the approved outline, and outline change history (MAJ-08 to MAJ-10). - ER: the student record report with optional course detail, this university only or all universities, and overall GPA (ER-05 to ER-07). - Framework: the authorized-user report for the whole system or one subsystem, never with passwords (FW-06). A shared viewer (src/components/Reports.tsx) opens from each screen. It picks the report and its options, shows the full report on screen before printing (GEN-18) with SignMeUp header, printed-by and date, and prints all of it or only the ticked sections. While the viewer is open, printing prints the report alone. This replaces the Faculty & Courses "Department report" stub, the decorative print options on the student record, and the old user-report scope picker. Co-Authored-By: Claude Opus 5.5 --- src/components/Reports.tsx | 109 ++++++++++++++ src/lib/reports.test.ts | 77 ++++++++++ src/lib/reports.ts | 252 ++++++++++++++++++++++++++++++++ src/screens/AuthorizedUsers.tsx | 16 +- src/screens/CourseSearch.tsx | 10 +- src/screens/Dashboard.tsx | 3 + src/screens/FacultyCourses.tsx | 8 +- src/screens/GradeEntry.tsx | 3 + src/screens/MajorOutline.tsx | 9 ++ src/screens/StudentRecord.tsx | 18 +-- src/styles/global.css | 38 +++++ 11 files changed, 522 insertions(+), 21 deletions(-) create mode 100644 src/components/Reports.tsx create mode 100644 src/lib/reports.test.ts create mode 100644 src/lib/reports.ts 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/lib/reports.test.ts b/src/lib/reports.test.ts new file mode 100644 index 0000000..a3a455f --- /dev/null +++ b/src/lib/reports.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest'; +import { createSeed } from '../data/seed'; +import { gradeStats } from './rules'; +import { + authorizedUsersReport, completedRequiredReport, courseListReport, departmentChoices, departmentOfferingsReport, facultyListReport, gradeStatisticsReport, + majorChoices, majorRequirementsReport, outlineHistoryReport, outlineStatusReport, seatsAvailableReport, shortDescription, studentRecordReport, studentScheduleReport, +} from './reports'; + +const db = createSeed(); +const MARIA = '20231847'; +const sectionIds = (r: { sections: { id: string }[] }) => r.sections.map((s) => s.id); + +describe('reports', () => { + it('shortens descriptions to their first sentence', () => { + expect(shortDescription('Arrays and lists. Then trees.')).toBe('Arrays and lists.'); + expect(shortDescription('x'.repeat(120)).length).toBe(90); + }); + + it('grade statistics: one section per department plus university totals that match the raw data', () => { + const u = gradeStatisticsReport(db, null); + expect(sectionIds(u).at(-1)).toBe('university'); + const termRegs = db.registrations.filter((r) => db.offerings.find((o) => o.scheduleNo === r.scheduleNo)?.term === db.term); + expect(u.sections.at(-1)!.rows[0][3]).toBe(gradeStats(termRegs).registered); + const cs = gradeStatisticsReport(db, 'CS'); + expect(sectionIds(cs)).toEqual(['dept-CS']); + expect(String(cs.sections[0].rows.at(-1)![0])).toBe('Computer Science total'); + }); + + it('faculty and course lists by department or for the whole university', () => { + expect(facultyListReport(db, 'CS').sections).toHaveLength(1); + expect(facultyListReport(db, null).sections.length).toBeGreaterThan(1); + const courses = courseListReport(db, null); + expect(courses.sections.flatMap((s) => s.rows)).toHaveLength(db.courses.length); + expect(courseListReport(db, 'MATH').sections[0].rows.every((r) => String(r[0]).startsWith('MATH'))).toBe(true); + }); + + it('student schedule lists every current enrollment with a description and total units', () => { + const r = studentScheduleReport(db, MARIA); + const enrolled = db.registrations.filter((x) => x.studentId === MARIA && db.offerings.find((o) => o.scheduleNo === x.scheduleNo)?.term === db.term); + expect(r.sections[0].rows).toHaveLength(enrolled.length); + expect(r.sections[0].rows[0][3]).not.toBe(''); + }); + + it('courses offered by a department and courses with seats available', () => { + expect(departmentOfferingsReport(db, 'CS').sections[0].rows.every((row) => String(row[0]).startsWith('CS'))).toBe(true); + const seats = seatsAvailableReport(db, null); + expect(seats.sections.flatMap((s) => s.rows).every((row) => !String(row[8]).startsWith('0 of'))).toBe(true); + }); + + it('MAJOR reports for a major and for one student', () => { + const m = majorRequirementsReport(db, 'CS-BS'); + expect(sectionIds(m)).toEqual(['required', 'electives']); + expect(m.sections[0].rows).toHaveLength(db.majors.find((x) => x.id === 'CS-BS')!.requiredCourses.length); + expect(completedRequiredReport(db, MARIA).sections[0].rows.some((r) => r[2] === 'Completed')).toBe(true); + const status = outlineStatusReport(db, MARIA); + expect(status.sections[0].rows).toHaveLength(db.outlines.find((o) => o.studentId === MARIA)!.entries.length); + expect(outlineHistoryReport(db, MARIA).sections[0].rows.length).toBeGreaterThan(0); + }); + + it('student record report honours course detail and this-university-only scope, and shows GPA', () => { + expect(sectionIds(studentRecordReport(db, MARIA, { detail: true, scope: 'all' }))).toEqual(['info', 'here', 'transfer', 'current', 'notes']); + expect(sectionIds(studentRecordReport(db, MARIA, { detail: true, scope: 'here' }))).toEqual(['info', 'here', 'current', 'notes']); + expect(sectionIds(studentRecordReport(db, MARIA, { detail: false, scope: 'all' }))).toEqual(['info', 'notes']); + expect(studentRecordReport(db, MARIA, { detail: false, scope: 'all' }).meta.find(([k]) => k === 'Overall GPA')![1]).toMatch(/^\d\.\d\d$/); + }); + + it('authorized user report never includes passwords and filters by subsystem', () => { + const r = authorizedUsersReport(db, 'GRADE'); + expect(r.sections[0].columns.join(' ')).not.toMatch(/password/i); + expect(r.sections[0].rows.every((row) => String(row[3]).includes('GRADE'))).toBe(true); + }); + + it('offers department and major choices for the viewer', () => { + expect(departmentChoices(db, 'All')[0]).toEqual(['', 'All']); + expect(majorChoices(db, 'MATH-MIN')[0][0]).toBe('MATH-MIN'); + }); +}); diff --git a/src/lib/reports.ts b/src/lib/reports.ts new file mode 100644 index 0000000..fba3025 --- /dev/null +++ b/src/lib/reports.ts @@ -0,0 +1,252 @@ +import type { Db, Offering, Student, Subsystem } from '../data/types'; +import { completedCourseIds, courseOf, currentRegistrations, gpa, gradeStats, isPassing, letterFor, offeringOf, seatsOpen } from './rules'; +import { formatDate, formatDateTime, formatTimeRange } from './format'; +import { fullName } from './names'; +import { classLevel } from './classLevel'; + +/** + * The SignMeUp reports (GEN-18 and the report requirements of each subsystem). Each builder turns + * the document into titled sections of rows; the report viewer previews them on screen and prints + * all of them or only the sections the user keeps (reports "as a whole or in parts"). + */ +export type Cell = string | number; +export interface ReportSection { id: string; title: string; note?: string; columns: string[]; numeric?: number[]; rows: Cell[][]; summary?: [string, string][]; empty?: string; } +export interface Report { title: string; subtitle: string; meta: [string, string][]; sections: ReportSection[]; } + +const deptName = (db: Db, id: string) => db.departments.find((d) => d.id === id)?.name ?? id; +const facultyName = (db: Db, id: string) => db.faculty.find((f) => f.id === id)?.name ?? '—'; +const levelLabel = (l: string) => (l === 'upper' ? 'Upper division' : l === 'graduate' ? 'Graduate' : 'Lower division'); +const when = (o: Offering) => `${o.days} ${formatTimeRange(o.start, o.end)}`; +const pct = (n: number, of: number) => (of ? `${Math.round((n / of) * 100)}%` : '—'); +/** First sentence of a description, trimmed: the "short description" reports ask for. */ +export function shortDescription(text: string, max = 90): string { + const first = text.split(/(?<=\.)\s/)[0] ?? text; + return first.length > max ? `${first.slice(0, max - 1).trimEnd()}…` : first; +} +const currentOfferings = (db: Db) => db.offerings.filter((o) => o.term === db.term); +const departmentsWith = (db: Db, ids: Iterable) => { const set = new Set(ids); return db.departments.filter((d) => set.has(d.id)); }; + +// ------------------------------------------------------------------ GRADE: course, department and university statistics +const STATS_COLUMNS = ['Course', 'Section', 'Instructor', 'Registered', 'Passing', 'Average', 'A', 'B', 'C', 'D', 'F']; +function statsRow(label: string, section: string, instructor: string, regs: Db['registrations']): Cell[] { + const s = gradeStats(regs); + const graded = Object.values(s.distribution).reduce((a, b) => a + b, 0); + return [label, section, instructor, s.registered, `${s.passing} · ${pct(s.passing, s.registered)}`, s.average === null ? '—' : `${s.average.toFixed(2)} ${letterFor(s.average)}`, + ...(['A', 'B', 'C', 'D', 'F'] as const).map((g) => pct(s.distribution[g], graded))]; +} + +/** Course, department and university grade statistics for the current term (GRADE reports). */ +export function gradeStatisticsReport(db: Db, deptId: string | null): Report { + const offerings = currentOfferings(db); + const regsOf = (os: Offering[]) => { const nos = new Set(os.map((o) => o.scheduleNo)); return db.registrations.filter((r) => nos.has(r.scheduleNo)); }; + const byDept = departmentsWith(db, offerings.map((o) => courseOf(db, o.courseId)?.deptId ?? '')).filter((d) => !deptId || d.id === deptId); + const sections: ReportSection[] = byDept.map((d) => { + const os = offerings.filter((o) => courseOf(db, o.courseId)?.deptId === d.id).sort((a, b) => a.courseId.localeCompare(b.courseId)); + return { + id: `dept-${d.id}`, title: `${d.name} · course statistics`, columns: STATS_COLUMNS, numeric: [3], + rows: [...os.map((o) => statsRow(o.courseId, o.scheduleNo, facultyName(db, o.instructorId), regsOf([o]))), statsRow(`${d.name} total`, `${os.length} sections`, '', regsOf(os))], + }; + }); + if (!deptId) sections.push({ id: 'university', title: 'University statistics', columns: STATS_COLUMNS, numeric: [3], rows: [statsRow('All courses', `${offerings.length} sections`, '', regsOf(offerings))] }); + return { + title: deptId ? `Department grade statistics · ${deptName(db, deptId)}` : 'University grade statistics', + subtitle: `${db.term} · number registered, completing with a passing grade, average grade, and the share of A, B, C, D and F grades`, + meta: [['Term', db.term], ['Scope', deptId ? deptName(db, deptId) : 'All departments']], + sections, + }; +} + +// ------------------------------------------------------------------ FCI: faculty and course lists +/** Faculty list with a short description, for one department or the whole university by department (FCI-07, FCI-08). */ +export function facultyListReport(db: Db, deptId: string | null): Report { + const depts = deptId ? db.departments.filter((d) => d.id === deptId) : departmentsWith(db, db.faculty.map((f) => f.deptId)); + return { + title: deptId ? `Faculty · ${deptName(db, deptId)}` : 'Faculty · university, by department', + subtitle: 'Faculty members with position, office, contact and the courses each is authorized to teach', + meta: [['Scope', deptId ? deptName(db, deptId) : 'All departments'], ['Faculty', String(db.faculty.filter((f) => !deptId || f.deptId === deptId).length)]], + sections: depts.map((d) => ({ + id: `fac-${d.id}`, title: d.name, columns: ['ID', 'Name', 'Position', 'Office · phone', 'Office hours', 'Authorized to teach'], + rows: db.faculty.filter((f) => f.deptId === d.id).sort((a, b) => a.name.localeCompare(b.name)).map((f) => [ + f.id, f.name, f.positionTitle, `${f.office} · ${f.officePhone}`, f.officeHours, + db.courses.filter((c) => c.qualifiedFaculty.includes(f.id)).map((c) => c.id).join(', ') || 'None', + ]), + empty: 'No faculty assigned to this department.', + })), + }; +} + +/** Course list with a short description, for one department or the whole university by department (FCI-09, FCI-10). */ +export function courseListReport(db: Db, deptId: string | null): Report { + const depts = deptId ? db.departments.filter((d) => d.id === deptId) : departmentsWith(db, db.courses.map((c) => c.deptId)); + return { + title: deptId ? `Courses · ${deptName(db, deptId)}` : 'Courses · university, by department', + subtitle: 'Catalog courses with units, level, prerequisites and a short description', + meta: [['Scope', deptId ? deptName(db, deptId) : 'All departments'], ['Courses', String(db.courses.filter((c) => !deptId || c.deptId === deptId).length)]], + sections: depts.map((d) => ({ + id: `crs-${d.id}`, title: d.name, columns: ['Course', 'Title', 'Units', 'Level', 'Prerequisites', 'Description'], numeric: [2], + rows: db.courses.filter((c) => c.deptId === d.id).sort((a, b) => a.id.localeCompare(b.id)).map((c) => [c.id, c.title, c.units, levelLabel(c.level), c.prereqs.join(', ') || 'None', shortDescription(c.description)]), + empty: 'No courses in this department.', + })), + }; +} + +// ------------------------------------------------------------------ REG: schedule reports +/** A student's schedule, listing and briefly describing every currently enrolled course (REG-10). */ +export function studentScheduleReport(db: Db, studentId: string): Report { + const s = db.students.find((x) => x.id === studentId); + const regs = currentRegistrations(db, studentId); + const rows = regs.map((r) => { const o = offeringOf(db, r.scheduleNo)!; const c = courseOf(db, o.courseId)!; return [c.id, o.scheduleNo, c.title, shortDescription(c.description, 70), when(o), o.location, facultyName(db, o.instructorId), c.units, r.type === 'letter' ? 'Letter' : r.type === 'crnc' ? 'CR/NC' : 'Audit'] as Cell[]; }); + const units = regs.reduce((n, r) => n + (courseOf(db, offeringOf(db, r.scheduleNo)?.courseId ?? '')?.units ?? 0), 0); + return { + title: `Student schedule · ${s ? fullName(s) : studentId}`, subtitle: `${db.term} · all currently enrolled courses`, + meta: [['Student ID', studentId], ['Term', db.term], ['Courses', String(regs.length)], ['Units', String(units)]], + sections: [{ id: 'schedule', title: 'Enrolled courses', columns: ['Course', 'Schedule #', 'Title', 'Description', 'Days / time', 'Location', 'Instructor', 'Units', 'Type'], numeric: [7], rows, summary: [['Total units', String(units)]], empty: 'Not registered for any course this term.' }], + }; +} + +const OFFERING_COLUMNS = ['Course', 'Schedule #', 'Title', 'Days / time', 'Location', 'Instructor', 'Units', 'Prerequisites', 'Seats open']; +const offeringRow = (db: Db, o: Offering): Cell[] => { const c = courseOf(db, o.courseId)!; return [c.id, o.scheduleNo, c.title, when(o), o.location, facultyName(db, o.instructorId), c.units, c.prereqs.join(', ') || 'None', `${seatsOpen(db, o)} of ${o.capacity}`]; }; + +/** Courses offered this term by a specified department (REG-11). */ +export function departmentOfferingsReport(db: Db, deptId: string): Report { + const os = currentOfferings(db).filter((o) => courseOf(db, o.courseId)?.deptId === deptId).sort((a, b) => a.courseId.localeCompare(b.courseId) || a.scheduleNo.localeCompare(b.scheduleNo)); + return { + title: `Courses offered · ${deptName(db, deptId)}`, subtitle: `${db.term} · every scheduled section in the department`, + meta: [['Department', deptName(db, deptId)], ['Term', db.term], ['Sections', String(os.length)]], + sections: [{ id: 'offered', title: deptName(db, deptId), columns: OFFERING_COLUMNS, numeric: [6], rows: os.map((o) => offeringRow(db, o)), empty: 'No sections scheduled this term.' }], + }; +} + +/** Courses with seats currently available, for one department or all departments (REG-12). */ +export function seatsAvailableReport(db: Db, deptId: string | null): Report { + const open = currentOfferings(db).filter((o) => seatsOpen(db, o) > 0 && (!deptId || courseOf(db, o.courseId)?.deptId === deptId)); + const depts = departmentsWith(db, open.map((o) => courseOf(db, o.courseId)?.deptId ?? '')); + return { + title: deptId ? `Seats available · ${deptName(db, deptId)}` : 'Seats available · all departments', subtitle: `${db.term} · sections with at least one open seat`, + meta: [['Scope', deptId ? deptName(db, deptId) : 'All departments'], ['Term', db.term], ['Open sections', String(open.length)]], + sections: depts.length ? depts.map((d) => ({ id: `open-${d.id}`, title: d.name, columns: OFFERING_COLUMNS, numeric: [6], rows: open.filter((o) => courseOf(db, o.courseId)?.deptId === d.id).sort((a, b) => a.courseId.localeCompare(b.courseId)).map((o) => offeringRow(db, o)) })) + : [{ id: 'open', title: 'Open sections', columns: OFFERING_COLUMNS, rows: [], empty: 'No sections have open seats.' }], + }; +} + +// ------------------------------------------------------------------ MAJOR reports +/** All required courses (and electives) for a specific major; available to all users (MAJ-08). */ +export function majorRequirementsReport(db: Db, majorId: string): Report { + const m = db.majors.find((x) => x.id === majorId); + if (!m) return { title: 'Major requirements', subtitle: '', meta: [], sections: [] }; + const row = (id: string): Cell[] => { const c = courseOf(db, id); return [id, c?.title ?? '—', c?.units ?? '—', c?.prereqs.join(', ') || 'None']; }; + const units = m.requiredCourses.reduce((n, id) => n + (courseOf(db, id)?.units ?? 0), 0); + return { + title: `Major requirements · ${m.title}`, subtitle: `${m.id} · ${deptName(db, m.deptId)} Department`, + meta: [['Major ID', m.id], ['Department', deptName(db, m.deptId)], ['Units required', `${m.unitsRequired} (${m.majorUnits} in the major)`], ['Advisors', m.advisors.map((id) => db.users.find((u) => u.id === id)?.name ?? id).join(', ') || '—']], + sections: [ + { id: 'required', title: 'Required courses', columns: ['Course', 'Title', 'Units', 'Prerequisites'], numeric: [2], rows: m.requiredCourses.map(row), summary: [['Required units', String(units)]], empty: 'No required courses.' }, + { id: 'electives', title: 'Electives within the major', columns: ['Course', 'Title', 'Units', 'Prerequisites'], numeric: [2], rows: m.electives.map(row), empty: 'No electives listed.' }, + ], + }; +} + +function completion(db: Db, s: Student, courseId: string): { done: boolean; where: string; term: string; grade: string } { + const here = s.completed.find((c) => c.courseId === courseId && isPassing(c.grade)); + if (here) return { done: true, where: 'This university', term: here.term, grade: here.grade }; + const t = s.transfer.find((c) => c.equivalentCourseId === courseId && isPassing(c.grade)); + if (t) return { done: true, where: `Transfer · ${t.university}`, term: t.term, grade: t.grade }; + const now = currentRegistrations(db, s.id).some((r) => offeringOf(db, r.scheduleNo)?.courseId === courseId); + return { done: false, where: now ? `In progress · ${db.term}` : 'Not completed', term: '—', grade: '—' }; +} + +/** Completed required courses for one student (MAJ-09; major advisors and that student only). */ +export function completedRequiredReport(db: Db, studentId: string): Report { + const s = db.students.find((x) => x.id === studentId); + const outline = db.outlines.find((o) => o.studentId === studentId); + const m = db.majors.find((x) => x.id === (outline?.majorId ?? s?.majorId)); + if (!s || !m) return { title: 'Completed required courses', subtitle: 'No major on file for this student.', meta: [], sections: [] }; + const rows = m.requiredCourses.map((id) => { const c = completion(db, s, id); return [id, courseOf(db, id)?.title ?? '—', c.done ? 'Completed' : c.where, c.done ? c.where : '', c.term, c.grade] as Cell[]; }); + const done = rows.filter((r) => r[2] === 'Completed').length; + return { + title: `Completed required courses · ${fullName(s)}`, subtitle: `${m.title} · ${done} of ${m.requiredCourses.length} required courses completed`, + meta: [['Student ID', s.id], ['Major', `${m.id} · ${m.title}`], ['Completed', `${done} of ${m.requiredCourses.length}`]], + sections: [{ id: 'required', title: 'Required courses', columns: ['Course', 'Title', 'Status', 'Where', 'Semester', 'Grade'], rows }], + }; +} + +/** Student status against the approved major outline (MAJ-10; major advisors and that student only). */ +export function outlineStatusReport(db: Db, studentId: string): Report { + const s = db.students.find((x) => x.id === studentId); + const outline = db.outlines.find((o) => o.studentId === studentId); + const m = db.majors.find((x) => x.id === outline?.majorId); + if (!s || !outline || !m) return { title: 'Status against approved outline', subtitle: 'No approved outline on file for this student.', meta: [], sections: [] }; + const done = completedCourseIds(s); + const rows = outline.entries.map((e) => { const c = completion(db, s, e.courseId); return [e.courseId, courseOf(db, e.courseId)?.title ?? '—', e.status[0].toUpperCase() + e.status.slice(1), formatDate(e.statusDate), e.status !== 'approved' ? '—' : done.has(e.courseId) ? `Completed ${c.term} · ${c.grade}` : c.where] as Cell[]; }); + const approved = outline.entries.filter((e) => e.status === 'approved'); + const completedCount = approved.filter((e) => done.has(e.courseId)).length; + return { + title: `Status against approved outline · ${fullName(s)}`, subtitle: `${m.title} · last approved ${formatDate(outline.approvedAt)} by ${outline.approvedBy}`, + meta: [['Student ID', s.id], ['Major', `${m.id} · ${m.title}`], ['Approved by', `${outline.approvedBy}, ${formatDate(outline.approvedAt)}`], ['Approved courses completed', `${completedCount} of ${approved.length}`]], + sections: [{ id: 'outline', title: 'Outline entries', columns: ['Course', 'Title', 'Outline status', 'Status date', 'Progress'], rows, summary: [['Approved', String(approved.length)], ['Completed', String(completedCount)], ['Remaining', String(approved.length - completedCount)]] }], + }; +} + +/** History of changes to a specific major outline (MAJOR reports; major advisors and that student only). */ +export function outlineHistoryReport(db: Db, studentId: string): Report { + const s = db.students.find((x) => x.id === studentId); + const outline = db.outlines.find((o) => o.studentId === studentId); + if (!s || !outline) return { title: 'Outline change history', subtitle: 'No approved outline on file for this student.', meta: [], sections: [] }; + return { + title: `Outline change history · ${fullName(s)}`, subtitle: 'Every change to the approved outline, oldest first; entries are never deleted', + meta: [['Student ID', s.id], ['Major', outline.majorId], ['Changes', String(outline.history.length)]], + sections: [{ id: 'history', title: 'Changes', columns: ['Date and time', 'Change', 'By'], rows: [...outline.history].sort((a, b) => a.at.localeCompare(b.at)).map((h) => [formatDateTime(h.at), h.action, h.by]), empty: 'No changes recorded.' }], + }; +} + +// ------------------------------------------------------------------ ER: student record report +/** The student record report: all student information, optional course detail, this university or all, and GPA (ER-05, ER-06, ER-07). */ +export function studentRecordReport(db: Db, studentId: string, opts: { detail: boolean; scope: 'here' | 'all' }): Report { + const s = db.students.find((x) => x.id === studentId); + if (!s) return { title: 'Student record', subtitle: 'Student not found.', meta: [], sections: [] }; + const major = db.majors.find((m) => m.id === s.majorId); + const minor = db.majors.find((m) => m.id === s.minorId); + const g = gpa(s); + const unitsHere = s.completed.reduce((n, c) => n + c.units, 0); + const unitsTransfer = s.transfer.reduce((n, c) => n + c.units, 0); + const sections: ReportSection[] = [{ + id: 'info', title: 'Student information', columns: ['Field', 'Value'], + rows: [['Student ID', s.id], ['Name', fullName(s)], ['Telephone', s.phone || '—'], ['Address', s.address || '—'], ['Date of birth', formatDate(s.dateOfBirth)], ['Major', major?.title ?? s.majorId], ['Minor', minor?.title ?? 'None'], + ['Class level', classLevel(s)], ['Graduate program', s.graduate ? 'Accepted' : 'No'], ['Standing', s.standing], ['Overall GPA (this university)', g === null ? '—' : g.toFixed(2)], + ['Units completed', opts.scope === 'all' ? `${unitsHere + unitsTransfer} (${unitsHere} here, ${unitsTransfer} transfer)` : `${unitsHere} at this university`]], + }]; + if (opts.detail) { + sections.push({ id: 'here', title: 'Courses completed at this university', columns: ['Course', 'Title', 'Semester', 'Units', 'Grade'], numeric: [3], rows: s.completed.map((c) => [c.courseId, c.title, c.term, c.units, c.grade]), summary: [['Units', String(unitsHere)], ['GPA', g === null ? '—' : g.toFixed(2)]], empty: 'None on file.' }); + if (opts.scope === 'all') sections.push({ id: 'transfer', title: 'Courses completed at other universities', columns: ['Course', 'Title', 'University', 'Location', 'Equivalent here', 'Semester', 'Units', 'Grade'], numeric: [6], rows: s.transfer.map((c) => [c.courseId, c.title, c.university, c.location, c.equivalentCourseId || '—', c.term, c.units, c.grade]), summary: [['Units', String(unitsTransfer)]], empty: 'None on file.' }); + sections.push({ id: 'current', title: `Currently enrolled · ${db.term}`, columns: ['Course', 'Title', 'Days / time', 'Units', 'Type'], numeric: [3], rows: currentRegistrations(db, s.id).map((r) => { const o = offeringOf(db, r.scheduleNo)!; const c = courseOf(db, o.courseId)!; return [c.id, c.title, when(o), c.units, r.type === 'letter' ? 'Letter' : r.type === 'crnc' ? 'CR/NC' : 'Audit']; }), empty: 'Not enrolled this term.' }); + } + sections.push({ id: 'notes', title: 'Notes', columns: ['Date and time', 'Category', 'Employee', 'Note'], rows: [...s.notes].sort((a, b) => a.at.localeCompare(b.at)).map((n) => [formatDateTime(n.at), n.category, n.byEmployeeId, n.text]), empty: 'No notes on file.' }); + return { + title: `Student record · ${fullName(s)}`, subtitle: `${opts.scope === 'all' ? 'All courses at all universities' : 'Courses at this university only'}${opts.detail ? ' · with course detail' : ''}`, + meta: [['Student ID', s.id], ['Overall GPA', g === null ? '—' : g.toFixed(2)], ['Major', major?.title ?? s.majorId]], + sections, + }; +} + +// ------------------------------------------------------------------ Framework: authorized users +/** Authorized users for the whole system or one subsystem, without passwords (FW-06). */ +export function authorizedUsersReport(db: Db, area: Subsystem | null): Report { + const users = db.users.filter((u) => !area || u.access.includes(area)).sort((a, b) => a.name.localeCompare(b.name)); + return { + title: area ? `Authorized users · ${area}` : 'Authorized users · whole system', subtitle: 'User name, employee number, job title and access areas. Passwords are never included.', + meta: [['Scope', area ? `${area} subsystem` : 'Whole system'], ['Users', String(users.length)]], + sections: [{ id: 'users', title: 'Users', columns: ['Name', 'Employee #', 'Job title', 'Access areas'], rows: users.map((u) => [u.name, u.id, u.jobTitle, u.access.join(', ')]) }], + }; +} + +// ------------------------------------------------------------------ choices for the report viewer +/** Department choices; with `allLabel`, an empty value for "every department" comes first. */ +export function departmentChoices(db: Db, allLabel?: string): [string, string][] { + const depts = db.departments.filter((d) => d.id !== 'UNIV' || db.courses.some((c) => c.deptId === 'UNIV')).map((d): [string, string] => [d.id, d.name]); + return allLabel ? [['', allLabel], ...depts] : depts; +} +/** Major and minor choices, with `firstId` (e.g. the student's own major) first. */ +export function majorChoices(db: Db, firstId?: string): [string, string][] { + const all = db.majors.map((m): [string, string] => [m.id, `${m.title} (${m.id})`]); + return firstId ? [...all.filter(([id]) => id === firstId), ...all.filter(([id]) => id !== firstId)] : all; +} diff --git a/src/screens/AuthorizedUsers.tsx b/src/screens/AuthorizedUsers.tsx index 92521d0..43e66a1 100644 --- a/src/screens/AuthorizedUsers.tsx +++ b/src/screens/AuthorizedUsers.tsx @@ -5,6 +5,8 @@ import { Shell, PageHeader, useToast } from '../components/Shell'; import { Banner, Chip, Empty, Stamp } from '../components/ui'; import { Plus, Search, X } from '../components/icons'; import { useProgressive } from '../components/progressive'; +import { ReportsButton } from '../components/Reports'; +import { authorizedUsersReport } from '../lib/reports'; import { formatDateTime } from '../lib/format'; import { wildcardMatch } from '../lib/wildcard'; import { ALLOWED_DOMAINS, STUDENT_ACCESS } from '../lib/auth'; @@ -23,7 +25,6 @@ export default function AuthorizedUsers() { const toast = useToast(); const [q, setQ] = useState(''); const [area, setArea] = useState(''); - const [scope, setScope] = useState<'all' | Subsystem>('all'); const [mode, setMode] = useState<{ kind: 'edit'; id: string } | { kind: 'add' } | null>(null); const users = useMemo(() => db.users.filter((u) => (!area || u.access.includes(area as Subsystem)) && (wildcardMatch(q, u.name) || wildcardMatch(q, u.id) || wildcardMatch(q, u.email))), [db.users, q, area]); @@ -50,9 +51,9 @@ export default function AuthorizedUsers() { return ( - {db.users.length} users · passwords are kept by the sign-in service and are never stored, shown or printed here{scope !== 'all' ? ` · report: ${scope} only` : ''}}> + {db.users.length} users · passwords are kept by the sign-in service and are never stored, shown or printed here}> - + [a, `${a} subsystem`])] }], build: (v) => authorizedUsersReport(db, (v.area || null) as Subsystem | null) }]} /> @@ -66,8 +67,7 @@ export default function AuthorizedUsers() {
Name · emailEmp / student #Job titleAccess areas
{users.length === 0 && No users match.} {page.visible.map((u) => ( - // The printed report covers the whole system or one subsystem (FW report); rows outside the chosen scope are left off the printout. -
+
{u.name}
{u.email} · {u.lastSignIn ? `last sign-in ${formatDateTime(u.lastSignIn)}` : 'never signed in'}
{u.id}{u.role === 'student' && <>
Student}
{u.jobTitle} @@ -77,11 +77,7 @@ export default function AuthorizedUsers() { ))} {page.more}
-
- Showing {users.length} of {db.users.length} - Report scope: - -
+
{users.length} of {db.users.length} users match · Print user report covers the whole system or one subsystem
); diff --git a/src/screens/CourseSearch.tsx b/src/screens/CourseSearch.tsx index 6df8178..8b47433 100644 --- a/src/screens/CourseSearch.tsx +++ b/src/screens/CourseSearch.tsx @@ -9,6 +9,8 @@ import { formatDate, formatTimeRange, shortName } from '../lib/format'; import { wildcardMatch } from '../lib/wildcard'; import { useEscapeToCancel } from '../components/draft'; import { useProgressive } from '../components/progressive'; +import { ReportsButton } from '../components/Reports'; +import { departmentChoices, departmentOfferingsReport, seatsAvailableReport, studentScheduleReport } from '../lib/reports'; const COLS = '84px 1fr 44px 130px 112px 92px'; // seats fits "3 seats left" and "120 of 120" chips, which never wrap @@ -93,7 +95,13 @@ export default function CourseSearch() { return ( - {db.term}Registration open until {formatDate(db.registrationCloses)}} /> + {db.term}Registration open until {formatDate(db.registrationCloses)}}> + studentScheduleReport(db, student.id) }] : []), + { id: 'offered', label: 'Courses offered by a department', params: [{ key: 'dept', label: 'Department', options: dept ? [...departmentChoices(db).filter(([id]) => id === dept), ...departmentChoices(db).filter(([id]) => id !== dept)] : departmentChoices(db) }], build: (v) => departmentOfferingsReport(db, v.dept) }, + { id: 'seats', label: 'Courses with seats available', params: [{ key: 'dept', label: 'Department', options: departmentChoices(db, 'All departments') }], build: (v) => seatsAvailableReport(db, v.dept || null) }, + ]} /> +
diff --git a/src/screens/Dashboard.tsx b/src/screens/Dashboard.tsx index 0b11ee3..89dd018 100644 --- a/src/screens/Dashboard.tsx +++ b/src/screens/Dashboard.tsx @@ -3,6 +3,8 @@ import { useStore } from '../data/store'; import { Shell, PageHeader, Dot, useToast } from '../components/Shell'; import { Banner, Chip, Empty, PrereqChip, SeatsChip, Stamp, StatusChip } from '../components/ui'; import { keyInfoBlock } from '../lib/student'; +import { ReportsButton } from '../components/Reports'; +import { studentScheduleReport } from '../lib/reports'; import { X } from '../components/icons'; import { courseOf, currentRegistrations, eligibleMajorOfferings, MAX_UNITS, offeringOf, seatsOpen, unitsRegistered } from '../lib/rules'; import { formatDate, formatTimeRange, shortName } from '../lib/format'; @@ -35,6 +37,7 @@ export default function Dashboard() { title={`Welcome back, ${student.firstName} ${student.lastName}`} meta={<>ID {student.id}{major?.title}{db.term}} > + studentScheduleReport(db, student.id) }]} /> Search courses diff --git a/src/screens/FacultyCourses.tsx b/src/screens/FacultyCourses.tsx index 28ed1dd..9412e9c 100644 --- a/src/screens/FacultyCourses.tsx +++ b/src/screens/FacultyCourses.tsx @@ -5,6 +5,8 @@ import { Banner, Empty } from '../components/ui'; import { Print, Search, X } from '../components/icons'; import { useEscapeToCancel, useWarnBeforeLeaving } from '../components/draft'; import { useProgressive } from '../components/progressive'; +import { ReportsButton } from '../components/Reports'; +import { courseListReport, departmentChoices, facultyListReport, majorChoices, majorRequirementsReport } from '../lib/reports'; import type { Course, Db, Faculty } from '../data/types'; import { canMaintainCatalog, type CourseField, type CourseIssue } from '../lib/catalog'; import type { FacultyEntry, FacultyField, FacultyIssue } from '../lib/faculty'; @@ -50,7 +52,11 @@ export default function FacultyCourses() { Query by faculty ID, faculty name, course ID or course title · use * as a wildcard}> {canMaintain && } {canMaintain && } - + facultyListReport(db, v.dept || null) }, + { id: 'courses', label: 'Course list', params: [{ key: 'dept', label: 'Department', options: departmentChoices(db, 'University, by department') }], build: (v) => courseListReport(db, v.dept || null) }, + { id: 'major', label: 'Required courses for a major', params: [{ key: 'major', label: 'Major', options: majorChoices(db) }], build: (v) => majorRequirementsReport(db, v.major) }, + ]} />
diff --git a/src/screens/GradeEntry.tsx b/src/screens/GradeEntry.tsx index 3b92a13..82cc9d2 100644 --- a/src/screens/GradeEntry.tsx +++ b/src/screens/GradeEntry.tsx @@ -10,6 +10,8 @@ import { fillerName } from '../data/seed'; import { wildcardMatch } from '../lib/wildcard'; import { useEscapeToCancel, useWarnBeforeLeaving } from '../components/draft'; import { useProgressive } from '../components/progressive'; +import { ReportsButton } from '../components/Reports'; +import { departmentChoices, gradeStatisticsReport } from '../lib/reports'; const COLS = '1.1fr 90px 90px 110px 1.7fr'; @@ -88,6 +90,7 @@ export default function GradeEntry() { {mine.map((o) => )} )} + d.id === course.deptId)?.name} Department`], ['', 'University (all departments)'], ...departmentChoices(db).filter(([id]) => id !== course.deptId).map(([id, name]): [string, string] => [id, `${name} Department`])] }], build: (v) => gradeStatisticsReport(db, v.dept || null) }]} /> diff --git a/src/screens/MajorOutline.tsx b/src/screens/MajorOutline.tsx index 2830df0..73d8d2d 100644 --- a/src/screens/MajorOutline.tsx +++ b/src/screens/MajorOutline.tsx @@ -9,6 +9,8 @@ import { completedCourseIds, courseOf, currentRegistrations, offeringOf } from ' import { formatDate, formatDateTime, shortName } from '../lib/format'; import { useEscapeToCancel } from '../components/draft'; import { keyInfoBlock } from '../lib/student'; +import { ReportsButton } from '../components/Reports'; +import { completedRequiredReport, majorChoices, majorRequirementsReport, outlineHistoryReport, outlineStatusReport } from '../lib/reports'; const COLS_EDIT = '84px 1fr 100px 100px 140px 120px'; const COLS_VIEW = '84px 1fr 100px 100px 140px'; @@ -70,6 +72,13 @@ export default function MajorOutline() { {db.students.map((s) => )} )} + {/* MAJOR reports: required courses for any major (all users); the other three are limited to this student and their advisors by the screen itself */} + outlineStatusReport(db, student.id) }, + { id: 'completed', label: 'Completed required courses', build: () => completedRequiredReport(db, student.id) }, + { id: 'history', label: 'Outline change history', build: () => outlineHistoryReport(db, student.id) }, + { id: 'major', label: 'Required courses for a major', params: [{ key: 'major', label: 'Major', options: majorChoices(db, major.id) }], build: (v) => majorRequirementsReport(db, v.major) }, + ]} /> {canEdit && (
setDetail(e.target.checked)} />Include course detail - - -
diff --git a/src/styles/global.css b/src/styles/global.css index dc7baca..206ab9f 100644 --- a/src/styles/global.css +++ b/src/styles/global.css @@ -199,9 +199,47 @@ textarea.input { height: auto; min-height: 72px; padding: 10px 12px; resize: ver .login { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; } .login .card { padding: 28px; gap: 18px; } +/* Report viewer: an on-screen preview of the printed report (GEN-18) */ +.report-overlay { position: fixed; inset: 0; z-index: 50; background: var(--bg); display: flex; flex-direction: column; overflow-y: auto; } +.report-toolbar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: flex-end; gap: 12px 20px; padding: 14px 24px; background: var(--surface); border-bottom: 1px solid var(--border); } +.report-controls { display: flex; flex-wrap: wrap; gap: 12px; } +.report-controls .field { min-width: 200px; } +.report-parts { display: flex; flex-direction: column; gap: 6px; flex: 1; min-width: 240px; } +.report-actions { display: flex; gap: 8px; margin-left: auto; } +.report-doc { width: 100%; max-width: 1040px; margin: 24px auto 48px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: 0 1px 2px rgba(15, 23, 42, 0.05); padding: 36px 40px; display: flex; flex-direction: column; gap: 28px; } +.report-head { display: flex; flex-direction: column; gap: 8px; border-bottom: 2px solid var(--text); padding-bottom: 18px; } +.report-brand { font-size: 11px; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); } +.report-head h1 { font-size: 24px; } +.report-meta, .report-summary { display: flex; flex-wrap: wrap; gap: 8px 28px; margin: 6px 0 0; font-size: 13px; } +.report-meta dt, .report-summary dt { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; } +.report-meta dd, .report-summary dd { margin: 2px 0 0; font-weight: 500; } +.report-summary { margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border); } +.report-section { display: flex; flex-direction: column; gap: 10px; break-inside: avoid-page; } +.report-section h2 { font-size: 15px; } +.report-table-wrap { overflow-x: auto; } +.report-table { width: 100%; border-collapse: collapse; font-size: 12.5px; } +.report-table th { text-align: left; font-weight: 600; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; padding: 8px 10px; border-bottom: 1px solid var(--border); background: var(--bg); } +.report-table td { padding: 8px 10px; border-bottom: 1px solid var(--row-border); vertical-align: top; } +.report-table .num { text-align: right; font-variant-numeric: tabular-nums; } +.report-table tbody tr:last-child td { border-bottom: 0; } +.report-foot { color: var(--muted); font-size: 11px; border-top: 1px solid var(--border); padding-top: 10px; text-align: center; } +body.report-open { overflow: hidden; } +@media (max-width: 640px) { + .report-toolbar { position: static; padding: 12px 16px; } /* on a phone the controls scroll away with the report */ + .report-parts .cluster { flex-direction: column; align-items: flex-start; } + .report-controls, .report-controls .field { width: 100%; min-width: 0; } + .report-doc { margin: 12px auto 24px; padding: 20px 16px; border-radius: 0; border-left: 0; border-right: 0; } +} + /* Print: any display can be printed, with all header information */ @media print { .nav, .actions, .panel, .foot, .no-print { display: none !important; } + body.report-open #root, .report-toolbar { display: none !important; } + body.report-open { overflow: visible; } + .report-overlay { position: static; overflow: visible; background: #fff; } + .report-doc { max-width: none; margin: 0; padding: 0; border: 0; box-shadow: none; } + .report-table-wrap { overflow: visible; } + .report-table th { background: none; } .main, .main.narrow { padding: 0; } .card { box-shadow: none; break-inside: avoid; } body { background: #fff; } From 090c1f31224a27076bbb3959fbbb64eb7d54ca8a Mon Sep 17 00:00:00 2001 From: Miguel Reese Date: Tue, 27 Oct 2026 22:33:55 -0700 Subject: [PATCH 2/4] Add editors for value lists, validation parameters and help screens Authorized Users now has three tabs for system administrators: Users, Value lists and Help screens. Value lists (GEN-11, GEN-12): src/lib/parameters.ts defines the user-maintained parameters and lists. Registration's maximum units per term and the grade list for grade entry and course history are now read from there instead of being fixed in code. Lists for semesters, universities, buildings, faculty positions and job titles back their entry fields. The database-fixed lists (note categories, registration types, outline statuses) are shown read-only. Edits are drafts with Save and Cancel and restore, validated with a reason and a requirement, and logged. Key sequence (GEN-12): in any field tied to a list, typing suggests values, and F4 or Alt+Down opens the full list (filtered by what is typed) to pick from with the arrow keys and Enter. Help screens: administrators can edit each screen's title, summary and field notes, or restore the built-in text. The Help window links admins to the editor. Fixes a bug where the copy of the help text saved when the shared database was first seeded overrode every later improvement: built-in help is now the default, and only topics an administrator edited (stamped with who and when) override it. Older unstamped rows are ignored. The default grade list now includes A+. Co-Authored-By: Claude Opus 5.5 --- api/_lib/mapping.ts | 8 +- src/components/Settings.tsx | 152 +++++++++++++++++++++++++++++ src/components/Shell.tsx | 9 +- src/components/ValueListPicker.tsx | 57 +++++++++++ src/components/help.ts | 2 +- src/data/seed.ts | 5 +- src/data/store.tsx | 31 +++++- src/data/types.ts | 5 +- src/lib/courseHistory.ts | 7 +- src/lib/mapping.test.ts | 7 ++ src/lib/parameters.test.ts | 47 +++++++++ src/lib/parameters.ts | 67 +++++++++++++ src/lib/rules.ts | 9 +- src/screens/AuthorizedUsers.tsx | 24 ++++- src/screens/CourseSearch.tsx | 5 +- src/screens/Dashboard.tsx | 5 +- src/screens/FacultyCourses.tsx | 6 +- src/screens/GradeEntry.tsx | 5 +- src/screens/StudentRecord.tsx | 9 +- src/styles/global.css | 26 +++++ 20 files changed, 450 insertions(+), 36 deletions(-) create mode 100644 src/components/Settings.tsx create mode 100644 src/components/ValueListPicker.tsx create mode 100644 src/lib/parameters.test.ts create mode 100644 src/lib/parameters.ts 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/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 })} />
+