diff --git a/docs/decisions/TIG-282-transcript-import.md b/docs/decisions/TIG-282-transcript-import.md new file mode 100644 index 00000000..770b6efc --- /dev/null +++ b/docs/decisions/TIG-282-transcript-import.md @@ -0,0 +1,99 @@ +# TIG-282: import taken and current courses (decision log) + +Branch: `tig-282-import-pre-existing-taken-and-currently-taking`, cut from `parallel-planning/view` +(independent of TIG-330 and TIG-337). The issue has no description, so the decisions below set the scope. + +## What ships + +- **Header → Import transcript** opens a dialog. The student uploads the TigerHub *unofficial transcript* + PDF, reviews what was found (code, title, Taken or Taking now, target semester), unchecks anything + unwanted, and clicks **Add N courses**. +- **`POST /api/v1/import_transcript/`** (login required) parses the PDF in memory and returns a preview. + It stores nothing and saves nothing. The chosen courses are added on the client and saved with the + normal `update_schedule_and_get_requirements` call, as one save, into the plan the student picks. +- **`tigerpath/transcript.py`** is the parser: pure functions, unit-tested, and runnable locally with + `python -m tigerpath.transcript TRANSCRIPT.pdf [CLASS_YEAR]`, which prints codes, terms and status + only (no grades). + +## Decisions + +### D1. Data source: the transcript PDF upload (chosen by you) + +Alternatives considered: pasting TigerHub text (depends on page layout) and an OIT student API +(needs access the repo doesn't have). + +### D2. Checked against a real TigerHub transcript + +A real "Undergraduate Internal Transcript" PDF from TigerHub (Oracle/PeopleSoft) showed three things the +first version got wrong. All three are fixed and covered by tests that use made-up courses in the same +layout (no student data is in the repo): + +1. **The PDF is encrypted with an empty open-password** (it only restricts editing). It's now opened with + `decrypt("")`; a PDF with a real password is still refused. +2. **The table is laid out in columns** (`COS 226 GRD Title Grade Distrib Area`), so the + department and number are separated by several spaces. The course pattern now allows any spacing. +3. **Each row ends with a Distrib Area** (`QCR`, `NONE`, `Writing`, …) after the Grade column, and the + Grade column is blank while a course is in progress. Status is now read column by column: grade basis + (`GRD`/`PDF`/`AUD`), title, then grade, skipping distribution areas. A title ending in "B" or an `AUD` + basis is never read as a grade. Single-spaced text without columns falls back to reading tokens from + the end, skipping numbers and distribution areas; there a lone grade letter only counts as a grade next to a credit or grade-point number, since without columns it could also end the title ("Part B", "Microeconomics W"). Such rows are marked **Check grade** and are not pre-selected: the student decides, so a possible withdrawal is never added automatically and a real course is never silently dropped. + +**Grades:** a passing final grade (A to D, P) means taken; an incomplete (`INC`) is marked **Check grade**, since the course wasn't finished at the end of the term. A blank grade, `IP` or "In Progress" means +currently taking. Failed (`F`), withdrawn (`W`) and audited (grade basis `AUD`) rows are skipped, since none earns credit. Term headings like "2026-2027 Fall", "Fall 2023" and +"Spring Term 2022-23" are recognised; Summer and Winter terms are skipped. + +**Still unverified:** a transcript with *finished* terms (letter grades in the Grade column). The layout +is the same, and the tests cover it, but run `python -m tigerpath.transcript` on a multi-term +transcript when one is available. + +### D3. Privacy: no storage and no grades returned + +The upload is read in memory (5 MB cap, must start with `%PDF-`, PDFs that need a real password are +rejected) and discarded. Grades only decide taken versus current, and they're never sent back to the browser (a test +asserts this). + +### D4. Review before adding, never auto-add + +The endpoint only previews. A row can't be added if it's: +- already somewhere in the plan; +- listed twice on the transcript; +- outside the four years (for example a future term), or unplaceable because there's no class year + (the dialog says to set it in Settings). + +Courses not in the TigerPath catalog are listed as "not added". + +### D5. "Taking now" isn't stored on the course + +The schedule format has no status field, and adding one would touch the classic UI and the requirement +verifier. Status is shown in the review step only. Current-term courses are placed in their semester +like any other course. + +### D6. The student picks which plan to import into (revised) + +The first version imported into the active plan only. Review asked for a choice, so the review step now has an +**Add to** dropdown with every plan, defaulting to the current one. +- **Current plan:** duplicates are checked in the review list, and Add makes one normal save. +- **Another plan:** Add reads that plan's courses by id, adds the new ones (skipping any already there), and + saves that plan by id, without changing which plan is active. If the student is still where they started, + TigerPath then opens that plan. The review list checks duplicates against the picked plan, and the dialog + says what will happen before you confirm. If the read or save fails, nothing is imported and a notice says so. +- See D8 for why loads and saves name their plan. + +### D8. Schedule loads and saves name their plan (`planId`) + +The server used to save every schedule to whichever plan was *active*, and switching plans changes that at once. +So a save still in flight when the student switched plans (or an import into another plan) could land on the +wrong plan. Review kept finding new versions of that race, so the fix is at the root: +- `get_schedule` and `get_requirements` take an optional `?planId=` (the same code as #546's compare view, so + the two PRs merge cleanly). `update_schedule` and `update_schedule_and_get_requirements` take an optional + `planId` in the POST body and write only that plan. A plan that isn't the user's returns 404 and nothing is + written. Without `planId`, everything works as before, so the classic UI is unchanged. +- The new planner remembers which plan the on-screen schedule came from, and every save names it. A plan + whose courses failed to load can't be saved over. +- Tests: a save naming a non-active plan lands there and leaves the active plan alone; another user's plan is + rejected for both reads and saves. + +### D7. New dependency: `pypdf==6.21.4` + +It's pure Python, with no system libraries to install, and it's pinned like the rest of `requirements.txt`. +Layout-mode extraction keeps table rows on one line; plain extraction is the fallback. diff --git a/frontend/src/new/App.jsx b/frontend/src/new/App.jsx index b70d0fca..31b10779 100644 --- a/frontend/src/new/App.jsx +++ b/frontend/src/new/App.jsx @@ -12,6 +12,7 @@ import Board from './components/Board'; import RequirementsPanel from './components/RequirementsPanel'; import CourseDrawer from './components/CourseDrawer'; import SettingsModal from './components/SettingsModal'; +import ImportTranscriptModal from './components/ImportTranscriptModal'; import './styles.css'; const semesterIndexOf = (droppableId) => parseInt(droppableId.replace('sem', ''), 10); @@ -27,6 +28,7 @@ export default function App() { const [draggingSeason, setDraggingSeason] = useState(null); const [pathModal, setPathModal] = useState(null); // {mode: 'create'|'edit', plan} const [settingsOpen, setSettingsOpen] = useState(false); + const [importOpen, setImportOpen] = useState(false); const [creditPath, setCreditPath] = useState(null); const themeName = profile?.theme || 'purple'; @@ -103,6 +105,7 @@ export default function App() {
setSettingsOpen(true)} + onImportTranscript={() => setImportOpen(true)} onSwitchToClassic={switchToClassic} onStartTutorial={startTutorial} /> @@ -193,6 +196,16 @@ export default function App() { /> )} + {importOpen && ( + setImportOpen(false)} + /> + )} + {settingsOpen && ( minorCodes: JSON.stringify(minorCodes || []), }); -export const getSchedule = () => apiFetch('/api/v1/get_schedule/'); +// Pass planId to read a plan without making it active (the active plan otherwise). +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 saveScheduleAndGetRequirements = (strippedSchedule) => +export const getRequirements = (planId) => + apiFetch( + `/api/v1/get_requirements/?layout=grouped${planId == null ? '' : `&planId=${encodeURIComponent(planId)}`}` + ); +// Saves name their plan so a save always lands on the plan the schedule was loaded from, even if +// the active plan changes while the request is in flight. +export const saveScheduleAndGetRequirements = (strippedSchedule, planId) => apiPost('/api/v1/update_schedule_and_get_requirements/?layout=grouped', { schedule: JSON.stringify(strippedSchedule), + ...(planId == null ? {} : { planId: String(planId) }), }); export const searchCourses = (query, signal) => @@ -53,3 +65,29 @@ export async function saveSettings({ year, theme }) { }); if (!response.ok) throw new Error(`API error: ${response.status}`); } + +/** + * TIG-282: upload a transcript PDF and get back a preview of its courses. The server stores + * nothing; courses are only added when the student confirms (through the normal schedule save). + */ +export async function importTranscript(file) { + const body = new FormData(); + body.append('transcript', file); + const response = await fetch('/api/v1/import_transcript/', { + method: 'POST', + credentials: 'same-origin', + headers: { 'X-CSRFToken': getCookie('csrftoken') }, + body, + }); + // An expired session redirects to the login page, which still answers 200 with HTML. + const isJson = (response.headers.get('Content-Type') || '').includes('application/json'); + if (response.redirected || !isJson) { + throw new Error('Your session has expired. Reload the page to sign in again, then retry the import.'); + } + const payload = await response.json().catch(() => null); + if (!response.ok) throw new Error(payload?.error || 'Could not read that transcript. Please try again.'); + if (!payload || !Array.isArray(payload.courses)) { + throw new Error('Could not read that transcript. Please try again.'); + } + return payload; +} diff --git a/frontend/src/new/components/Header.jsx b/frontend/src/new/components/Header.jsx index e60fb472..0656de5b 100644 --- a/frontend/src/new/components/Header.jsx +++ b/frontend/src/new/components/Header.jsx @@ -4,7 +4,7 @@ import Icon from './Icon'; const FEEDBACK_URL = 'https://docs.google.com/forms/d/e/1FAIpQLSdjBwHsURKujVqfnUk7nyocAMnFDFI6fyubDmqYMgLElpm_Nw/viewform'; -export default function Header({ onOpenSettings, onSwitchToClassic, onStartTutorial }) { +export default function Header({ onOpenSettings, onSwitchToClassic, onStartTutorial, onImportTranscript }) { return (
@@ -20,6 +20,10 @@ export default function Header({ onOpenSettings, onSwitchToClassic, onStartTutor Tutorial + + +
+ + )} + + {payload && ( +
+ {rows.length === 0 ? ( +

+ No Princeton courses were found in that PDF. Make sure it's the unofficial transcript from TigerHub. +

+ ) : ( + <> +

+ Found {rows.length} course{rows.length === 1 ? '' : 's'}. Uncheck any you don't want to add. + {payload.classYear ? ( + <> + {' '} + Semesters are placed for the class of {payload.classYear} (change it in Settings if + that's wrong). + + ) : null} +

+ {(plans || []).length > 1 && ( + + )} + {unclearCount > 0 && ( +

+ {unclearCount} course{unclearCount === 1 ? '' : 's'} marked Check grade: TigerPath + couldn't tell the grade apart from the title (for example a withdrawal, W). They aren't + selected; check the ones you took. +

+ )} + {!targetIsActive && ( +

+ The courses will be added to {targetName}, skipping any already in that + plan, and TigerPath will then open it. +

+ )} + + + )} + {payload.unmatched?.length > 0 && ( +

+ Not in the TigerPath catalog, so not added: {payload.unmatched.join(', ')}. +

+ )} +
+ + +
+
+ )} + + ); +} diff --git a/frontend/src/new/helpers/transcript.js b/frontend/src/new/helpers/transcript.js new file mode 100644 index 00000000..2a61cb08 --- /dev/null +++ b/frontend/src/new/helpers/transcript.js @@ -0,0 +1,70 @@ +import { SEASONS, YEARS } from './schedule'; +import { courseFromSearchResult, isCourseAlreadyScheduled } from './schedule'; + +export const semesterLabel = (index) => + index == null ? null : `${YEARS[Math.floor(index / 2)]} ${SEASONS[index % 2]}`; + +/** + * Review rows for the import dialog. A row can be added only if it maps to a board semester and the + * course isn't already somewhere in the plan; otherwise `reason` says why it's skipped. + */ +export function buildImportRows(payload, schedule) { + const items = payload?.courses || []; + const placedReason = (item) => { + if (item.semesterIndex == null) { + return payload?.classYear ? 'Outside your four years' : 'Set your class year in Settings'; + } + if (isCourseAlreadyScheduled(schedule, item.course?.id)) return 'Already in this plan'; + return null; + }; + // A course listed more than once (a repeat) keeps one row: the first taken/in-progress one, so a + // completed retake wins over an earlier incomplete or unclear attempt; otherwise the first row. + const keeper = new Map(); + items.forEach((item, i) => { + if (placedReason(item)) return; + const id = item.course?.id; + const current = keeper.get(id); + if (current === undefined || (items[current].status === 'unclear' && item.status !== 'unclear')) { + keeper.set(id, i); + } + }); + return items.map((item, i) => { + const reason = + placedReason(item) || (keeper.get(item.course?.id) !== i ? 'Listed twice on the transcript' : null); + return { + key: `${item.code}-${item.term}-${i}`, + code: item.course?.name || item.code, + title: item.course?.title || '', + term: item.term, + status: item.status, + semesterIndex: item.semesterIndex, + semester: semesterLabel(item.semesterIndex), + course: item.course, + reason, + // The parser couldn't tell the grade from the title (e.g. a possible W): unchecked by default. + defaultOff: item.status === 'unclear', + }; + }); +} + +/** + * New schedule with the chosen rows appended to their semesters (input is not mutated). `skipped` + * counts rows whose course was already in the schedule; that check happens here when the rows were + * reviewed against a different plan than the one they land in. + */ +export function applyImport(schedule, rows) { + const next = (schedule || []).map((semester) => semester.slice()); + let added = 0; + let skipped = 0; + rows.forEach((row) => { + if (row.reason || row.semesterIndex == null || !row.course) return; + if (isCourseAlreadyScheduled(next, row.course.id)) { + skipped += 1; + return; + } + while (next.length <= row.semesterIndex) next.push([]); + next[row.semesterIndex].push(courseFromSearchResult(row.course)); + added += 1; + }); + return { schedule: next, added, skipped }; +} diff --git a/frontend/src/new/helpers/transcript.test.js b/frontend/src/new/helpers/transcript.test.js new file mode 100644 index 00000000..cfb9f890 --- /dev/null +++ b/frontend/src/new/helpers/transcript.test.js @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest'; +import { applyImport, buildImportRows, semesterLabel } from './transcript'; + +const course = (id, name) => ({ id, name, title: `${name} title`, semester: 'both', semester_list: ['f25'] }); +const empty = () => Array.from({ length: 9 }, () => []); + +const payload = { + classYear: 2026, + courses: [ + { code: 'COS 126', term: 'Fall 2022', status: 'taken', semesterIndex: 0, course: course('1', 'COS 126') }, + { code: 'COS 226', term: 'Spring 2023', status: 'taken', semesterIndex: 1, course: course('2', 'COS 226') }, + { code: 'COS 217', term: 'Fall 2023', status: 'current', semesterIndex: 2, course: course('3', 'COS 217') }, + { code: 'COS 126', term: 'Spring 2024', status: 'taken', semesterIndex: 3, course: course('1', 'COS 126') }, + { code: 'MAT 103', term: 'Fall 2027', status: 'current', semesterIndex: null, course: course('4', 'MAT 103') }, + ], +}; + +describe('buildImportRows', () => { + it('labels semesters and explains skipped rows', () => { + const schedule = empty(); + schedule[5].push({ id: '2', name: 'COS 226' }); + const rows = buildImportRows(payload, schedule); + expect(rows.map((r) => [r.code, r.semester, r.reason])).toEqual([ + ['COS 126', 'Freshman Fall', null], + ['COS 226', 'Freshman Spring', 'Already in this plan'], + ['COS 217', 'Sophomore Fall', null], + ['COS 126', 'Sophomore Spring', 'Listed twice on the transcript'], + ['MAT 103', null, 'Outside your four years'], + ]); + }); + + it('asks for a class year when terms could not be placed', () => { + const rows = buildImportRows({ classYear: null, courses: [{ ...payload.courses[0], semesterIndex: null }] }, empty()); + expect(rows[0].reason).toBe('Set your class year in Settings'); + }); +}); + +describe('applyImport', () => { + it('adds only addable rows, without mutating the schedule', () => { + const schedule = empty(); + const rows = buildImportRows(payload, schedule); + const { schedule: next, added } = applyImport(schedule, rows); + // COS 126 (once), COS 226, COS 217; the repeat and the unplaced MAT 103 are skipped. + expect(added).toBe(3); + expect(next[0].map((c) => c.id)).toEqual(['1']); + expect(next[1].map((c) => c.id)).toEqual(['2']); + expect(next[2].map((c) => c.id)).toEqual(['3']); + expect(next[0][0]).toMatchObject({ name: 'COS 126', settled: [] }); + expect(schedule[0]).toEqual([]); + }); +}); + +describe('unclear rows', () => { + it('are addable but not pre-selected', () => { + const rows = buildImportRows( + { classYear: 2026, courses: [{ ...payload.courses[0], status: 'unclear' }, payload.courses[1]] }, + empty() + ); + expect(rows.map((r) => [r.code, r.reason, r.defaultOff])).toEqual([ + ['COS 126', null, true], + ['COS 226', null, false], + ]); + }); +}); + +describe('repeated courses', () => { + it('keep a completed retake over an earlier unclear attempt', () => { + const cos = course('1', 'COS 126'); + const rows = buildImportRows( + { + classYear: 2026, + courses: [ + { code: 'COS 126', term: 'Fall 2022', status: 'unclear', semesterIndex: 0, course: cos }, + { code: 'COS 126', term: 'Fall 2023', status: 'taken', semesterIndex: 2, course: cos }, + ], + }, + empty() + ); + expect(rows.map((r) => [r.semester, r.reason])).toEqual([ + ['Freshman Fall', 'Listed twice on the transcript'], + ['Sophomore Fall', null], + ]); + }); +}); + +describe('applyImport into another plan', () => { + it('skips courses already in the target plan and counts them', () => { + // Rows reviewed with no target schedule (another plan): no "already" reasons yet. + const rows = buildImportRows(payload, null); + const target = empty(); + target[4].push({ id: '1', name: 'COS 126' }); // COS 126 already in the target plan + const { added, skipped, schedule: next } = applyImport(target, rows); + expect(skipped).toBe(1); + expect(added).toBe(2); // COS 226 and COS 217 + expect(next[4].map((c) => c.id)).toEqual(['1']); + }); +}); + +describe('semesterLabel', () => { + it('names board semesters', () => { + expect(semesterLabel(7)).toBe('Senior Spring'); + expect(semesterLabel(null)).toBeNull(); + }); +}); diff --git a/frontend/src/new/styles.css b/frontend/src/new/styles.css index 64fbf450..b2dd2b0d 100644 --- a/frontend/src/new/styles.css +++ b/frontend/src/new/styles.css @@ -195,6 +195,11 @@ button:disabled { border: 1px solid #f0d878; } +.tp-notice.success { + background: var(--tp-drop-ok); + border-color: #b9d97a; +} + .tp-notice.error { background: #ffe9e4; border-color: #f3b4a6; @@ -1281,6 +1286,155 @@ button:disabled { line-height: 1.5; } +/* ── Transcript import (TIG-282) ───────────────────────────────────────── */ + +.tp-import-modal { + width: min(640px, 100%); +} + +.tp-import-help { + margin: 0 0 14px; + font-size: 15px; + line-height: 1.45; +} + +.tp-import-file { + display: flex; + align-items: center; + gap: 10px; + padding: 14px 16px; + border: 2px dashed var(--tp-border); + border-radius: 12px; + font-weight: 700; + cursor: pointer; +} + +.tp-import-file:hover, +.tp-import-file:focus-within { + border-color: var(--tp-active-plan-border); +} + +.tp-import-file input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; +} + +.tp-import-target { + display: flex; + align-items: center; + gap: 10px; + margin: 0 0 10px; + font-size: 15px; + font-weight: 700; +} + +.tp-import-target .tp-select { + width: auto; + min-width: 200px; +} + +.tp-import-note { + margin: 0 0 10px; + padding: 8px 12px; + border-radius: 8px; + background: #fff6cc; + font-size: 14px; +} + +.tp-import-list { + list-style: none; + margin: 0; + padding: 0; + max-height: 360px; + overflow-y: auto; + border: 1px solid var(--tp-border); + border-radius: 10px; +} + +.tp-import-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 8px 12px; + border-bottom: 1px solid #ececec; + font-size: 14px; +} + +.tp-import-row:last-child { + border-bottom: 0; +} + +.tp-import-row label { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + cursor: pointer; +} + +.tp-import-code { + font-weight: 700; + white-space: nowrap; +} + +.tp-import-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--tp-muted); +} + +.tp-import-meta { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; + font-size: 13px; +} + +.tp-import-status { + padding: 1px 8px; + border-radius: 999px; + font-size: 12px; + font-weight: 700; +} + +.tp-import-status.taken { + background: var(--tp-drop-ok); +} + +.tp-import-status.unclear { + background: #fff6cc; +} + +.tp-import-status.current { + background: var(--tp-plan-tabs-fill, #eee); +} + +.tp-import-row.skipped label { + cursor: default; +} + +.tp-import-row.skipped .tp-import-meta { + color: var(--tp-muted); +} + +.tp-import-unmatched { + margin: 10px 0 0; + font-size: 13px; + color: var(--tp-muted); +} + +@media (max-width: 760px) { + .tp-import-row { + flex-direction: column; + align-items: flex-start; + } +} + /* ── Responsive ────────────────────────────────────────────────────────── */ @media (max-width: 1100px) { diff --git a/frontend/src/new/usePlanner.js b/frontend/src/new/usePlanner.js index 10edeebc..f471a372 100644 --- a/frontend/src/new/usePlanner.js +++ b/frontend/src/new/usePlanner.js @@ -9,18 +9,27 @@ import { stripSchedule, } from './helpers/schedule'; import { settleCourse, unwrapGroupedRequirements } from './helpers/requirements'; +import { applyImport } from './helpers/transcript'; const NOTICE_MS = 2500; /** - * All planner state and server sync. Mirrors the classic App.jsx data flow: - * every schedule change is saved to the active plan and requirements are recomputed. + * All planner state and server sync. Mirrors the classic App.jsx data flow: every schedule change + * is saved and requirements are recomputed. Loads and saves name their plan by id, so a save always + * lands on the plan the schedule on screen came from, whatever the server's active plan is by then. */ export default function usePlanner() { const [profile, setProfile] = useState(null); const [plans, setPlans] = useState([]); const [activePlanId, setActivePlanId] = useState(null); const [schedule, setSchedule] = useState(null); + // The plan the on-screen schedule belongs to; every save names it. + const schedulePlanId = useRef(null); + // Mirrors activePlanId for async callbacks that must see the latest value. + const activePlanRef = useRef(null); + // True when the last schedule load failed and `schedule` is only an empty placeholder: nothing + // may save over the plan in that state (it would replace the plan's real courses). + const [scheduleLoadFailed, setScheduleLoadFailed] = useState(false); const [requirements, setRequirements] = useState(null); const [editorOptions, setEditorOptions] = useState({ majorOptions: [], minorOptions: [], maxMajors: 3 }); const [notice, setNotice] = useState(null); @@ -28,6 +37,15 @@ export default function usePlanner() { // Responses for older saves are ignored so fast edits can't apply stale requirements. const saveSeq = useRef(0); + // Only the newest plan load may set the schedule: after a plan switch, a slower response for the + // previous plan must not land on the new one (a pending import would save it over that plan). + const loadSeq = useRef(0); + // Plan actions that change the active plan are numbered too: if a newer one starts, the older one's + // response (and any recovery read after it fails) is ignored. + const actionSeq = useRef(0); + // Active-plan changes run one at a time, in order: the server applies each as it lands, so letting + // two overlap could leave the server on one plan and the page on another. + const actionQueue = useRef(Promise.resolve()); const showNotice = useCallback((text, tone = 'warning') => setNotice({ text, tone, at: Date.now() }), []); @@ -39,28 +57,52 @@ export default function usePlanner() { const applyPlans = useCallback((payload) => { setPlans(payload?.plans || []); - setActivePlanId(payload?.activePlanId ?? null); + activePlanRef.current = payload?.activePlanId ?? null; + setActivePlanId(activePlanRef.current); }, []); - const loadPlanContents = useCallback(() => { + // Load one plan's schedule and requirements by id (null: whatever plan the server has active). + const loadPlanContents = useCallback((planId) => { + const seq = ++loadSeq.current; + const current = () => seq === loadSeq.current; + // Responses to saves made for the plan on screen until now no longer apply. + saveSeq.current += 1; + setSaving(false); + schedulePlanId.current = planId ?? null; setSchedule(null); setRequirements(null); + setScheduleLoadFailed(false); api - .getSchedule() - .then((data) => setSchedule(data && data.length ? data : emptySchedule())) - .catch(() => setSchedule(emptySchedule())); + .getSchedule(planId) + .then((data) => current() && setSchedule(data && data.length ? data : emptySchedule())) + .catch(() => { + if (!current()) return; + setScheduleLoadFailed(true); + setSchedule(emptySchedule()); + }); api - .getRequirements() - .then((data) => setRequirements(unwrapGroupedRequirements(data))) - .catch(() => setRequirements(unwrapGroupedRequirements(null))); + .getRequirements(planId) + .then((data) => current() && setRequirements(unwrapGroupedRequirements(data))) + .catch(() => current() && setRequirements(unwrapGroupedRequirements(null))); }, []); + const reloadPlan = useCallback(() => loadPlanContents(activePlanRef.current), [loadPlanContents]); + useEffect(() => { api .getProfile() .then(setProfile) .catch(() => setProfile({ classYear: null, theme: 'purple' })); - api.getPlans().then(applyPlans).catch(() => {}); + // The plan list says which plan is active, so its contents can be loaded by id. + const firstAction = actionSeq.current; + api + .getPlans() + .then((payload) => { + if (firstAction !== actionSeq.current) return; // a plan action already took over + applyPlans(payload); + loadPlanContents(payload?.activePlanId); + }) + .catch(() => firstAction === actionSeq.current && loadPlanContents(null)); api .getPlanEditorOptions() .then((payload) => @@ -71,16 +113,21 @@ export default function usePlanner() { }) ) .catch(() => {}); - loadPlanContents(); }, [applyPlans, loadPlanContents]); const commitSchedule = useCallback( (next) => { + if (scheduleLoadFailed) { + // The plan's courses never loaded: saving would replace them with only what's on screen. + showNotice("This plan didn't load, so changes can't be saved. Please reload the page.", 'error'); + return false; + } setSchedule(next); const seq = ++saveSeq.current; + const planId = schedulePlanId.current; setSaving(true); api - .saveScheduleAndGetRequirements(stripSchedule(next)) + .saveScheduleAndGetRequirements(stripSchedule(next), planId) .then((data) => { if (seq === saveSeq.current) setRequirements(unwrapGroupedRequirements(data)); }) @@ -88,13 +135,13 @@ export default function usePlanner() { if (seq !== saveSeq.current) return; showNotice('Could not save your last change. Your plan was reloaded.', 'error'); // Resync with what the server actually stored instead of showing unsaved edits. - loadPlanContents(); + loadPlanContents(planId); }) .finally(() => { if (seq === saveSeq.current) setSaving(false); }); }, - [showNotice, loadPlanContents] + [scheduleLoadFailed, showNotice, loadPlanContents] ); // ── Schedule edits ─────────────────────────────────────────────────────── @@ -177,32 +224,133 @@ export default function usePlanner() { (request, { reload = true } = {}) => request.then((payload) => { applyPlans(payload); - if (reload) loadPlanContents(); + if (reload) loadPlanContents(payload?.activePlanId); return payload; }), [applyPlans, loadPlanContents] ); + // Create, copy, delete and switch can all change which plan the server treats as active, as soon as + // the request lands. They run one at a time; only the newest one's result is shown. If one fails, + // re-read the plan list (it may still have changed the server) and show the plan the server is on. + const changeActivePlan = useCallback( + (makeRequest) => { + loadSeq.current += 1; + const seq = ++actionSeq.current; + const run = actionQueue.current.then(() => makeRequest()); + // Keep the queue going even if this action fails. + actionQueue.current = run.catch(() => {}); + return run.then( + (payload) => { + if (seq !== actionSeq.current) return payload; // a newer plan action is queued after this one + applyPlans(payload); + loadPlanContents(payload?.activePlanId); + return payload; + }, + (error) => { + // A failed or half-finished action (e.g. a plan created but not named) may still have changed + // the server: re-read the plan list and the active plan so the page matches it. + if (seq === actionSeq.current) { + api + .getPlans() + .then((payload) => { + if (seq !== actionSeq.current) return; // a newer plan action took over meanwhile + applyPlans(payload); + loadPlanContents(payload?.activePlanId); + }) + .catch(() => seq === actionSeq.current && loadPlanContents(activePlanRef.current)); + } + throw error; + } + ); + }, + [applyPlans, loadPlanContents] + ); + const actions = useMemo( () => ({ - selectPlan: (id) => (id === activePlanId ? Promise.resolve() : planAction(api.setActivePlan(id))), - createPlan: () => planAction(api.createPlan()), - copyPlan: (sourcePlanId, name) => planAction(api.copyPlan({ sourcePlanId, name })), - deletePlan: (id) => planAction(api.deletePlan(id)), + selectPlan: (id) => (id === activePlanId ? Promise.resolve() : changeActivePlan(() => api.setActivePlan(id))), + createPlan: () => changeActivePlan(() => api.createPlan()), + copyPlan: (sourcePlanId, name) => changeActivePlan(() => api.copyPlan({ sourcePlanId, name })), + deletePlan: (id) => changeActivePlan(() => api.deletePlan(id)), updatePlan: (settings) => planAction(api.updatePlanSettings(settings)), // Create a plan, then name it and set its major/minors in one flow. - createPlanWith: async ({ name, majorIds, minorCodes }) => { - const payload = await api.createPlan(); - await planAction( - api.updatePlanSettings({ planId: payload.activePlanId, name, majorIds, minorCodes }) - ); - }, + createPlanWith: ({ name, majorIds, minorCodes }) => + changeActivePlan(() => + api + .createPlan() + .then((payload) => + api.updatePlanSettings({ planId: payload.activePlanId, name, majorIds, minorCodes }) + ) + ), }), - [activePlanId, planAction] + [activePlanId, planAction, changeActivePlan] ); const activePlan = plans.find((p) => p.id === activePlanId) || null; + // TIG-282: add the transcript rows the student confirmed to the plan they picked, as one save. + // The plan on screen is updated in place. Any other plan is read and saved by id (the active plan + // never changes underneath it), then shown if the student is still where they started. + const importCourses = useCallback( + async (rows, targetPlanId = activePlanId) => { + const target = targetPlanId ?? activePlanId; + const planName = plans.find((p) => p.id === target)?.name; + const where = planName ? ` to ${planName}` : ''; + const report = (added, skipped) => + showNotice( + added > 0 + ? `Added ${added} course${added === 1 ? '' : 's'} from your transcript${where}${skipped ? ` (${skipped} already there)` : ''}.` + : `Nothing new to add${where}: ${skipped ? 'those courses are already there' : 'no courses selected'}.`, + added > 0 ? 'success' : 'warning' + ); + + if (target === schedulePlanId.current && schedule && !scheduleLoadFailed) { + const { schedule: next, added, skipped } = applyImport(schedule, rows); + if (added > 0 && commitSchedule(next) === false) return 0; + report(added, skipped); + return added; + } + + const startedOn = activePlanRef.current; + const startedAction = actionSeq.current; + // Runs in the plan-action queue, so opening the target plan waits until its new courses are saved + // (the student can't load the old copy and edit it over the import). + const showsTarget = () => schedulePlanId.current === target; + const work = actionQueue.current.then(async () => { + if (showsTarget()) { + // The target is on screen but not loaded yet: hold off its load until the save is done. + loadSeq.current += 1; + setSchedule(null); + } + try { + // Read the plan's stored courses first: saving without them would replace them. + const stored = await api.getSchedule(target); + const result = applyImport(stored && stored.length ? stored : emptySchedule(), rows); + if (result.added > 0) { + await api.saveScheduleAndGetRequirements(stripSchedule(result.schedule), target); + } + report(result.added, result.skipped); + return result.added; + } catch { + showNotice(`Couldn't add the courses${where}. Nothing was imported. Please try again.`, 'error'); + return null; + } finally { + if (showsTarget()) loadPlanContents(target); + } + }); + actionQueue.current = work.catch(() => {}); + const added = await work; + if (added == null) return 0; + if (!showsTarget() && activePlanRef.current === startedOn && actionSeq.current === startedAction) { + // Still where they started: take them to the plan the courses went to. + await changeActivePlan(() => api.setActivePlan(target)).catch(() => {}); + } + return added; + }, + [activePlanId, plans, schedule, scheduleLoadFailed, commitSchedule, loadPlanContents, changeActivePlan, showNotice] + ); + return { profile, setProfile, @@ -220,7 +368,8 @@ export default function usePlanner() { settle, addExternalCredit, removeExternalCredit, - reloadPlan: loadPlanContents, + reloadPlan, + importCourses, ...actions, }; } diff --git a/requirements.txt b/requirements.txt index 32ec5d01..12bda33e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -23,6 +23,7 @@ requests==2.32.4 cloudscraper==1.2.71 beautifulsoup4==4.11.2 lxml==4.9.4 +pypdf==6.21.4 # transcript import (TIG-282) redis==5.0.8 # Utilities diff --git a/tigerpath/test_transcript.py b/tigerpath/test_transcript.py new file mode 100644 index 00000000..94be069e --- /dev/null +++ b/tigerpath/test_transcript.py @@ -0,0 +1,324 @@ +"""TIG-282: transcript PDF import. Builds tiny real PDFs so pypdf extraction is exercised too.""" + +import datetime + +from django.contrib.auth.models import User +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import SimpleTestCase, TestCase + +from tigerpath.models import Course, Course_Listing, Semester +from tigerpath.transcript import ( + CURRENT, + TAKEN, + UNCLEAR, + TranscriptError, + extract_text, + parse_term, + parse_transcript_text, + semester_index, +) + + +def make_pdf(lines): + """A minimal one-page PDF with one Helvetica text line per entry.""" + + def esc(text): + return text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)") + + ops = ["BT", "/F1 10 Tf", "12 TL", "40 760 Td"] + for line in lines: + ops.append(f"({esc(line)}) Tj T*") + ops.append("ET") + stream = "\n".join(ops).encode("latin-1") + objects = [ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " + b"/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>", + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream", + ] + out = bytearray(b"%PDF-1.4\n") + offsets = [] + for i, body in enumerate(objects, start=1): + offsets.append(len(out)) + out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n" + xref = len(out) + out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode() + for off in offsets: + out += f"{off:010d} 00000 n \n".encode() + out += ( + f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode() + ) + return bytes(out) + + +TRANSCRIPT_LINES = [ + "Princeton University - Unofficial Transcript", + "2022-2023 Fall", + "COS 126 Computer Science: An Interdisciplinary Approach 1.00 1.00 A 4.00", + "HIS 214 A History of the Atlantic World 1.00 1.00 B+ 3.30", + "ECO 100 Introduction to Microeconomics 1.00 0.00 W", + "Spring Term 2022-23", + "COS226 Algorithms and Data Structures 1.00 1.00 A- 3.70", + "Summer 2023", + "ENV 101 Field Course 1.00 1.00 A", + "Fall 2023", + "COS 217 Introduction to Programming Systems 1.00 0.00 IP", + "ZZZ 999 Not In The Catalog 1.00", +] + + +class ParseTranscriptTest(SimpleTestCase): + def test_term_heading_styles(self): + self.assertEqual(parse_term("2022-2023 Fall"), ("fall", 2022)) + self.assertEqual(parse_term("2022-2023 Spring"), ("spring", 2023)) + self.assertEqual(parse_term("Spring Term 2022-23"), ("spring", 2023)) + self.assertEqual(parse_term("Fall 2023"), ("fall", 2023)) + self.assertEqual(parse_term("Summer 2023"), "other") + self.assertEqual(parse_term("2022-2023 Summer"), "other") + self.assertEqual(parse_term("2022-23 Winter"), "other") + # Season-first with an academic year, like "Spring Term 2022-23". + self.assertEqual(parse_term("Summer Term 2022-23"), "other") + self.assertEqual(parse_term("Summer 2022-2023"), "other") + self.assertEqual(parse_term("Intersession 2023-2024"), "other") + self.assertIsNone(parse_term("Cumulative GPA 3.80")) + + def test_statuses_and_terms(self): + entries = parse_transcript_text("\n".join(TRANSCRIPT_LINES)) + got = [(e.code, e.term_label, e.status) for e in entries] + self.assertEqual( + got, + [ + ("COS 126", "Fall 2022", TAKEN), + # A title word "A" is not a grade; the row's real grade (B+) is. + ("HIS 214", "Fall 2022", TAKEN), + ("COS 226", "Spring 2023", TAKEN), + ("COS 217", "Fall 2023", CURRENT), + ("ZZZ 999", "Fall 2023", CURRENT), + ], + ) # ECO 100 (withdrawn) and the summer course are skipped + + def test_year_first_summer_heading_ends_the_spring_term(self): + text = ( + "2022-2023 Spring\nCOS 226 GRD Algorithms A QCR\n" + "2022-2023 Summer\nENV 101 GRD Field Course A SEN\n" + "2023-2024 Fall\nCOS 217 GRD Programming Systems SEN\n" + ) + got = [(e.code, e.term_label) for e in parse_transcript_text(text)] + # The summer course is skipped, not filed under Spring 2023. + self.assertEqual(got, [("COS 226", "Spring 2023"), ("COS 217", "Fall 2023")]) + + def test_season_first_summer_heading_ends_the_spring_term(self): + text = ( + "Spring 2022-2023\nCOS 226 GRD Algorithms A QCR\n" + "Summer Term 2022-23\nENV 101 GRD Field Course A SEN\n" + ) + got = [(e.code, e.term_label) for e in parse_transcript_text(text)] + self.assertEqual(got, [("COS 226", "Spring 2023")]) + + def test_courses_before_any_term_are_ignored(self): + self.assertEqual(parse_transcript_text("COS 126 Something A\nFall 2023"), []) + + def test_semester_index(self): + # Class of 2026: freshman fall is Fall 2022. + self.assertEqual(semester_index("fall", 2022, 2026), 0) + self.assertEqual(semester_index("spring", 2023, 2026), 1) + self.assertEqual(semester_index("spring", 2026, 2026), 7) + self.assertIsNone(semester_index("fall", 2026, 2026)) + self.assertIsNone(semester_index("fall", 2021, 2026)) + self.assertIsNone(semester_index("fall", 2022, None)) + + def test_extract_text_rejects_non_pdfs(self): + with self.assertRaises(TranscriptError): + extract_text(b"not a pdf") + with self.assertRaises(TranscriptError): + extract_text(b"") + + def test_extract_text_reads_a_pdf(self): + text = extract_text(make_pdf(TRANSCRIPT_LINES)) + self.assertIn("COS 126", text) + self.assertEqual(len(parse_transcript_text(text)), 5) + + +# Mirrors the TigerHub "Undergraduate Internal Transcript" layout (made-up courses, no student +# data): +# layout-mode text keeps table columns, separated by runs of spaces, and rows end in a distrib area. +TIGERHUB_LAYOUT = """Undergraduate Internal Transcript +(not for External Use) +2025-2026 Fall + Course Grade Title Grade Distrib Area + Basis + COS 126 GRD Computer Science: An Approach A QCR + HIS 214 PDF The Atlantic World P HA + ECO 100 GRD Intro to Microeconomics W SA +2026-2027 Fall + PHY 104 GRD Physics Lab Part B SEN + MUS 105 AUD Music Theory LA + WRI 140 GRD Writing Seminar Writing +Number of Elected PDFs: 0 +Unofficial GPA: .000 +""" + + +class TigerHubLayoutTest(SimpleTestCase): + def test_columns_grades_and_distrib_areas(self): + got = [(e.code, e.term_label, e.status) for e in parse_transcript_text(TIGERHUB_LAYOUT)] + self.assertEqual( + got, + [ + ("COS 126", "Fall 2025", TAKEN), + ("HIS 214", "Fall 2025", TAKEN), # P/D/F basis, graded P + # ECO 100 withdrawn (W) and MUS 105 audited (AUD) are skipped: no credit. + ("PHY 104", "Fall 2026", CURRENT), # title ends in "B"; no grade column yet + ("WRI 140", "Fall 2026", CURRENT), # "Writing" is the distrib area + ], + ) + + def test_incomplete_is_check_grade(self): + text = "Fall 2025\nCOS 126 GRD Intro INC QCR\nCOS 226 GRD Algorithms A QCR" + got = [(e.code, e.status) for e in parse_transcript_text(text)] + self.assertEqual(got, [("COS 126", UNCLEAR), ("COS 226", TAKEN)]) + + def test_failed_courses_are_skipped(self): + text = ( + "Fall 2025\nCOS 126 GRD Intro F QCR\n" + "COS 226 GRD Algorithms B QCR\nMAT 103 GRD Calculus 1.00 F 0.00" + ) + self.assertEqual([e.code for e in parse_transcript_text(text)], ["COS 226"]) + + def test_cross_listed_rows(self): + text = ( + "Fall 2025\nCOS 126/EGR 126 AUD Intro QCR\n" + "COS 226 / EGR 226 GRD Algorithms A QCR\nMUS 314/COS 314 GRD Music LA" + ) + got = [(e.code, e.status) for e in parse_transcript_text(text)] + # The audit is skipped even with a cross-listing before its basis column. + self.assertEqual(got, [("COS 226", TAKEN), ("MUS 314", CURRENT)]) + + def test_audited_rows_are_skipped(self): + text = ( + "Fall 2025\nMUS 105 AUD Music Theory LA\n" + "MUS 106 AUD Music Theory II LA\nCOS 126 GRD Intro A QCR" + ) + self.assertEqual([e.code for e in parse_transcript_text(text)], ["COS 126"]) + + def test_single_spaced_rows_without_columns(self): + # Columns lost: a lone trailing grade letter could be a grade or the end of the title, so + # the row is UNCLEAR (shown, not pre-selected) unless a credit number sits next to it. + text = ( + "Fall 2025\nCOS 126 GRD Computer Science A QCR\nPHY 104 GRD Physics Lab Part B SEN\n" + "ECO 100 GRD Intro to Microeconomics W SA\nHIN 105 GRD Intermediate Hindi I NONE\n" + "COS 226 GRD Algorithms 1.00 A 4.00\nMAT 202 GRD Linear Algebra A- QCR\n" + "COS 217 GRD Systems 1.00 F 0.00" + ) + got = [(e.code, e.status) for e in parse_transcript_text(text)] + self.assertEqual( + got, + [ + ("COS 126", UNCLEAR), + ("PHY 104", UNCLEAR), + ("ECO 100", UNCLEAR), # maybe withdrawn: never added without the student choosing + ("HIN 105", CURRENT), # "I" isn't a grade letter + ("COS 226", TAKEN), + ("MAT 202", TAKEN), + ], + ) # COS 217: F next to credit numbers is a real failing grade, so skipped + + def test_empty_password_pdf_opens_but_real_password_is_refused(self): + import io + + from pypdf import PdfReader, PdfWriter + + def encrypted(user_password): + writer = PdfWriter() + for page in PdfReader(io.BytesIO(make_pdf(TRANSCRIPT_LINES))).pages: + writer.add_page(page) + writer.encrypt(user_password=user_password, owner_password="owner-only") + out = io.BytesIO() + writer.write(out) + return out.getvalue() + + # TigerHub's PDFs are like the first: encrypted, but with an empty open-password. + self.assertIn("COS 126", extract_text(encrypted(""))) + with self.assertRaises(TranscriptError): + extract_text(encrypted("secret")) + + +class ImportTranscriptApiTest(TestCase): + def setUp(self): + self.user = User.objects.create_user(username="transcript_user", password="testpass") + self.client.force_login(self.user) + profile = self.user.profile + profile.year = 2026 + profile.save(update_fields=["year"]) + semester = Semester.objects.create( + start_date=datetime.date(2025, 9, 1), + end_date=datetime.date(2025, 12, 20), + term_code="1262", + ) + for registrar_id, dept, number, title in [ + ("002051", "COS", "126", "Computer Science: An Interdisciplinary Approach"), + ("002065", "COS", "226", "Algorithms and Data Structures"), + ("002062", "COS", "217", "Introduction to Programming Systems"), + ("004210", "HIS", "214", "The Atlantic World"), + ]: + course = Course.objects.create( + semester=semester, + title=title, + description="", + registrar_id=registrar_id, + cross_listings=f"{dept} {number}", + all_semesters=["f25"], + is_master=True, + ) + Course_Listing.objects.create(course=course, dept=dept, number=number, is_primary=True) + self.plan = profile.schedule_plans.get() + + def upload(self, data, name="transcript.pdf"): + return self.client.post( + "/api/v1/import_transcript/", + {"transcript": SimpleUploadedFile(name, data, content_type="application/pdf")}, + ) + + def test_preview_places_courses_and_never_saves(self): + schedule_before = self.plan.schedule + response = self.upload(make_pdf(TRANSCRIPT_LINES)) + self.assertEqual(response.status_code, 200) + payload = response.json() + self.assertEqual(payload["classYear"], 2026) + rows = [ + (c["code"], c["semesterIndex"], c["status"], c["course"]["id"]) + for c in payload["courses"] + ] + self.assertEqual( + rows, + [ + ("COS 126", 0, TAKEN, "002051"), + ("HIS 214", 0, TAKEN, "004210"), + ("COS 226", 1, TAKEN, "002065"), + ("COS 217", 2, CURRENT, "002062"), + ], + ) + self.assertEqual(payload["unmatched"], ["ZZZ 999"]) + # Grades are never sent back. + self.assertNotIn("grade", response.content.decode().lower()) + self.plan.refresh_from_db() + self.assertEqual(self.plan.schedule, schedule_before) + + def test_rejects_bad_uploads(self): + self.assertEqual(self.upload(b"hello", name="notes.txt").status_code, 400) + self.assertEqual(self.client.post("/api/v1/import_transcript/").status_code, 400) + self.assertEqual(self.client.get("/api/v1/import_transcript/").status_code, 404) + + def test_requires_login(self): + self.client.logout() + response = self.upload(make_pdf(TRANSCRIPT_LINES)) + self.assertEqual(response.status_code, 302) + + def test_without_class_year_courses_are_unplaced(self): + profile = self.user.profile + profile.year = None + profile.save(update_fields=["year"]) + payload = self.upload(make_pdf(TRANSCRIPT_LINES)).json() + self.assertTrue(all(c["semesterIndex"] is None for c in payload["courses"])) diff --git a/tigerpath/tests.py b/tigerpath/tests.py index 7f37774f..1296bdcb 100644 --- a/tigerpath/tests.py +++ b/tigerpath/tests.py @@ -290,6 +290,46 @@ def test_set_active_plan_and_update_schedule_are_plan_specific(self): self.assertEqual(second_plan.schedule, updated_schedule) self.assertNotEqual(self.default_plan.schedule, updated_schedule) + def test_schedule_reads_and_saves_can_name_their_plan(self): + other_plan = SchedulePlan.objects.create( + user_profile=self.profile, name="Other", schedule=[[] for _ in range(9)] + ) + saved = [[{"id": "ext-9", "name": "AP Bio", "external": True, "settled": []}]] + [ + [] for _ in range(8) + ] + # The default plan stays active; the save names the other plan and must land there. + response = self.client.post( + "/api/v1/update_schedule_and_get_requirements/?layout=grouped", + {"schedule": json.dumps(saved), "planId": other_plan.id}, + ) + self.assertEqual(response.status_code, 200) + other_plan.refresh_from_db() + self.default_plan.refresh_from_db() + self.assertEqual(other_plan.schedule, saved) + self.assertNotEqual(self.default_plan.schedule, saved) + + fetched = self.client.get(f"/api/v1/get_schedule/?planId={other_plan.id}").json() + self.assertEqual(fetched[0][0]["id"], "ext-9") + active = self.client.get("/api/v1/get_plans/").json()["activePlanId"] + self.assertEqual(active, self.default_plan.id) + + def test_schedule_save_rejects_another_users_plan(self): + stranger = User.objects.create_user(username="stranger", password="pw") + foreign = stranger.profile.schedule_plans.first() or SchedulePlan.objects.create( + user_profile=stranger.profile, name="Theirs", schedule=[[] for _ in range(9)] + ) + before = foreign.schedule + response = self.client.post( + "/api/v1/update_schedule_and_get_requirements/?layout=grouped", + {"schedule": json.dumps([[{"id": "x"}]]), "planId": foreign.id}, + ) + self.assertEqual(response.status_code, 404) + foreign.refresh_from_db() + self.assertEqual(foreign.schedule, before) + self.assertEqual( + self.client.get(f"/api/v1/get_schedule/?planId={foreign.id}").status_code, 404 + ) + def test_requirements_use_active_plan_major_not_profile_major(self): profile_major = Major.objects.create( name="Profile Major", diff --git a/tigerpath/transcript.py b/tigerpath/transcript.py new file mode 100644 index 00000000..9db92a2f --- /dev/null +++ b/tigerpath/transcript.py @@ -0,0 +1,267 @@ +"""Parse a Princeton unofficial transcript PDF into (course code, term, status) entries (TIG-282). + +The PDF is read in memory and never stored. Grades are only used to tell taken courses from +in-progress ones and are not returned. Parsing is deliberately tolerant: it recognises several +term-heading styles and course rows ("COS 126", "COS126", cross-listings like "COS 126/EGR 126"). +""" + +import io +import re +from dataclasses import dataclass + +MAX_TRANSCRIPT_BYTES = 5 * 1024 * 1024 + +# "Fall 2023-2024", "Fall Term 2023-24", "Spring 2023-2024 Term" +_TERM_SEASON_FIRST_ACADEMIC = re.compile( + r"\b(Fall|Spring)(?:\s+Term)?\s+(\d{4})\s*[-–/]\s*(\d{2,4})\b", re.IGNORECASE +) +# "2023-2024 Fall", "2023-24 Spring Term" +_TERM_YEAR_FIRST_ACADEMIC = re.compile( + r"\b(\d{4})\s*[-–/]\s*(\d{2,4})\s+(Fall|Spring)\b", re.IGNORECASE +) +# "Fall 2023", "Spring Term 2024" +_TERM_CALENDAR = re.compile(r"\b(Fall|Spring)(?:\s+Term)?\s+(\d{4})\b", re.IGNORECASE) +# Summer and other non-fall/spring terms end the current term so their courses aren't misfiled. +# Both orders, like fall/spring: "Summer 2023", "Summer Term 2023", "2022-2023 Summer". +_TERM_OTHER = re.compile( + r"\b(?:(?:Summer|Winter|Intersession)(?:\s+Term)?\s+\d{4}" + r"|\d{4}\s*[-\u2013/]\s*\d{2,4}\s+(?:Summer|Winter|Intersession))\b", + re.IGNORECASE, +) + +# Course row: dept (3 capitals) + number (3 digits, optional letter). The TigerHub transcript lays +# these out in columns ("COS 226 GRD ..."), and other exports glue them ("COS126"). +_COURSE = re.compile(r"^\s*([A-Z]{3})\s*(\d{3}[A-Z]?)\b(.*)$") +# Layout-mode text separates table columns with runs of 2+ spaces. +_COLUMN_GAP = re.compile(r"\s{2,}") +_GRADES = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "P"} +# Final grades that earn no credit: skipped like withdrawals, so they can't satisfy requirements. +_NO_CREDIT = {"F", "W"} +# "Grade Basis" column right after the course number (graded, P/D/F, audit, ...). +_GRADE_BASIS = {"GRD", "PDF", "AUD", "NGR", "NG"} +# "Distrib Area" column at the end of a TigerHub row; skipped when looking for the grade. +_DISTRIB_AREAS = { + "CD", + "EC", + "EM", + "HA", + "LA", + "QCR", + "QR", + "SA", + "SEL", + "SEN", + "ST", + "STL", + "STN", + "STX", + "NONE", + "WRITING", + "LANGUAGE", + "LANG", + "W/L", +} +_NUMERIC = re.compile(r"^[\d.,()*]+$") +# Extra cross-listed codes right after the first one ("COS 126/EGR 126", "COS 126 / EGR 126"). +_CROSS_LISTING = re.compile(r"^(?:\s*/\s*[A-Z]{3}\s*\d{3}[A-Z]?\b)+") + +TAKEN = "taken" +CURRENT = "current" +# Columns were lost and the row ends in a lone grade letter that could also end the title +# ("... Part B", "... Microeconomics W"): the student decides; the row is not pre-selected. +UNCLEAR = "unclear" + + +@dataclass(frozen=True) +class TranscriptEntry: + dept: str + number: str + season: str # "fall" | "spring" + year: int # calendar year the term falls in + status: str # TAKEN | CURRENT + + @property + def code(self): + return f"{self.dept} {self.number}" + + @property + def term_label(self): + return f"{self.season.capitalize()} {self.year}" + + +class TranscriptError(ValueError): + """The upload isn't a readable transcript PDF. The message is safe to show the user.""" + + +def extract_text(pdf_bytes): + """Text of every page. Layout mode keeps table rows on one line; plain mode is the fallback.""" + if not pdf_bytes or len(pdf_bytes) > MAX_TRANSCRIPT_BYTES: + raise TranscriptError("Upload a transcript PDF under 5 MB.") + if not pdf_bytes.lstrip()[:5] == b"%PDF-": + raise TranscriptError( + "That file isn't a PDF. Upload the unofficial transcript PDF from TigerHub." + ) + from pypdf import PdfReader + from pypdf.errors import PdfReadError + + try: + reader = PdfReader(io.BytesIO(pdf_bytes)) + # TigerHub's transcript is encrypted with an empty open-password (it only restricts + # editing), so try that before treating the file as password-protected. + if reader.is_encrypted and not reader.decrypt(""): + raise TranscriptError("That PDF is password-protected. Download an unprotected copy.") + pages = [] + for page in reader.pages: + try: + pages.append(page.extract_text(extraction_mode="layout") or "") + except Exception: # layout mode can fail on unusual fonts + pages.append(page.extract_text() or "") + return "\n".join(pages) + except TranscriptError: + raise + except (PdfReadError, Exception) as exc: + raise TranscriptError( + "Couldn't read that PDF. Try downloading the transcript again." + ) from exc + + +def _full_year(start_year, end_part): + end = int(end_part) + return end if end >= 1000 else (start_year // 100) * 100 + end + + +def parse_term(line): + """(season, calendar_year) for a fall/spring heading, "other" for summer etc., else None.""" + m = _TERM_SEASON_FIRST_ACADEMIC.search(line) + if m: + season, start = m.group(1).lower(), int(m.group(2)) + end = _full_year(start, m.group(3)) + return season, start if season == "fall" else end + m = _TERM_YEAR_FIRST_ACADEMIC.search(line) + if m: + start, season = int(m.group(1)), m.group(3).lower() + end = _full_year(start, m.group(2)) + return season, start if season == "fall" else end + m = _TERM_CALENDAR.search(line) + if m: + return m.group(1).lower(), int(m.group(2)) + if _TERM_OTHER.search(line): + return "other" + return None + + +def _grade_status(token): + token = token.strip().upper() + if token in _GRADES: + return TAKEN + if token == "INC": + return UNCLEAR # incomplete: not finished at the end of the term, so the student decides + if token in _NO_CREDIT: + return None # failed or withdrawn: no credit + if token == "IP": + return CURRENT + return "unknown" + + +def _status(rest_of_line): + """TAKEN with a passing grade, CURRENT for IP/no grade, None for F, W or audited (AUD). + + TigerHub rows read: [grade basis] title [grade] [distrib area]. When the text keeps its columns, + the title is one column, so a title ending in "B" can't be read as a grade, and the grade basis + (e.g. AUD) is never mistaken for one. Otherwise, fall back to scanning tokens from the end. + """ + if re.search(r"\bin progress\b", rest_of_line, re.IGNORECASE): + return CURRENT + columns = [c for c in _COLUMN_GAP.split(rest_of_line.strip()) if c] + if columns and columns[0].upper() == "AUD": + return None # audited: no credit, so it can't count toward requirements; skip it + if columns and columns[0].upper() in _GRADE_BASIS: + columns = columns[1:] + if len(columns) >= 2: + # columns[0] is the title; a grade can only be one of the columns after it. + for column in columns[1:]: + if _NUMERIC.match(column) or column.upper() in _DISTRIB_AREAS: + continue + found = _grade_status(column) + if found != "unknown": + return found + return CURRENT + # Single-spaced text (columns lost): scan from the end, skipping numbers and a trailing + # distribution area. A lone grade letter is ambiguous here ("Physics Lab Part B" vs a grade of + # B, "Intro to Microeconomics W" vs withdrawn), so it only counts as a grade next to a credit or + # grade-point number. Otherwise the row is UNCLEAR: shown but not pre-selected, so neither is a + # withdrawn course added nor a real course dropped without the student deciding. + tokens = rest_of_line.split() + if tokens and tokens[0].upper() == "AUD": + return None + if tokens and tokens[0].upper() in _GRADE_BASIS: + tokens = tokens[1:] + for i in range(len(tokens) - 1, -1, -1): + token = tokens[i] + if _NUMERIC.match(token) or token.upper() in _DISTRIB_AREAS: + continue + if len(token) == 1: + before = tokens[i - 1] if i else "" + after = tokens[i + 1] if i + 1 < len(tokens) else "" + if not any(_NUMERIC.match(t) for t in (before, after) if t): + letter = token.upper() + return UNCLEAR if letter in _GRADES or letter in _NO_CREDIT else CURRENT + found = _grade_status(token) + return CURRENT if found == "unknown" else found + return CURRENT + + +def parse_transcript_text(text): + """Entries in transcript order, one per course per term (duplicates within a term dropped).""" + entries = [] + seen = set() + term = None + for raw_line in (text or "").splitlines(): + line = raw_line.strip() + if not line: + continue + course = _COURSE.match(line) + if not course: + found = parse_term(line) + if found is not None: + term = None if found == "other" else found + continue + if term is None: + continue + dept, number, rest = course.group(1), course.group(2), course.group(3) + rest = _CROSS_LISTING.sub("", rest) # so the grade-basis column (e.g. AUD) comes first + status = _status(rest) + if status is None: + continue + key = (dept, number, term) + if key in seen: + continue + seen.add(key) + entries.append(TranscriptEntry(dept, number, term[0], term[1], status)) + return entries + + +def semester_index(season, year, class_year): + """0-7 board index for a fall/spring term given the graduation year, or None if outside it.""" + if not class_year: + return None + first_fall = int(class_year) - 4 + index = (year - first_fall) * 2 if season == "fall" else (year - first_fall - 1) * 2 + 1 + return index if 0 <= index < 8 else None + + +if __name__ == "__main__": + # Check a real transcript locally without uploading it anywhere. Prints codes, terms and + # status only (never grades): + # python -m tigerpath.transcript path/to/transcript.pdf [class_year] + import sys + + if len(sys.argv) < 2: + sys.exit("usage: python -m tigerpath.transcript TRANSCRIPT.pdf [CLASS_YEAR]") + with open(sys.argv[1], "rb") as fh: + found = parse_transcript_text(extract_text(fh.read())) + year = int(sys.argv[2]) if len(sys.argv) > 2 else None + for entry in found: + idx = semester_index(entry.season, entry.year, year) + print(f"{entry.code:9} {entry.term_label:12} {entry.status:8} semester={idx}") + print(f"{len(found)} course(s) found") diff --git a/tigerpath/urls.py b/tigerpath/urls.py index 27f3c2d4..6d4ebccf 100644 --- a/tigerpath/urls.py +++ b/tigerpath/urls.py @@ -19,6 +19,7 @@ path("api/v1/get_courses/", views.get_courses, name="get_courses"), path("api/v1/update_schedule/", views.update_schedule, name="update_schedule"), path("api/v1/get_schedule/", views.get_schedule, name="get_schedule"), + path("api/v1/import_transcript/", views.import_transcript, name="import_transcript"), path("api/v1/get_requirements/", views.get_requirements, name="get_requirements"), path("api/v1/get_plans/", views.get_plans, name="get_plans"), path("api/v1/create_plan/", views.create_plan, name="create_plan"), diff --git a/tigerpath/views.py b/tigerpath/views.py index e8dff83b..a2d7a82d 100644 --- a/tigerpath/views.py +++ b/tigerpath/views.py @@ -21,6 +21,13 @@ from functools import wraps from . import forms, models, utils +from .transcript import ( + MAX_TRANSCRIPT_BYTES, + TranscriptError, + extract_text, + parse_transcript_text, + semester_index, +) from .majors_and_certificates.scripts.university_info import LANG_DEPTS from .majors_and_certificates.scripts.verifier import ( check_degree, @@ -1025,22 +1032,72 @@ def update_plan_settings(request): return JsonResponse(get_user_plans_payload(profile)) +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() + + +def get_posted_plan(request, profile): + """The plan a save names with planId, else the active plan (the classic UI sends none). + + Naming the plan means a save always lands on the plan it was loaded from, even if the active + plan changed while the request was in flight. Returns None for a plan the user does not own. + """ + raw_plan_id = request.POST.get("planId") + 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() + + +def save_posted_schedule(request): + """Write the posted schedule to its plan and return that plan (None if it is not the user's).""" + plan = get_posted_plan(request, request.user.profile) + if plan is not None: + plan.schedule = json.loads(request.POST.get("schedule", "[]")) + plan.save(update_fields=["schedule", "updated_at"]) + return plan + + +def plan_not_found(): + return JsonResponse({"error": "Plan not found"}, status=404) + + +def requirements_response(request, profile, plan): + # 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(profile, plan)) + return JsonResponse(build_requirements_for_plan(profile, plan), safe=False) + + # updates user's schedules with added courses @login_required def update_schedule(request): - profile = request.user.profile - active_plan = get_active_plan(profile) - active_plan.schedule = json.loads(request.POST.get("schedule", "[]")) - active_plan.save(update_fields=["schedule", "updated_at"]) + if save_posted_schedule(request) is None: + return plan_not_found() return JsonResponse({"status": "ok"}) -# returns user's existing schedule +# returns user's existing schedule (the active plan, or ?planId=) @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 plan_not_found() + schedule = ensure_minimum_schedule(plan.schedule) return JsonResponse(schedule, safe=False) @@ -1048,18 +1105,79 @@ def get_schedule(request): @login_required def get_requirements(request): curr_user = request.user.profile - active_plan = get_active_plan(curr_user) - # 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(requirements, safe=False) + plan = get_requested_plan(request, curr_user) + if plan is None: + return plan_not_found() + return requirements_response(request, curr_user, plan) +# saves the schedule to the plan it names (planId), then returns that plan's requirements @login_required def update_schedule_and_get_requirements(request): - update_schedule(request) - return get_requirements(request) + plan = save_posted_schedule(request) + if plan is None: + return plan_not_found() + return requirements_response(request, request.user.profile, plan) + + +def match_transcript_courses(entries): + """(dept, number) -> catalog Course for every course code on the transcript.""" + from django.db.models import Q + + codes = {(e.dept, e.number) for e in entries} + if not codes: + return {} + query = Q() + for dept, number in codes: + query |= Q(dept=dept, number=number) + matched = {} + listings = ( + models.Course_Listing.objects.filter(query) + .select_related("course") + .order_by("-course__is_master", "-course__id") + ) + for listing in listings: + matched.setdefault((listing.dept, listing.number), listing.course) + return matched + + +# TIG-282: parse an uploaded transcript PDF into a preview. Nothing is stored and nothing is saved; +# the client adds the courses the student confirms through the normal schedule save. +@login_required +def import_transcript(request): + if request.method != "POST": + raise Http404 + upload = request.FILES.get("transcript") + if upload is None: + return JsonResponse({"error": "Choose your transcript PDF to upload."}, status=400) + if upload.size > MAX_TRANSCRIPT_BYTES: + return JsonResponse({"error": "Upload a transcript PDF under 5 MB."}, status=400) + try: + entries = parse_transcript_text(extract_text(upload.read())) + except TranscriptError as error: + return JsonResponse({"error": str(error)}, status=400) + + class_year = request.user.profile.year + matched = match_transcript_courses(entries) + courses = [] + unmatched = [] + for entry in entries: + course = matched.get((entry.dept, entry.number)) + if course is None: + unmatched.append(entry.code) + continue + courses.append( + { + "code": entry.code, + "term": entry.term_label, + "status": entry.status, + "semesterIndex": semester_index(entry.season, entry.year, class_year), + "course": convert_courses([course], [])[0], + } + ) + return JsonResponse( + {"classYear": class_year, "courses": courses, "unmatched": sorted(set(unmatched))} + ) @login_required