diff --git a/docs/decisions/TIG-337-compare-view.md b/docs/decisions/TIG-337-compare-view.md new file mode 100644 index 00000000..2b902ffe --- /dev/null +++ b/docs/decisions/TIG-337-compare-view.md @@ -0,0 +1,101 @@ +# TIG-337: side-by-side compare view (decision log) + +Branch: `tig-337-tigerpath-side-by-side-parallel-view-for-comparing`. It's stacked on TIG-330 +(`tig-330-tigerpath-implement-lucys-color-gradient-ui-on-the`), as the issue asks ("start it after TIG-330"), +so the compare boards use the gradient tokens. + +## What ships + +- **Backend:** `GET /api/v1/get_schedule/?planId=` and `GET /api/v1/get_requirements/?planId=` read any of + the user's own plans. Without `planId` they behave exactly as before (active plan). A plan id that is + missing, malformed or belongs to someone else returns 404. Neither read changes the active plan or writes anything. +- **`usePlanner`:** `comparePlanId` plus `compareSchedule`/`compareRequirements`, loaded through those + GETs only. Stale responses are dropped when the user switches quickly. +- **UI:** a **Compare** button next to the plan tabs opens a "Compare with" picker. The active plan is + editable on the left; the compared plan is read-only on the right. Each side shows a compact + requirement summary for every major and minor on that plan. Below 1100px it's one board at a time, + with a toggle between the two plans. + +## Checks from the issue + +| Check | How it's covered | +|---|---| +| Plans with different `additional_major_ids` each show their own requirements | `ComparePlanApiTest.test_each_plan_reports_its_own_majors`. Preview: plan b has two majors (SPI and POL). | +| Opening or closing compare never changes the active plan or writes a schedule | `test_compare_reads_never_change_active_plan_or_write` (plans' `schedule` and `updated_at` unchanged). Preview: zero non-GET requests across open, switch and close. | +| Selecting the same plan twice is blocked | The picker never lists the active plan (`compareOptions`, unit-tested); `setComparePlanId` refuses it as well. | +| Screenshots at 1440px and 1100px | In the PR. | + +## Decisions + +### D1. A read-only `planId` on the existing GETs, not a new endpoint + +**Blocker:** both endpoints only ever returned the active plan (`get_active_plan`). +**Decision:** add an optional `planId` to the two existing GET views, scoped to `profile.schedule_plans`. +It's honored on GET only, so `update_schedule_and_get_requirements` (POST, which reuses +`get_requirements`) always answers for the active plan it just saved. Tested. +*Other option:* a separate `get_plan_snapshot` endpoint. That's more surface area for the same data. + +### D2. The Figma has no finished side-by-side design + +The file's only compare artifact is Angelina's low-fidelity grey "STEP 2: COMPARE" wireframe: two +halves, each with a majors/minors box. **Decision:** follow the issue's behavior spec and the existing new-planner +visual language (gradient tokens, plan-tab styling). Lucy should review the layout (see the PR). + +### D3. Compare layout: two boards plus compact summaries; search and the full requirements panel are hidden + +At 1440px a search column, two boards and two full `RequirementsPanel`s don't fit. Each board would be about 360px, +which truncates every course code. **Decision:** while comparing, the two boards take the full width (about 680px +each, close to the normal board), and each side gets a compact per-major/minor summary (the issue's +"compact per-major summary" fallback). Search, settling and external credits need the full panel, +so close compare to use them. Moving and removing courses on the left still works. +*Other option:* keep `RequirementsPanel` per side and drop the search column only. That's still too narrow at 1440px. + +### D4. The read-only board renders without drag-and-drop + +Both boards sit inside one `DragDropContext`. Reusing `Droppable`/`Draggable` on the right would duplicate the +`sem0`…`sem7` droppable ids. `Board readOnly` renders static markup instead: no remove button, no +grab cursor, no hover gradient, and no `#semesters` id (the tutorial targets the left board's). + +### D5. Clicking the compared plan's tab swaps the sides + +Making the compared plan active would otherwise put the same plan on both sides. **Decision:** the +previously active plan moves to the compare side. This is the only compare-related flow that writes, +because the user explicitly chose a new active plan (`set_active_plan`). It's the same request as clicking any tab. + +### D6. Compare state isn't persisted + +Compare closes on reload. Persisting it would mean a write (`user_state`) when opening compare, and +the issue says opening and closing compare must not write. + +### D7. Summary text stays at WCAG AA + +The summary's "x/y complete" count and the "not supported yet" label use the text color, because the existing +muted grey (4.31:1) and incomplete red (4.06:1) fall just under 4.5:1 on the tinted requirement card. Colored +dots carry each requirement's done/incomplete status. +*Not changed:* the existing full requirements panel still shows its red count on white (4.27:1). Flagged for follow-up. + +### D8. The tutorial closes compare first + +The tour highlights the search pane and requirements panel, which compare mode hides. + +### D9. Print shows the active plan only + +The compare side and the summaries are `dont-print`. The printout stays "My Four Year Schedule: ". + +### D10. "By year" is the default compare layout; "Boards" stays as an option + +Requested in review: line the two plans up year by year so each semester can be compared at a glance. +**Decision:** compare mode opens in **By year**: Freshman to Senior run top to bottom, each with a Fall row +and a Spring row. Each row holds one plan's courses on a single line, active plan on the left and compared plan +on the right, so the same semester sits side by side. +- **Differences** are shown by outline shape, not color alone. A solid outline means the course is only in this + plan; a dashed outline means it's in a different semester in the other plan (the chip's tooltip says which). + Courses in the same semester in both plans stay plain. A one-line summary counts each kind, and screen readers + get the same wording. Matching uses the catalog id (external credits match by name), over the eight board + semesters (`diffSchedules`, unit-tested). +- **The left plan stays editable:** each row is a horizontal drop target, so courses can be reordered, moved + between semesters (including by keyboard) or removed. Chips shrink and truncate to keep one line per semester; + the hover card shows the full name. +- **Below 1100px** the existing toggle shows one plan's column, still aligned by semester with the markers. +- **Printing** while comparing prints the active plan as a normal board. +- **Boards** (two four-year grids, the issue's literal ask) is one click away, so reviewers can choose. diff --git a/frontend/src/new/App.jsx b/frontend/src/new/App.jsx index da4412ae..377afd82 100644 --- a/frontend/src/new/App.jsx +++ b/frontend/src/new/App.jsx @@ -12,13 +12,17 @@ import Board from './components/Board'; import RequirementsPanel from './components/RequirementsPanel'; import CourseDrawer from './components/CourseDrawer'; import SettingsModal from './components/SettingsModal'; +import ComparePicker from './components/ComparePicker'; +import CompareSummary from './components/CompareSummary'; +import CompareByYear from './components/CompareByYear'; import './styles.css'; const semesterIndexOf = (droppableId) => parseInt(droppableId.replace('sem', ''), 10); export default function App() { const planner = usePlanner(); - const { profile, plans, activePlan, schedule, requirements } = planner; + const { profile, plans, activePlan, schedule, requirements, comparePlan } = planner; + const comparing = Boolean(comparePlan); const [searchQuery, setSearchQuery] = useState(''); const [searchResults, setSearchResults] = useState([]); @@ -28,6 +32,10 @@ export default function App() { const [pathModal, setPathModal] = useState(null); // {mode: 'create'|'edit', plan} const [settingsOpen, setSettingsOpen] = useState(false); const [creditPath, setCreditPath] = useState(null); + // Below 1100px compare mode shows one board at a time; this picks which. + const [compareView, setCompareView] = useState('active'); + // 'year': semesters lined up across both plans (default); 'boards': two four-year boards. + const [compareLayout, setCompareLayout] = useState('year'); // main.jsx already applied the last-used theme before the first paint. Only apply (and remember) // a theme once the profile says which one, so there is no flash to purple while it loads and a @@ -101,12 +109,52 @@ export default function App() { const switchToClassic = () => setUiVersion('classic').then(() => window.location.reload()); + const centerTop = ( +
+ setPathModal({ mode: 'edit', plan })} + onCreate={() => setPathModal({ mode: 'create' })} + /> + { + setCompareView('active'); + planner.setComparePlanId(id); + }} + /> + + {planner.saving ? 'Saving…' : ''} + +
+ ); + + const activeBoard = schedule ? ( + + ) : ( +

Loading your plan...

+ ); + return (
setSettingsOpen(true)} onSwitchToClassic={switchToClassic} - onStartTutorial={startTutorial} + onStartTutorial={() => { + // The tour points at the search pane and requirements panel, which compare mode hides. + if (!comparing) return startTutorial(); + planner.setComparePlanId(null); + return requestAnimationFrame(() => requestAnimationFrame(startTutorial)); + }} />
@@ -118,6 +166,126 @@ export default function App() {
+ {comparing ? ( +
+
+ {centerTop} + {planner.notice && ( +
+ {planner.notice.text} +
+ )} +
+
+ + +
+
+ + +
+
+ {planner.compareError ? ( +
+

Couldn't load {comparePlan.name} to compare. Your own plan is unaffected.

+
+ + +
+
+ ) : compareLayout === 'year' ? ( + <> +
+ +
+ {/* Printing while comparing prints the active plan as a normal board. */} +
+ {schedule && } +
+ + ) : ( +
+
+
+

{activePlan?.name || 'Active plan'}

+ Editing +
+
+ +
+ {activeBoard} +
+
+
+

{comparePlan.name}

+ Read-only +
+ + {planner.compareSchedule ? ( + + ) : ( +

Loading {comparePlan.name}...

+ )} +
+
+ )} +
+
+ ) : (
-
- setPathModal({ mode: 'edit', plan })} - onCreate={() => setPathModal({ mode: 'create' })} - /> - - {planner.saving ? 'Saving…' : ''} - -
+ {centerTop} {planner.notice && (
{planner.notice.text}
)} - {schedule ? ( - - ) : ( -

Loading your plan...

- )} + {activeBoard}
activePlan && setPathModal({ mode: 'edit', plan: activePlan })} />
+ )}
minorCodes: JSON.stringify(minorCodes || []), }); -export const getSchedule = () => apiFetch('/api/v1/get_schedule/'); +// Without a planId these read the active plan. With one (compare mode) they read that plan +// read-only; the server never changes the active plan for these GETs. +export const getSchedule = (planId) => + apiFetch(planId == null ? '/api/v1/get_schedule/' : `/api/v1/get_schedule/?planId=${encodeURIComponent(planId)}`); // "grouped" returns {majors, degrees, minors} covering every major on the plan. -export const getRequirements = () => apiFetch('/api/v1/get_requirements/?layout=grouped'); +export const getRequirements = (planId) => + apiFetch( + `/api/v1/get_requirements/?layout=grouped${planId == null ? '' : `&planId=${encodeURIComponent(planId)}`}` + ); export const saveScheduleAndGetRequirements = (strippedSchedule) => apiPost('/api/v1/update_schedule_and_get_requirements/?layout=grouped', { schedule: JSON.stringify(strippedSchedule), diff --git a/frontend/src/new/components/Board.jsx b/frontend/src/new/components/Board.jsx index 8e76e834..894e0337 100644 --- a/frontend/src/new/components/Board.jsx +++ b/frontend/src/new/components/Board.jsx @@ -40,7 +40,45 @@ function CourseHoverCard({ course, semesterIndex, duplicate }) { ); } -function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { +/** + * By-year compare marker. The chip's outline (solid = only in this plan, dashed = other semester there) + * shows the difference; this text says it for screen readers, and the chip's title for hover. + */ +function DiffTag({ diff }) { + if (!diff || diff.status === 'same') return null; + return {diff.status === 'only' ? ' (only in this plan)' : ` (${diff.title})`}; +} + +const diffTitle = (diff) => { + if (!diff || diff.status === 'same') return undefined; + return diff.status === 'only' ? 'Only in this plan' : `Moved: ${diff.title}`; +}; + +const diffClass = (diff) => (diff && diff.status !== 'same' ? `diff-${diff.status}` : ''); + +/** Compare mode's right-hand board: same look, no drag-and-drop and no remove button. */ +export function ReadOnlyCourseChip({ course, semesterIndex, duplicate, diff }) { + const [hover, setHover] = useState(false); + return ( +
setHover(true)} + onMouseLeave={() => setHover(false)} + onFocus={() => setHover(true)} + onBlur={() => setHover(false)} + aria-label={`${course.name}${course.title ? `: ${course.title}` : ''}`} + > + {course.name} + + {course.title} + {hover && } +
+ ); +} + +export function CourseChip({ course, semesterIndex, index, duplicate, onRemove, diff }) { const [hover, setHover] = useState(false); return ( @@ -51,7 +89,8 @@ function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { {...provided.dragHandleProps} className={`tp-course ${snapshot.isDragging ? 'dragging' : ''} ${ isWrongSeason(course, semesterIndex) ? 'wrong-season' : '' - }`} + } ${diffClass(diff)}`} + title={diffTitle(diff)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} onFocus={() => setHover(true)} @@ -59,6 +98,7 @@ function CourseChip({ course, semesterIndex, index, duplicate, onRemove }) { aria-label={`${course.name}${course.title ? `: ${course.title}` : ''}`} > {course.name} + {course.title}
+ ); +} + +/** Highlight for the semester under a drag: green if the course is offered that term, red if not. */ +export function dropToneFor(season, draggingSeason, isDraggingOver) { + if (!isDraggingOver) return ''; + if (draggingSeason !== 'fall' && draggingSeason !== 'spring') return 'drop-ok'; + return draggingSeason === season.toLowerCase() ? 'drop-ok' : 'drop-warn'; +} + +/** Course names that appear more than once in the first eight semesters. */ +export function duplicateNamesIn(schedule) { + const counts = new Map(); + (schedule || []).slice(0, 8).flat().forEach((c) => counts.set(c.name, (counts.get(c.name) || 0) + 1)); + return new Set([...counts].filter(([, n]) => n > 1).map(([name]) => name)); +} + function Semester({ index, season, courses, draggingSeason, duplicateNames, onRemove }) { return ( {(provided, snapshot) => { - let dropTone = ''; - if (snapshot.isDraggingOver) { - const columnSeason = season.toLowerCase(); - dropTone = - draggingSeason === 'fall' || draggingSeason === 'spring' - ? draggingSeason === columnSeason - ? 'drop-ok' - : 'drop-warn' - : 'drop-ok'; - } + const dropTone = dropToneFor(season, draggingSeason, snapshot.isDraggingOver); return (
{season} @@ -120,14 +184,20 @@ function Semester({ index, season, courses, draggingSeason, duplicateNames, onRe ); } -export default function Board({ schedule, classYear, draggingSeason, onRemove }) { - const counts = new Map(); - (schedule || []).slice(0, 8).flat().forEach((c) => counts.set(c.name, (counts.get(c.name) || 0) + 1)); - const duplicateNames = new Set([...counts].filter(([, n]) => n > 1).map(([name]) => name)); +/** + * The four-year grid. `readOnly` renders the compare-mode board: no drag-and-drop (so its ids never + * collide with the editable board's droppables) and no #semesters id, which the tutorial targets. + */ +export default function Board({ schedule, classYear, draggingSeason, onRemove, readOnly = false, label }) { + const duplicateNames = duplicateNamesIn(schedule); return ( -
- {!classYear && ( +
+ {!classYear && !readOnly && (

Set your class year in Settings to label semesters correctly.

)}
@@ -137,6 +207,17 @@ export default function Board({ schedule, classYear, draggingSeason, onRemove })
{SEASONS.map((season, s) => { const index = y * 2 + s; + if (readOnly) { + return ( + + ); + } return ( `${YEARS[Math.floor(index / 2)]} ${SEASONS[index % 2]}`; + +function withTitle(mark, otherPlanName) { + if (!mark || mark.status !== 'moved') return mark; + return { ...mark, title: `${semesterName(mark.otherIndex)} in ${otherPlanName}` }; +} + +/** One semester of the editable (active) plan, as a single horizontal line of chips. */ +function EditableRow({ index, season, courses, draggingSeason, duplicateNames, marks, otherName, onRemove }) { + return ( + + {(provided, snapshot) => ( +
+ {courses.map((course, i) => ( + + ))} + {provided.placeholder} + {courses.length === 0 && !snapshot.isDraggingOver && —} +
+ )} +
+ ); +} + +function ReadOnlyRow({ index, courses, duplicateNames, marks, otherName }) { + return ( +
+ {courses.map((course, i) => ( + + ))} + {courses.length === 0 && —} +
+ ); +} + +/** + * TIG-337 "By year" compare: one row per semester, each plan's courses on a single line, the two plans + * side by side so every semester lines up across. Courses not in the other plan are tagged "only here"; + * courses in a different semester there are tagged "moved". The active plan (left) stays editable. + */ +export default function CompareByYear({ + activePlan, + comparePlan, + schedule, + compareSchedule, + requirements, + compareRequirements, + draggingSeason, + onRemove, +}) { + const diff = useMemo(() => diffSchedules(schedule, compareSchedule), [schedule, compareSchedule]); + const leftDupes = useMemo(() => duplicateNamesIn(schedule), [schedule]); + const rightDupes = useMemo(() => duplicateNamesIn(compareSchedule), [compareSchedule]); + const activeName = activePlan?.name || 'Active plan'; + const counts = { + leftOnly: [...diff.left.values()].filter((m) => m.status === 'only').length, + rightOnly: [...diff.right.values()].filter((m) => m.status === 'only').length, + moved: [...diff.left.values()].filter((m) => m.status === 'moved').length, + }; + + return ( +
+

+ {counts.leftOnly} only in {activeName} · {counts.rightOnly} only in{' '} + {comparePlan.name} · {counts.moved} in a different semester + + only in this plan + + + other semester there (hover a course for where) + +

+
+
+
+
+

{activeName}

+ Editing +
+ +
+
+
+

{comparePlan.name}

+ Read-only +
+ +
+ + {YEARS.map((year, y) => ( + +

{year}

+ {SEASONS.map((season, s) => { + const index = y * 2 + s; + return ( + +
{season}
+ + {compareSchedule ? ( + + ) : ( +
+ Loading… +
+ )} +
+ ); + })} +
+ ))} +
+
+ ); +} diff --git a/frontend/src/new/components/ComparePicker.jsx b/frontend/src/new/components/ComparePicker.jsx new file mode 100644 index 00000000..9d5ece42 --- /dev/null +++ b/frontend/src/new/components/ComparePicker.jsx @@ -0,0 +1,51 @@ +import React from 'react'; +import Icon from './Icon'; +import { compareOptions } from '../helpers/compare'; + +/** + * "Compare with…" control next to the plan tabs. Only offers plans other than the active one, + * so the same plan can never be on both sides. Choosing or clearing a plan only reads data. + */ +export default function ComparePicker({ plans, activePlanId, comparePlanId, onChange }) { + const options = compareOptions(plans, activePlanId); + const comparing = comparePlanId != null; + + if (!comparing) { + const disabled = options.length === 0; + return ( + + ); + } + + return ( +
+ + +
+ ); +} diff --git a/frontend/src/new/components/CompareSummary.jsx b/frontend/src/new/components/CompareSummary.jsx new file mode 100644 index 00000000..9645f44d --- /dev/null +++ b/frontend/src/new/components/CompareSummary.jsx @@ -0,0 +1,46 @@ +import React from 'react'; +import { planSummaries } from '../helpers/compare'; + +/** + * Compact per-program progress for one side of compare mode. Two full RequirementsPanels do not fit + * beside two boards, so each side gets one row per major/minor with its top-level requirements. + */ +export default function CompareSummary({ requirements }) { + if (!requirements) return

Loading requirements...

; + const summaries = planSummaries(requirements); + if (summaries.length === 0) { + return

No major or minors on this plan yet.

; + } + return ( +
    + {summaries.map((s, i) => ( +
  • +
    + {s.label} + {s.unsupported ? ( + not supported yet + ) : ( + + {s.done}/{s.total} complete + + )} +
    + {!s.unsupported && s.items.length > 0 && ( +
      + {s.items.map((item, j) => ( +
    • + {item.name} + {item.min > 0 && ( + + {item.count}/{item.min} + + )} +
    • + ))} +
    + )} +
  • + ))} +
+ ); +} diff --git a/frontend/src/new/components/Icon.jsx b/frontend/src/new/components/Icon.jsx index 9d95bb8b..a25c9731 100644 --- a/frontend/src/new/components/Icon.jsx +++ b/frontend/src/new/components/Icon.jsx @@ -43,6 +43,7 @@ const PATHS = { plusCircle: ['M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z', 'M8 12h8', 'M12 8v8'], history: ['M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8', 'M3 3v5h5', 'M12 7v5l4 2'], loader: ['M21 12a9 9 0 1 1-6.22-8.56'], + columns: ['M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z', 'M12 3v18'], }; export default function Icon({ name, size = 18, strokeWidth = 2, className = '', title }) { diff --git a/frontend/src/new/helpers/compare.js b/frontend/src/new/helpers/compare.js new file mode 100644 index 00000000..c8d2baf9 --- /dev/null +++ b/frontend/src/new/helpers/compare.js @@ -0,0 +1,89 @@ +import { majorLabel, minorLabel, requirementStatus } from './requirements'; + +/** Plans the user can compare against the active one: every other plan, never the active plan itself. */ +export function compareOptions(plans, activePlanId) { + return (plans || []).filter((plan) => plan.id !== activePlanId); +} + +/** + * Compact progress for one program tree (compare mode shows two of these side by side instead of + * two full RequirementsPanels). Unsupported majors arrive from the API as plain strings. + */ +export function programSummary(program, kind) { + const label = kind === 'minor' ? minorLabel(program) : majorLabel(program); + if (!program || typeof program !== 'object') { + return { label, name: String(program || label), unsupported: true, done: 0, total: 0, items: [] }; + } + const items = (program.req_list || []).map((req) => ({ + name: req.name, + count: req.count, + min: req.min_needed, + status: requirementStatus(req), + })); + const counted = items.filter((item) => item.status !== 'neutral'); + return { + label, + name: program.name || label, + unsupported: false, + done: counted.filter((item) => item.status === 'done').length, + total: counted.length, + items, + }; +} + +/** Every major then minor on a plan, as summaries. */ +export function planSummaries(requirements) { + if (!requirements) return []; + return [ + ...(requirements.majors || []).map((m) => programSummary(m, 'major')), + ...(requirements.minors || []).map((m) => programSummary(m, 'minor')), + ]; +} + +const BOARD_SEMESTERS = 8; + +/** One identity per course: catalog id, or the name for external credits (which have random ids). */ +export const courseKey = (course) => (course?.external ? `ext:${course.name}` : `id:${course?.id}`); + +/** Every board semester each course appears in (a course can be scheduled more than once). */ +function semestersByKey(schedule) { + const where = new Map(); + (schedule || []).slice(0, BOARD_SEMESTERS).forEach((semester, index) => { + (semester || []).forEach((course) => { + const key = courseKey(course); + if (!where.has(key)) where.set(key, new Set()); + where.get(key).add(index); + }); + }); + return where; +} + +/** Mark key for one occurrence: the course plus the semester it sits in. */ +export const occurrenceKey = (course, semesterIndex) => `${courseKey(course)}@${semesterIndex}`; + +function markSide(schedule, otherWhere) { + const marks = new Map(); + (schedule || []).slice(0, BOARD_SEMESTERS).forEach((semester, index) => { + (semester || []).forEach((course) => { + const others = otherWhere.get(courseKey(course)); + let mark; + if (!others) mark = { status: 'only' }; + else if (others.has(index)) mark = { status: 'same' }; + else mark = { status: 'moved', otherIndex: Math.min(...others) }; + marks.set(occurrenceKey(course, index), mark); + }); + }); + return marks; +} + +/** + * Per-occurrence differences between two plans, for the "By year" compare view, keyed by + * `occurrenceKey(course, semester)`: 'same' (the other plan has it in this semester too), 'moved' + * (only in other semesters there: `otherIndex`) or 'only' (not in the other plan at all). A course + * scheduled twice gets a mark for each copy. Only the eight board semesters are compared. + */ +export function diffSchedules(left, right) { + const leftWhere = semestersByKey(left); + const rightWhere = semestersByKey(right); + return { left: markSide(left, rightWhere), right: markSide(right, leftWhere) }; +} diff --git a/frontend/src/new/helpers/compare.test.js b/frontend/src/new/helpers/compare.test.js new file mode 100644 index 00000000..93b9e9b0 --- /dev/null +++ b/frontend/src/new/helpers/compare.test.js @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest'; +import { compareOptions, planSummaries, programSummary } from './compare'; + +const leaf = (name, count, min) => ({ name, count, min_needed: min, settled: [] }); + +describe('compareOptions', () => { + it('never offers the active plan, so the same plan cannot be on both sides', () => { + const plans = [{ id: 1 }, { id: 2 }, { id: 3 }]; + expect(compareOptions(plans, 2).map((p) => p.id)).toEqual([1, 3]); + expect(compareOptions([{ id: 1 }], 1)).toEqual([]); + }); +}); + +describe('programSummary', () => { + it('counts finished top-level requirements and skips neutral ones', () => { + const eco = { + name: 'Economics', + code: 'ECO', + req_list: [leaf('Prerequisites', 3, 3), leaf('Core', 2, 3), leaf('Notes', 0, 0)], + }; + const summary = programSummary(eco, 'major'); + expect(summary).toMatchObject({ label: 'ECO', name: 'Economics', done: 1, total: 2, unsupported: false }); + expect(summary.items.map((i) => i.status)).toEqual(['done', 'incomplete', 'neutral']); + }); + + it('marks unsupported majors (plain strings from the API)', () => { + expect(programSummary('Astrophysics', 'major')).toMatchObject({ unsupported: true, name: 'Astrophysics' }); + }); +}); + +describe('planSummaries', () => { + it('lists each plan’s own majors then minors', () => { + const reqs = { + majors: [{ name: 'Computer Science', code: 'COS', req_list: [] }, 'Politics'], + minors: [{ name: 'Finance', code: 'FIN', req_list: [leaf('Core', 1, 1)] }], + }; + expect(planSummaries(reqs).map((s) => s.label)).toEqual(['COS', 'Politics', 'FIN']); + expect(planSummaries(null)).toEqual([]); + }); +}); + +import { courseKey, diffSchedules, occurrenceKey } from './compare'; + +describe('diffSchedules', () => { + const sched = (...semesters) => [...semesters, ...Array.from({ length: 9 - semesters.length }, () => [])]; + const c = (id, name = id) => ({ id, name }); + + it('marks courses as same, moved or only, from each side', () => { + const left = sched([c('eco100'), c('cos126')], [c('mat103')]); + const right = sched([c('eco100')], [], [c('cos126'), c('pol220')]); + const { left: l, right: r } = diffSchedules(left, right); + expect(l.get('id:eco100@0')).toEqual({ status: 'same' }); + expect(l.get('id:cos126@0')).toEqual({ status: 'moved', otherIndex: 2 }); + expect(l.get('id:mat103@1')).toEqual({ status: 'only' }); + expect(r.get('id:cos126@2')).toEqual({ status: 'moved', otherIndex: 0 }); + expect(r.get('id:pol220@2')).toEqual({ status: 'only' }); + }); + + it('matches external credits by name and ignores the external-credits slot', () => { + const ap = { id: 'random-1', external: true, name: 'AP Calculus' }; + const left = sched([ap]); + const right = sched([{ ...ap, id: 'random-2' }]); + right[8] = [c('only-in-slot-9')]; + expect(diffSchedules(left, right).left.get(occurrenceKey(ap, 0))).toEqual({ status: 'same' }); + expect(diffSchedules(left, right).right.has('id:only-in-slot-9@8')).toBe(false); + }); + + it('marks each copy of a course scheduled twice on its own', () => { + // Left has COS 126 in semesters 0 and 2; right has it only in semester 0. + const left = sched([c('cos126')], [], [c('cos126')]); + const right = sched([c('cos126')]); + const { left: l } = diffSchedules(left, right); + expect(l.get('id:cos126@0')).toEqual({ status: 'same' }); + expect(l.get('id:cos126@2')).toEqual({ status: 'moved', otherIndex: 0 }); + }); +}); diff --git a/frontend/src/new/styles.css b/frontend/src/new/styles.css index bb23c605..58ad9097 100644 --- a/frontend/src/new/styles.css +++ b/frontend/src/new/styles.css @@ -1282,6 +1282,381 @@ button:disabled { line-height: 1.5; } +/* ── Compare mode (TIG-337) ────────────────────────────────────────────── */ + +.tp-compare-btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: 38px; + padding: 0 14px; + border: 1.5px solid var(--tp-border); + border-radius: 19px; + background: #fff; + font-size: 14px; + font-weight: 700; + flex-shrink: 0; +} + +.tp-compare-btn:hover:not(:disabled) { + border-color: var(--tp-active-plan-border); +} + +.tp-compare-picker { + display: flex; + align-items: center; + gap: 4px; + flex-shrink: 0; +} + +.tp-compare-picker label { + display: flex; + align-items: center; + gap: 8px; + font-size: 14px; + font-weight: 700; + white-space: nowrap; +} + +.tp-compare-picker .tp-select { + width: auto; + min-width: 140px; + max-width: 220px; +} + +.tp-main.comparing { + grid-template-columns: minmax(0, 1fr); +} + +.tp-compare { + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; +} + +.tp-compare-toggle { + display: none; +} + +.tp-compare-sides { + flex: 1; + min-height: 0; + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + /* Header, summary, board: shared rows keep both boards top-aligned whatever each summary holds. */ + grid-template-rows: auto auto minmax(0, 1fr); + column-gap: 22px; +} + +.tp-compare-side { + display: grid; + grid-row: span 3; + grid-template-rows: subgrid; + min-width: 0; + min-height: 0; +} + +.tp-compare-head { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 8px; +} + +.tp-compare-head h2 { + margin: 0; + font-size: 20px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.tp-compare-tag { + flex-shrink: 0; + padding: 2px 10px; + border-radius: 999px; + background: var(--tp-plan-tabs-fill); + color: var(--tp-text); + font-size: 12px; + font-weight: 700; +} + +.tp-compare-tag.editable { + background: var(--tp-plan-tab-active-fill); +} + +.tp-compare-summary { + list-style: none; + margin: 0 0 12px; + padding: 0; + display: flex; + flex-wrap: wrap; + gap: 8px; + max-height: 150px; + overflow-y: auto; +} + +.tp-compare-program { + flex: 1 1 200px; + min-width: 0; + padding: 8px 10px; + border-radius: 10px; + background: var(--tp-req-panel-fill); + box-shadow: 0 0 6px rgba(0, 0, 0, 0.12); +} + +.tp-compare-program-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + font-size: 15px; +} + +.tp-compare-program-head .tp-req-count { + font-size: 13px; +} + +/* Text color, not muted grey or --tp-incomplete red: both fall just under 4.5:1 on the tinted card. + The status dots carry the done/incomplete signal. */ +.tp-compare-program-head .tp-req-count.incomplete .current, +.tp-compare-unsupported { + color: var(--tp-text); +} + +.tp-compare-unsupported { + font-size: 13px; + font-style: italic; +} + +.tp-compare-reqs { + list-style: none; + margin: 4px 0 0; + padding: 0; + font-size: 13px; +} + +.tp-compare-req { + display: flex; + align-items: center; + gap: 6px; + min-height: 20px; +} + +.tp-compare-req::before { + content: ''; + width: 7px; + height: 7px; + border-radius: 50%; + flex-shrink: 0; + background: var(--tp-border); +} + +.tp-compare-req.done::before { + background: var(--tp-req-chip-text); +} + +.tp-compare-req.incomplete::before { + background: var(--tp-incomplete); +} + +.tp-compare-req-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.tp-compare-req-count { + font-variant-numeric: tabular-nums; + font-weight: 700; +} + +.tp-compare-side .tp-board { + min-height: 0; +} + +.tp-compare-side .tp-year-title { + padding: 10px 0 8px; + font-size: clamp(18px, 1.6vw, 24px); +} + +/* The compared plan is read-only: no grab cursor and no hover gradient that suggests dragging. */ +.tp-course.readonly { + cursor: default; +} + +.tp-course.readonly:hover, +.tp-course.readonly:focus-visible { + background: linear-gradient(to bottom, var(--tp-course-card-fill-start), var(--tp-course-card-fill-end)); + box-shadow: none; +} + +/* ── Compare: By year layout (TIG-337) ──────────────────────────────────── */ + +.tp-compare-error p { + margin: 0; +} + +.tp-compare-error .tp-confirm-actions { + margin-top: 10px; +} + +.tp-compare-controls { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 10px; +} + +.tp-compare-layout { + display: flex; + gap: 4px; + padding: 4px; + border-radius: 19px; + background: var(--tp-plan-tabs-fill); +} + +.tp-compare-layout button { + height: 30px; + padding: 0 14px; + border: 1.5px solid transparent; + border-radius: 15px; + background: none; + font-size: 14px; + font-weight: 500; +} + +.tp-compare-layout button.active { + background: #fff; + border-color: var(--tp-active-plan-border); + font-weight: 700; +} + +.tp-byyear-wrap { + flex: 1; + min-height: 0; + overflow-y: auto; + padding-right: 6px; +} + +.tp-byyear-legend { + margin: 0 0 10px; + font-size: 13px; + line-height: 1.8; +} + +.tp-byyear-grid { + display: grid; + grid-template-columns: 64px minmax(0, 1fr) minmax(0, 1fr); + column-gap: 16px; + row-gap: 6px; +} + +.tp-byyear-head { + position: sticky; + top: 0; + z-index: 3; + padding-bottom: 8px; + background: #fff; +} + +.tp-byyear-year { + grid-column: 1 / -1; + margin: 10px 0 2px; + padding-bottom: 4px; + border-bottom: 2px solid var(--tp-border); + font-size: 18px; +} + +.tp-byyear-season { + align-self: center; + font-size: 13px; + font-weight: 700; +} + +/* One line per semester: chips shrink and truncate (full name on hover) instead of wrapping. */ +.tp-byyear-row { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + min-height: 44px; + padding: 4px; + border: 1px solid #ececec; + border-radius: 8px; + transition: background-color 0.12s; +} + +.tp-byyear-row.drop-ok { + background: var(--tp-drop-ok); +} + +.tp-byyear-row.drop-warn { + background: var(--tp-drop-warn); +} + +.tp-byyear-row .tp-course { + flex: 0 1 auto; + min-width: 0; + max-width: 200px; + min-height: 34px; + font-size: 14px; +} + +.tp-byyear-empty { + padding: 0 6px; + color: var(--tp-muted); + font-size: 13px; +} + +/* Diff markers: a word tag plus an outline, so the difference never relies on color alone. */ +.tp-course.diff-only { + box-shadow: inset 0 0 0 2px var(--tp-active-plan-border); +} + +.tp-course.diff-moved { + outline: 2px dashed var(--tp-active-plan-border); + outline-offset: -2px; +} + +.tp-byyear-key { + display: inline-flex; + align-items: center; + gap: 6px; + margin-left: 16px; +} + +.tp-byyear-swatch { + width: 26px; + height: 14px; + border-radius: 4px; + background: linear-gradient(to bottom, var(--tp-course-card-fill-start), var(--tp-course-card-fill-end)); +} + +.tp-byyear-swatch.diff-only { + box-shadow: inset 0 0 0 2px var(--tp-active-plan-border); +} + +.tp-byyear-swatch.diff-moved { + outline: 2px dashed var(--tp-active-plan-border); + outline-offset: -2px; +} + +.tp-sr-only { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + /* ── Responsive ────────────────────────────────────────────────────────── */ @media (max-width: 1100px) { @@ -1302,6 +1677,62 @@ button:disabled { .tp-center { min-height: 720px; } + + /* Compare mode falls back to one board at a time with a toggle between the two plans. */ + .tp-compare-toggle { + display: flex; + align-self: flex-start; + gap: 4px; + margin-bottom: 12px; + padding: 4px; + border-radius: 19px; + background: var(--tp-plan-tabs-fill); + } + + .tp-compare-toggle button { + height: 30px; + padding: 0 14px; + border: 1.5px solid transparent; + border-radius: 15px; + background: none; + font-size: 14px; + font-weight: 500; + } + + .tp-compare-toggle button.active { + background: var(--tp-plan-tab-active-fill); + border-color: var(--tp-active-plan-border); + font-weight: 700; + } + + .tp-compare-sides { + grid-template-columns: minmax(0, 1fr); + } + + .tp-compare[data-show='active'] .compare-side, + .tp-compare[data-show='compare'] .active-side, + .tp-compare[data-show='active'] .compare-col, + .tp-compare[data-show='compare'] .active-col { + display: none; + } + + .tp-byyear-grid { + grid-template-columns: 64px minmax(0, 1fr); + } + + .tp-compare-toggle { + margin-bottom: 0; + } + + .tp-compare-sides { + grid-template-rows: none; + } + + .tp-compare-side { + display: flex; + flex-direction: column; + min-height: 720px; + } } @media (max-width: 760px) { diff --git a/frontend/src/new/usePlanner.js b/frontend/src/new/usePlanner.js index e689aa55..b2a54afc 100644 --- a/frontend/src/new/usePlanner.js +++ b/frontend/src/new/usePlanner.js @@ -25,6 +25,16 @@ export default function usePlanner() { const [editorOptions, setEditorOptions] = useState({ majorOptions: [], minorOptions: [], maxMajors: 3 }); const [notice, setNotice] = useState(null); const [saving, setSaving] = useState(false); + // Compare mode (TIG-337): a second plan shown read-only next to the active one. + const [comparePlanId, setComparePlanIdState] = useState(null); + const [compareSchedule, setCompareSchedule] = useState(null); + const [compareRequirements, setCompareRequirements] = useState(null); + // A failed compare read shows an error, never an empty plan (which would look like every course differs). + const [compareError, setCompareError] = useState(false); + const compareSeq = useRef(0); + // True while a tab click swaps the two sides: for a moment the compared plan equals the still-active + // plan, which must not count as "both sides show the same plan". + const swapping = useRef(false); // Responses for older saves are ignored so fast edits can't apply stale requirements. const saveSeq = useRef(0); @@ -172,6 +182,61 @@ export default function usePlanner() { [schedule, commitSchedule] ); + // ── Compare mode ───────────────────────────────────────────────────────── + // Read-only GETs by planId: opening, switching or closing compare never calls setActivePlan + // and never saves a schedule. + + const loadCompare = useCallback((planId) => { + const seq = ++compareSeq.current; + setCompareSchedule(null); + setCompareRequirements(null); + setCompareError(false); + if (planId == null) return; + const failed = () => { + if (seq !== compareSeq.current) return; + setCompareSchedule(null); + setCompareRequirements(null); + setCompareError(true); + }; + api + .getSchedule(planId) + .then((data) => seq === compareSeq.current && setCompareSchedule(data && data.length ? data : emptySchedule())) + .catch(failed); + api + .getRequirements(planId) + .then((data) => seq === compareSeq.current && setCompareRequirements(unwrapGroupedRequirements(data))) + .catch(failed); + }, []); + + const setComparePlanId = useCallback( + (planId) => { + const next = planId == null ? null : planId; + // The same plan can't be on both sides. + if (next != null && next === activePlanId) return; + setComparePlanIdState(next); + loadCompare(next); + }, + [activePlanId, loadCompare] + ); + + // Close compare if its plan disappears (deleted) or becomes the active plan, e.g. deleting the + // active plan makes the server activate the compared one; both sides would show the same plan. + useEffect(() => { + if (comparePlanId == null) return; + const sameAsActive = comparePlanId === activePlanId && !swapping.current; + if (sameAsActive || !plans.some((p) => p.id === comparePlanId)) { + setComparePlanIdState(null); + loadCompare(null); + } + }, [plans, activePlanId, comparePlanId, loadCompare]); + + // Reload both sides: requirements depend on the class year, so a Settings change must refresh the + // compared plan too, not only the active one. + const reloadPlans = useCallback(() => { + loadPlanContents(); + if (comparePlanId != null) loadCompare(comparePlanId); + }, [loadPlanContents, loadCompare, comparePlanId]); + // ── Plans ──────────────────────────────────────────────────────────────── const planAction = useCallback( @@ -186,7 +251,27 @@ export default function usePlanner() { const actions = useMemo( () => ({ - selectPlan: (id) => (id === activePlanId ? Promise.resolve() : planAction(api.setActivePlan(id))), + selectPlan: (id) => { + if (id === activePlanId) return Promise.resolve(); + // Picking the compared plan as active swaps the sides instead of showing one plan twice. + if (id === comparePlanId) { + const previous = activePlanId; + swapping.current = true; + setComparePlanIdState(previous); + loadCompare(previous); + return planAction(api.setActivePlan(id)) + .catch((error) => { + // Switch failed: put the compared plan back so the sides stay distinct. + setComparePlanIdState(id); + loadCompare(id); + throw error; + }) + .finally(() => { + swapping.current = false; + }); + } + return planAction(api.setActivePlan(id)); + }, createPlan: () => planAction(api.createPlan()), copyPlan: (sourcePlanId, name) => planAction(api.copyPlan({ sourcePlanId, name })), deletePlan: (id) => planAction(api.deletePlan(id)), @@ -199,10 +284,11 @@ export default function usePlanner() { ); }, }), - [activePlanId, planAction] + [activePlanId, comparePlanId, loadCompare, planAction] ); const activePlan = plans.find((p) => p.id === activePlanId) || null; + const comparePlan = plans.find((p) => p.id === comparePlanId) || null; return { profile, @@ -221,7 +307,13 @@ export default function usePlanner() { settle, addExternalCredit, removeExternalCredit, - reloadPlan: loadPlanContents, + reloadPlan: reloadPlans, + comparePlan, + compareSchedule, + compareRequirements, + compareError, + retryCompare: () => loadCompare(comparePlanId), + setComparePlanId, ...actions, }; } diff --git a/tigerpath/tests.py b/tigerpath/tests.py index 7f37774f..eed476f3 100644 --- a/tigerpath/tests.py +++ b/tigerpath/tests.py @@ -478,3 +478,89 @@ def test_copy_plan_copies_additional_majors(self): def test_editor_options_expose_major_cap(self): options = self.client.get("/api/v1/get_plan_editor_options/").json() self.assertEqual(options["maxMajors"], 3) + + +# External credits need no Course rows, so these fixtures stay independent of course data. +ACTIVE_CREDIT = {"id": "a1", "external": True, "name": "Credit A", "settled": []} +OTHER_CREDIT = {"id": "b1", "external": True, "name": "Credit B", "settled": []} + + +class ComparePlanApiTest(TestCase): + """TIG-337: compare mode reads a second plan by ?planId= without touching the active plan.""" + + def setUp(self): + self.user = User.objects.create_user(username="compare_user", password="testpass") + self.client.force_login(self.user) + self.profile = self.user.profile + self.profile.year = forms.create_year_choices()[0][0] + self.profile.save(update_fields=["year"]) + self.eco = Major.objects.create(name="Economics", code="ECO", degree="AB", supported=False) + self.pol = Major.objects.create(name="Politics", code="POL", degree="AB", supported=False) + self.cos = Major.objects.create( + name="Computer Science", code="COS", degree="BSE", supported=False + ) + + self.active = self.profile.schedule_plans.get() + self.active.major = self.eco + self.active.additional_major_ids = [self.pol.id] + self.active.schedule = [[ACTIVE_CREDIT]] + [[] for _ in range(8)] + self.active.save() + self.other = SchedulePlan.objects.create( + user_profile=self.profile, + name="Plan B", + major=self.cos, + minors=[], + additional_major_ids=[], + schedule=[[], [OTHER_CREDIT]] + [[] for _ in range(7)], + ) + state = self.profile.user_state or {} + state["active_plan_id"] = self.active.id + self.profile.user_state = state + self.profile.save(update_fields=["user_state"]) + + def active_plan_id(self): + return self.client.get("/api/v1/get_profile/").json()["activePlanId"] + + def test_schedule_for_compare_plan(self): + response = self.client.get(f"/api/v1/get_schedule/?planId={self.other.id}") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()[1][0]["name"], "Credit B") + # Without planId the active plan is still returned. + active_schedule = self.client.get("/api/v1/get_schedule/").json() + self.assertEqual(active_schedule[0][0]["name"], "Credit A") + + def test_each_plan_reports_its_own_majors(self): + # Plans with different additional_major_ids (migration 0023) get their own requirements. + active = self.client.get("/api/v1/get_requirements/?layout=grouped").json() + other = self.client.get( + f"/api/v1/get_requirements/?layout=grouped&planId={self.other.id}" + ).json() + self.assertEqual(active["majors"], ["Economics", "Politics"]) + self.assertEqual(other["majors"], ["Computer Science"]) + + def test_compare_reads_never_change_active_plan_or_write(self): + before = {p.id: (p.schedule, p.updated_at) for p in self.profile.schedule_plans.all()} + self.client.get(f"/api/v1/get_schedule/?planId={self.other.id}") + self.client.get(f"/api/v1/get_requirements/?layout=grouped&planId={self.other.id}") + self.client.get(f"/api/v1/get_requirements/?planId={self.other.id}") + self.assertEqual(self.active_plan_id(), self.active.id) + after = {p.id: (p.schedule, p.updated_at) for p in self.profile.schedule_plans.all()} + self.assertEqual(before, after) + + def test_other_users_plan_is_not_found(self): + stranger = User.objects.create_user(username="stranger", password="testpass") + foreign = stranger.profile.schedule_plans.get() + for url in ("/api/v1/get_schedule/", "/api/v1/get_requirements/?layout=grouped"): + sep = "&" if "?" in url else "?" + self.assertEqual(self.client.get(f"{url}{sep}planId={foreign.id}").status_code, 404) + self.assertEqual(self.client.get(f"{url}{sep}planId=not-a-number").status_code, 404) + + def test_schedule_save_ignores_plan_id(self): + # The save endpoint always writes and answers for the active plan. + response = self.client.post( + f"/api/v1/update_schedule_and_get_requirements/?layout=grouped&planId={self.other.id}", + {"schedule": json.dumps([[] for _ in range(9)])}, + ) + self.assertEqual(response.json()["majors"], ["Economics", "Politics"]) + self.other.refresh_from_db() + self.assertEqual(self.other.schedule[1], [OTHER_CREDIT]) diff --git a/tigerpath/views.py b/tigerpath/views.py index e8dff83b..2c633718 100644 --- a/tigerpath/views.py +++ b/tigerpath/views.py @@ -1035,12 +1035,29 @@ def update_schedule(request): return JsonResponse({"status": "ok"}) -# returns user's existing schedule +def get_requested_plan(request, profile): + """The plan named by ?planId= (read-only compare view), else the active plan. + + Looking up a plan this way never changes which plan is active. Returns None when + planId is given but is not one of this user's plans. + """ + raw_plan_id = request.GET.get("planId") if request.method == "GET" else None + if raw_plan_id in (None, ""): + return get_active_plan(profile) + plan_id = parse_plan_id(raw_plan_id) + if plan_id is None: + return None + return profile.schedule_plans.filter(id=plan_id).first() + + +# returns user's existing schedule (the active plan, or ?planId= for compare mode) @login_required def get_schedule(request): profile = request.user.profile - active_plan = get_active_plan(profile) - schedule = ensure_minimum_schedule(active_plan.schedule) + plan = get_requested_plan(request, profile) + if plan is None: + return JsonResponse({"error": "Plan not found"}, status=404) + schedule = ensure_minimum_schedule(plan.schedule) return JsonResponse(schedule, safe=False) @@ -1048,11 +1065,13 @@ def get_schedule(request): @login_required def get_requirements(request): curr_user = request.user.profile - active_plan = get_active_plan(curr_user) + plan = get_requested_plan(request, curr_user) + if plan is None: + return JsonResponse({"error": "Plan not found"}, status=404) # The new UI asks for every major and minor on the plan; the classic response is unchanged. if request.GET.get("layout") == "grouped": - return JsonResponse(build_grouped_requirements(curr_user, active_plan)) - requirements = build_requirements_for_plan(curr_user, active_plan) + return JsonResponse(build_grouped_requirements(curr_user, plan)) + requirements = build_requirements_for_plan(curr_user, plan) return JsonResponse(requirements, safe=False)