From 0bf98e62f7727ba0ed3fb80077996cc255b083fb Mon Sep 17 00:00:00 2001 From: Siddharth Gupta Date: Mon, 23 Nov 2026 21:03:01 -0500 Subject: [PATCH 01/23] (feat) import taken and current courses from a transcript PDF (TIG-282) Header -> Import transcript: the student uploads the TigerHub unofficial transcript PDF, reviews the courses found (taken / taking now, target semester), and adds the ones they choose to the active plan. - POST /api/v1/import_transcript/ parses the PDF in memory with pypdf and returns a preview. Nothing is stored or saved; grades are never returned. - tigerpath/transcript.py: tolerant term/course/status parser, runnable locally to check a real transcript without uploading it. - Courses already in the plan, outside the four years, or missing a class year can't be added; catalog misses are listed. - Chosen courses are added with one normal schedule save. - Tests: 10 backend (parser, real PDF extraction, endpoint, no-save, bad uploads) and frontend helper tests. Decision log: docs/decisions/TIG-282-transcript-import.md Co-Authored-By: Claude Opus 5.5 --- docs/decisions/TIG-282-transcript-import.md | 69 +++++++ frontend/src/new/App.jsx | 12 ++ frontend/src/new/api.js | 18 ++ frontend/src/new/components/Header.jsx | 6 +- frontend/src/new/components/Icon.jsx | 1 + .../new/components/ImportTranscriptModal.jsx | 143 +++++++++++++ frontend/src/new/helpers/transcript.js | 50 +++++ frontend/src/new/helpers/transcript.test.js | 58 ++++++ frontend/src/new/styles.css | 128 ++++++++++++ frontend/src/new/usePlanner.js | 16 ++ requirements.txt | 1 + tigerpath/test_transcript.py | 195 ++++++++++++++++++ tigerpath/transcript.py | 182 ++++++++++++++++ tigerpath/urls.py | 1 + tigerpath/views.py | 67 ++++++ 15 files changed, 946 insertions(+), 1 deletion(-) create mode 100644 docs/decisions/TIG-282-transcript-import.md create mode 100644 frontend/src/new/components/ImportTranscriptModal.jsx create mode 100644 frontend/src/new/helpers/transcript.js create mode 100644 frontend/src/new/helpers/transcript.test.js create mode 100644 tigerpath/test_transcript.py create mode 100644 tigerpath/transcript.py diff --git a/docs/decisions/TIG-282-transcript-import.md b/docs/decisions/TIG-282-transcript-import.md new file mode 100644 index 00000000..732e836c --- /dev/null +++ b/docs/decisions/TIG-282-transcript-import.md @@ -0,0 +1,69 @@ +# 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. +- **`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. The real transcript layout hasn't been verified yet + +No real Princeton transcript was available, so the parser is tolerant by design: +- **Term headings:** "Fall 2023", "2023-2024 Fall", "Fall Term 2023-24" and "Spring Term 2022-23". + Summer and Winter terms close the current term, so their courses aren't misfiled. +- **Course rows:** "COS 126" or "COS126" at the start of a line. Cross-listed courses map to their + catalog course through the `Course_Listing` lookup. +- **Status:** read from the *end* of the row, after the credit and grade-point numbers. A final grade + (A to F, P, AUD, INC) means taken. "IP", "In Progress" or no grade means currently taking. "W" + (withdrawn) is skipped. Reading from the end means a title word like "A History…" is never taken for + a grade. + +**Before merging:** run `python -m tigerpath.transcript .pdf ` on a real +transcript. If a heading or row style is missed, add it as a test case in `test_transcript.py`. + +### D3. Privacy: no storage and no grades returned + +The upload is read in memory (5 MB cap, must start with `%PDF-`, encrypted PDFs 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. Imports go into the active plan only + +This matches how every other edit works. To import into another plan, switch to it first. + +### 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..365b0387 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,15 @@ export default function App() { /> )} + {importOpen && ( + setImportOpen(false)} + /> + )} + {settingsOpen && ( ({})); + if (!response.ok) throw new Error(payload.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. +

+
    + {rows.map((row) => ( +
  • + + + {STATUS_LABEL[row.status] || row.status} + {row.reason || row.semester} + +
  • + ))} +
+ + )} + {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..c2e8aa6d --- /dev/null +++ b/frontend/src/new/helpers/transcript.js @@ -0,0 +1,50 @@ +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 seen = new Set(); + return (payload?.courses || []).map((item, i) => { + const id = item.course?.id; + let reason = null; + if (item.semesterIndex == null) { + reason = payload?.classYear ? 'Outside your four years' : 'Set your class year in Settings'; + } else if (isCourseAlreadyScheduled(schedule, id)) { + reason = 'Already in this plan'; + } else if (seen.has(id)) { + reason = 'Listed twice on the transcript'; + } + if (!reason) seen.add(id); + 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, + }; + }); +} + +/** New schedule with the chosen rows appended to their semesters (input is not mutated). */ +export function applyImport(schedule, rows) { + const next = (schedule || []).map((semester) => semester.slice()); + let added = 0; + rows.forEach((row) => { + if (row.reason || row.semesterIndex == null || !row.course) return; + if (isCourseAlreadyScheduled(next, row.course.id)) return; + while (next.length <= row.semesterIndex) next.push([]); + next[row.semesterIndex].push(courseFromSearchResult(row.course)); + added += 1; + }); + return { schedule: next, added }; +} diff --git a/frontend/src/new/helpers/transcript.test.js b/frontend/src/new/helpers/transcript.test.js new file mode 100644 index 00000000..ac76af12 --- /dev/null +++ b/frontend/src/new/helpers/transcript.test.js @@ -0,0 +1,58 @@ +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('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..f584e839 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,129 @@ 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-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.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..6d2aad4c 100644 --- a/frontend/src/new/usePlanner.js +++ b/frontend/src/new/usePlanner.js @@ -9,6 +9,7 @@ import { stripSchedule, } from './helpers/schedule'; import { settleCourse, unwrapGroupedRequirements } from './helpers/requirements'; +import { applyImport } from './helpers/transcript'; const NOTICE_MS = 2500; @@ -171,6 +172,20 @@ export default function usePlanner() { [schedule, commitSchedule] ); + // TIG-282: add the transcript rows the student confirmed, as one normal schedule save. + const importCourses = useCallback( + (rows) => { + if (!schedule) return 0; + const { schedule: next, added } = applyImport(schedule, rows); + if (added > 0) { + commitSchedule(next); + showNotice(`Added ${added} course${added === 1 ? '' : 's'} from your transcript.`, 'success'); + } + return added; + }, + [schedule, commitSchedule, showNotice] + ); + // ── Plans ──────────────────────────────────────────────────────────────── const planAction = useCallback( @@ -221,6 +236,7 @@ export default function usePlanner() { addExternalCredit, removeExternalCredit, reloadPlan: loadPlanContents, + 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..818f347a --- /dev/null +++ b/tigerpath/test_transcript.py @@ -0,0 +1,195 @@ +"""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, + 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.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_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) + + +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/transcript.py b/tigerpath/transcript.py new file mode 100644 index 00000000..0c7c4e26 --- /dev/null +++ b/tigerpath/transcript.py @@ -0,0 +1,182 @@ +"""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. +_TERM_OTHER = re.compile(r"\b(Summer|Winter|Intersession)\b(?:\s+Term)?\s+\d{4}", re.IGNORECASE) + +# Course row: dept (3 capitals) + number (3 digits, optional letter), optionally glued ("COS126"). +_COURSE = re.compile(r"^\s*([A-Z]{3})\s?(\d{3}[A-Z]?)\b(.*)$") +# Final grades. Read only from the end of a row (after the title), so a title word like "A" +# never counts. +_GRADES = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "F", "P", "AUD", "INC"} +_NUMERIC = re.compile(r"^[\d.,()*]+$") + +TAKEN = "taken" +CURRENT = "current" + + +@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)) + if reader.is_encrypted: + 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 _status(rest_of_line): + """TAKEN with a final grade, CURRENT for IP/no grade, None for withdrawn (W).""" + if re.search(r"\bin progress\b", rest_of_line, re.IGNORECASE): + return CURRENT + for token in reversed(rest_of_line.split()): + if _NUMERIC.match(token): + continue # credits / grade points columns + token = token.upper() + if token in _GRADES: + return TAKEN + if token == "W": + return None + return CURRENT # "IP", or the row ends in the title: no grade yet + 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) + 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..8e3f11e6 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, @@ -1062,6 +1069,66 @@ def update_schedule_and_get_requirements(request): return get_requirements(request) +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 def set_ui_version(request): if request.method != "POST": From c51abfbacc2e2134247eb528c38ce54363cde039 Mon Sep 17 00:00:00 2001 From: Siddharth Gupta Date: Mon, 23 Nov 2026 21:05:59 -0500 Subject: [PATCH 02/23] (fix) TIG-282: parse the real TigerHub transcript layout Checked against a real TigerHub "Undergraduate Internal Transcript" PDF: - open PDFs encrypted with an empty open-password (TigerHub's are); - allow column spacing between dept and number ("COS 226"); - read status by column (grade basis, title, grade), skipping the trailing Distrib Area, so taken courses aren't shown as in progress and a title ending in "B" or an AUD basis is never a grade. Regression tests use made-up courses in the same layout. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/TIG-282-transcript-import.md | 41 ++++++---- tigerpath/test_transcript.py | 60 ++++++++++++++ tigerpath/transcript.py | 87 +++++++++++++++++---- 3 files changed, 156 insertions(+), 32 deletions(-) diff --git a/docs/decisions/TIG-282-transcript-import.md b/docs/decisions/TIG-282-transcript-import.md index 732e836c..cb42aefd 100644 --- a/docs/decisions/TIG-282-transcript-import.md +++ b/docs/decisions/TIG-282-transcript-import.md @@ -22,25 +22,34 @@ Branch: `tig-282-import-pre-existing-taken-and-currently-taking`, cut from `para Alternatives considered: pasting TigerHub text (depends on page layout) and an OIT student API (needs access the repo doesn't have). -### D2. The real transcript layout hasn't been verified yet - -No real Princeton transcript was available, so the parser is tolerant by design: -- **Term headings:** "Fall 2023", "2023-2024 Fall", "Fall Term 2023-24" and "Spring Term 2022-23". - Summer and Winter terms close the current term, so their courses aren't misfiled. -- **Course rows:** "COS 126" or "COS126" at the start of a line. Cross-listed courses map to their - catalog course through the `Course_Listing` lookup. -- **Status:** read from the *end* of the row, after the credit and grade-point numbers. A final grade - (A to F, P, AUD, INC) means taken. "IP", "In Progress" or no grade means currently taking. "W" - (withdrawn) is skipped. Reading from the end means a title word like "A History…" is never taken for - a grade. - -**Before merging:** run `python -m tigerpath.transcript .pdf ` on a real -transcript. If a heading or row style is missed, add it as a test case in `test_transcript.py`. +### 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. + +**Grades:** a final grade (A to F, P, INC) means taken. A blank grade, `IP` or "In Progress" means +currently taking. `W` (withdrawn) is skipped. 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-`, encrypted PDFs are rejected) and -discarded. Grades only decide taken versus current, and they're never sent back to the browser (a test +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 diff --git a/tigerpath/test_transcript.py b/tigerpath/test_transcript.py index 818f347a..30c58f88 100644 --- a/tigerpath/test_transcript.py +++ b/tigerpath/test_transcript.py @@ -116,6 +116,66 @@ def test_extract_text_reads_a_pdf(self): 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) is skipped. + ("PHY 104", "Fall 2026", CURRENT), # title ends in "B"; no grade column yet + ("MUS 105", "Fall 2026", CURRENT), # AUD is the grade basis, not a grade + ("WRI 140", "Fall 2026", CURRENT), # "Writing" is the distrib area + ], + ) + + def test_single_spaced_row_with_distrib_area(self): + text = "Fall 2025\nCOS 126 GRD Computer Science A QCR\nMAT 202 GRD Linear Algebra QCR" + got = [(e.code, e.status) for e in parse_transcript_text(text)] + self.assertEqual(got, [("COS 126", TAKEN), ("MAT 202", CURRENT)]) + + 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") diff --git a/tigerpath/transcript.py b/tigerpath/transcript.py index 0c7c4e26..f1b12cb5 100644 --- a/tigerpath/transcript.py +++ b/tigerpath/transcript.py @@ -24,11 +24,36 @@ # Summer and other non-fall/spring terms end the current term so their courses aren't misfiled. _TERM_OTHER = re.compile(r"\b(Summer|Winter|Intersession)\b(?:\s+Term)?\s+\d{4}", re.IGNORECASE) -# Course row: dept (3 capitals) + number (3 digits, optional letter), optionally glued ("COS126"). -_COURSE = re.compile(r"^\s*([A-Z]{3})\s?(\d{3}[A-Z]?)\b(.*)$") -# Final grades. Read only from the end of a row (after the title), so a title word like "A" -# never counts. -_GRADES = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "F", "P", "AUD", "INC"} +# 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", "F", "P", "INC"} +# "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.,()*]+$") TAKEN = "taken" @@ -69,7 +94,9 @@ def extract_text(pdf_bytes): try: reader = PdfReader(io.BytesIO(pdf_bytes)) - if reader.is_encrypted: + # 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: @@ -111,19 +138,47 @@ def parse_term(line): return None +def _grade_status(token): + token = token.strip().upper() + if token in _GRADES: + return TAKEN + if token == "W": + return None # withdrawn: not taken + if token == "IP": + return CURRENT + return "unknown" + + def _status(rest_of_line): - """TAKEN with a final grade, CURRENT for IP/no grade, None for withdrawn (W).""" + """TAKEN with a final grade, CURRENT for IP/no grade, None for withdrawn (W). + + 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 - for token in reversed(rest_of_line.split()): - if _NUMERIC.match(token): - continue # credits / grade points columns - token = token.upper() - if token in _GRADES: - return TAKEN - if token == "W": - return None - return CURRENT # "IP", or the row ends in the title: no grade yet + columns = [c for c in _COLUMN_GAP.split(rest_of_line.strip()) if c] + 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: scan from the end, skipping numbers and a trailing distribution area. + tokens = rest_of_line.split() + if tokens and tokens[0].upper() in _GRADE_BASIS: + tokens = tokens[1:] + for token in reversed(tokens): + if _NUMERIC.match(token) or token.upper() in _DISTRIB_AREAS: + continue + found = _grade_status(token) + return CURRENT if found == "unknown" else found return CURRENT From 0b1c110a1e5b064a520d3529d07f24fa16c2e56b Mon Sep 17 00:00:00 2001 From: Siddharth Gupta Date: Tue, 24 Nov 2026 14:31:46 -0500 Subject: [PATCH 03/23] (feat) TIG-282: choose which plan a transcript import goes into The import review step gets an "Add to" dropdown (defaults to the current plan). Importing into another plan switches to it, waits for its schedule, then adds the courses with one normal save, skipping any already there and saying how many in the confirmation. No backend change. Decision log D6 revised. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/TIG-282-transcript-import.md | 16 ++++-- frontend/src/new/App.jsx | 3 +- .../new/components/ImportTranscriptModal.jsx | 43 ++++++++++++-- frontend/src/new/helpers/transcript.js | 14 ++++- frontend/src/new/helpers/transcript.test.js | 13 +++++ frontend/src/new/styles.css | 22 +++++++ frontend/src/new/usePlanner.js | 57 ++++++++++++++----- 7 files changed, 140 insertions(+), 28 deletions(-) diff --git a/docs/decisions/TIG-282-transcript-import.md b/docs/decisions/TIG-282-transcript-import.md index cb42aefd..9bcfb03d 100644 --- a/docs/decisions/TIG-282-transcript-import.md +++ b/docs/decisions/TIG-282-transcript-import.md @@ -10,7 +10,7 @@ Branch: `tig-282-import-pre-existing-taken-and-currently-taking`, cut from `para 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. + 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). @@ -68,9 +68,17 @@ The schedule format has no status field, and adding one would touch the classic verifier. Status is shown in the review step only. Current-term courses are placed in their semester like any other course. -### D6. Imports go into the active plan only - -This matches how every other edit works. To import into another plan, switch to it first. +### 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:** the server only saves the active plan's schedule, so Add switches to that plan + (`set_active_plan`, the same as clicking its tab), waits for its schedule to load, then adds the courses with + one save. Duplicates already in that plan are skipped at that point and counted in the confirmation ("Added 3 + courses … to plan b (1 already there)"). The dialog says this before you confirm. If the switch fails, nothing + is imported and an error notice says so. +- **No backend change**, so #547 stays independent of #545 and #546. ### D7. New dependency: `pypdf==6.21.4` diff --git a/frontend/src/new/App.jsx b/frontend/src/new/App.jsx index 365b0387..31b10779 100644 --- a/frontend/src/new/App.jsx +++ b/frontend/src/new/App.jsx @@ -199,7 +199,8 @@ export default function App() { {importOpen && ( setImportOpen(false)} /> diff --git a/frontend/src/new/components/ImportTranscriptModal.jsx b/frontend/src/new/components/ImportTranscriptModal.jsx index 173e409d..da007ce5 100644 --- a/frontend/src/new/components/ImportTranscriptModal.jsx +++ b/frontend/src/new/components/ImportTranscriptModal.jsx @@ -10,14 +10,22 @@ const STATUS_LABEL = { taken: 'Taken', current: 'Taking now' }; * TIG-282: upload the TigerHub unofficial transcript PDF, review what was found, then add the chosen * courses to the active plan. Nothing is saved until "Add" (and then only through the normal save). */ -export default function ImportTranscriptModal({ schedule, planName, onImport, onClose }) { +export default function ImportTranscriptModal({ schedule, plans, activePlanId, onImport, onClose }) { const [file, setFile] = useState(null); + const [targetPlanId, setTargetPlanId] = useState(activePlanId); + const targetIsActive = targetPlanId === activePlanId; + const targetName = (plans || []).find((p) => p.id === targetPlanId)?.name || 'this plan'; const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [payload, setPayload] = useState(null); const [excluded, setExcluded] = useState(() => new Set()); - const rows = useMemo(() => (payload ? buildImportRows(payload, schedule) : []), [payload, schedule]); + // Duplicates are checked against the target plan: here for the active plan (its schedule is loaded), + // or when the rows are added for any other plan. + const rows = useMemo( + () => (payload ? buildImportRows(payload, targetIsActive ? schedule : null) : []), + [payload, schedule, targetIsActive] + ); const chosen = rows.filter((r) => !r.reason && !excluded.has(r.key)); const upload = async (e) => { @@ -51,8 +59,8 @@ export default function ImportTranscriptModal({ schedule, planName, onImport, on

Upload your unofficial transcript PDF from TigerHub. TigerPath reads the course codes and - terms, then lets you choose which to add to {planName || 'this plan'}. The file isn't - stored, and grades aren't kept. + terms, then lets you choose which courses to add and which plan to add them to. The file isn't stored, + and grades aren't kept.