diff --git a/.env.example b/.env.example index e0fa8d4..ecddc68 100644 --- a/.env.example +++ b/.env.example @@ -11,7 +11,7 @@ WEB_ORIGIN= # Generate once: node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" JWT_SECRET= -# Stripe hosted Checkout. Only sandbox secret keys (sk_test_) are accepted. +# Provider credential for hosted card checkout. STRIPE_SECRET_KEY= # Email delivery. Enter the provider settings in your ignored .env file. @@ -22,7 +22,7 @@ SMTP_REQUIRE_TLS=true SMTP_USER= SMTP_PASS= SMTP_FROM= -# Probation warnings run in production by default. Enable in development for SMTP testing. +# Probation warnings run automatically in production. # PROBATION_WARNINGS_ENABLED=true # Google Calendar OAuth (Req. 116). Create OAuth credentials in Google Cloud. @@ -31,6 +31,3 @@ GOOGLE_CLIENT_SECRET= GOOGLE_REDIRECT_URI=http://localhost:3000/api/calendar/oauth/callback CALENDAR_TOKEN_ENCRYPTION_KEY= UNIVERSITY_TIMEZONE=Africa/Cairo - -# Development accounts only; disabled by default and always disabled in production. -ALLOW_DEMO_SEED=true diff --git a/README.md b/README.md index d99fa1c..47daa11 100644 --- a/README.md +++ b/README.md @@ -10,15 +10,8 @@ A timetable change can affect more than a student's week. It can consume a seat, [![Functional regression on development](https://github.com/Advanced-Computer-Lab-2026/Bobos/actions/workflows/regression.yml/badge.svg?branch=development)](https://github.com/Advanced-Computer-Lab-2026/Bobos/actions/workflows/regression.yml?query=branch%3Adevelopment) -GitHub Actions runs the functional and browser suites on pushes and pull requests targeting `development` or `main`. On the local Sprint 2 baseline `2997234`, the production build succeeded and all 21 browser tests passed. Of 358 functional checks, 357 passed. The Requirement 121 startup-reminder test hit its five-second startup deadline in that run and passed on an isolated rerun. The [GitHub Actions run for this commit](https://github.com/Advanced-Computer-Lab-2026/Bobos/actions/runs/46045616414) passed. -| Known issue or limit | Effect | -| --- | --- | -| Requirement 121 startup test can time out | A slow API startup can fail the reminder test before it reaches the notification assertions. | -| Checkout supports Stripe sandbox only | Card payments use test transactions in EGP. Checkout needs an `sk_test_` key and accepts one settlement method per request. | -| SMTP and Google Calendar need separate configuration | Email password reset, probation emails and Calendar sync need provider credentials. Automated tests use local mail and controlled provider responses. Live provider availability needs a separate check. | -| Optional advisor and administrator seeds require prepared fixtures | The advisor preview seed expects a published Scientific Methods offering and a future term. The administrator preview seed looks up student IDs that differ from those used by the standard sign-in fixtures. The installation steps use the base and timetable seeds. | -| Assessment deployment needs its own accounts and data | Local seed fixtures are for development. The hosted portal needs provisioned university accounts and a smoke test of each role. See [production readiness](docs/production-readiness.md). | +GitHub Actions builds Portal and runs the functional and browser suites on pushes and pull requests targeting `development` or `main`. The badge links to the latest results. See [deployment configuration](docs/production-readiness.md) for the services and accounts to provision before release. ## Code style @@ -75,7 +68,7 @@ Select a single date or a range. Click the month heading to choose a different m | **React, JavaScript, HTML, and CSS** | Render the portal shell, role-based navigation, and academic workflow screens. Vite runs the development server and bundles the production frontend. | | **JWT and bcryptjs** | Authenticate API calls and hash passwords. | | **Nodemailer and SMTP** | Send password-reset codes and academic warning emails. | -| **Stripe Checkout and Google Calendar API** | Provide sandbox card payments and Google OAuth calendar sync. | +| **Stripe Checkout and Google Calendar API** | Provide hosted card checkout and Google OAuth calendar sync. | | **PDFKit and CSV** | Generate transcripts, timetables, receipts, confirmations, and tabular exports. | | **Node Test Runner, Playwright, and GitHub Actions** | Check policy functions, API behavior, and browser workflows in CI. | @@ -91,7 +84,7 @@ The repo uses npm workspaces. `apps/web` contains the live frontend and `apps/ap | Normal-student scheduling | Build standard schedule templates, assign groups, check clashes and seat capacity, view or download timetables, view registered courses, and submit or withdraw eligible whole-schedule swaps. | | Advising schedules | Submit ranked scheduling preferences, view assigned advisor details, handle bachelor-project eligibility and mandatory retakes, select eligible courses and groups within the credit limit, and draft, review, process, or reopen schedules. | | Individual changes and removals | Request eligible tutorial or lab replacements and mandatory-course removals. Staff can filter submissions, review reasons, record decisions, and track schedule changes. | -| Extra hours and payments | Check eligibility and rates, submit or withdraw pending requests, record coordinator decisions, settle through the wallet or Stripe sandbox, or defer to the next installment. Students can see attempts, retry checkout, and download receipts or deferral confirmations. Staff can review cancellations and refunds. | +| Extra hours and payments | Check eligibility and rates, submit or withdraw pending requests, record coordinator decisions, settle through the wallet or Stripe Checkout, or defer to the next installment. Students can see attempts, retry checkout, and download receipts or deferral confirmations. Staff can review cancellations and refunds. | | Graduation | Draft and review term-by-term graduation plans, record decisions, and submit and review exit-exam requests. | | Financial administration | Search financial records, filter by settlement status and date, export matching rows, and handle cancellation or refund requests. | | Calendar and reminders | View deadlines, connect or disconnect Google Calendar, sync processed timetable changes, receive workflow notifications and deadline reminders, and trigger probation warnings from semester standings. | @@ -153,13 +146,21 @@ export function filterSlotChanges(requests, filters, coordinator = false) { } ~~~ -### 5. Enable checkout with a sandbox key -The Express service checks for a test-mode key before it calls Stripe. [Source](apps/api/src/services/stripe-checkout.js#L3) +### 5. Validate preferred scheduling days + +The parser converts ordered weekdays into ranked preferences and catches duplicates. [Source](apps/web/src/preference-inputs.js#L3) ~~~js -export function stripeCheckoutConfigured() { - return /^sk_test_\w+$/.test(process.env.STRIPE_SECRET_KEY || ""); +export function parseDays(value) { + const names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; + const days = value.split(",").map(item => item.trim()).filter(Boolean).map(day => { + const name = names.find(name => name.toLowerCase() === day.toLowerCase()); + if (!name) throw new Error(`Unknown weekday: ${day}. Use a full name such as Monday.`); + return name; + }); + if (new Set(days).size !== days.length) throw new Error("Remove duplicate weekday entries."); + return days.map((day, index) => ({ day, priority: index + 1 })); } ~~~ @@ -177,7 +178,7 @@ Install **Git, Node.js 22.12 or later with npm, MongoDB Community 8.x, and Mongo node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" ~~~ - Paste the generated value into `JWT_SECRET` in your local `.env`. Keep `MONGODB_URI=mongodb://127.0.0.1:27017/bobos?replicaSet=rs0` (the example default) for the steps below. + Paste the generated value into `JWT_SECRET` in your local `.env`. For a fresh local assessment, set `MONGODB_URI=mongodb://127.0.0.1:27017/bobos_evaluation?replicaSet=rs0` in the same file. 2. Start a local MongoDB replica set. Keep this terminal running. If a MongoDB service already uses port 27017, use that replica set or stop the local service before running a second server on the same port. @@ -186,39 +187,34 @@ Install **Git, Node.js 22.12 or later with npm, MongoDB Community 8.x, and Mongo mongod --replSet rs0 --dbpath .mongodb-data --bind_ip 127.0.0.1 ~~~ -3. In a second terminal, initialize that replica set once, then start the portal and API from the Bobos folder. + +3. In a second terminal, initialize the replica set once. Run both data setup commands in the repository with the same local database. ~~~powershell mongosh --host 127.0.0.1 --eval "rs.initiate({_id:'rs0',members:[{_id:0,host:'127.0.0.1:27017'}]})" - npm run dev + npm run seed:evaluation --workspace @bobos/api + npm run seed:b1 --workspace @bobos/api ~~~ - Open [the portal](http://localhost:5173/) and check [API health](http://localhost:3000/api/health). The health response should include `"database":"connected"`. The frontend proxies `/api` requests locally. Sign in with your university email and password. + The first command that loads data prints the sign-in credentials and creates the curriculum, terms, ten elective courses and the required advising and staff accounts. The second adds the normal-student cohort, processed schedules, pending requests, swaps and financial history. The scripts preserve existing collections. [Assessment accounts and workflows](docs/b1-seed.md) -4. On a **fresh local demo database**, open a third terminal in Bobos to load sample academic data and create the demo accounts. Keep `ALLOW_DEMO_SEED=true` in your local `.env` for this step. +4. Start Portal and the API from the repository root. ~~~powershell - $env:BOBOS_PORTAL_DEMO='standard' - npm run seed --workspace @bobos/api - Invoke-RestMethod -Method Post http://localhost:3000/api/identity/seed-demo | Out-Null - npm run seed:group4 --workspace @bobos/api + npm run dev ~~~ - The base seed clears user, student, course, term, and offering collections in the configured database. `seed:group4` replaces the active timetable of the two demo student accounts. Use the sample accounts and database for this recipe. See the [B1 fixture guide](docs/b1-seed.md) for more request-history scenarios and the [configuration template](.env.example) for SMTP, Stripe sandbox, and Google Calendar settings. + Open [Portal](http://localhost:5173/) and confirm [API health](http://localhost:3000/api/health) reports `"database":"connected"`. Sign in with the university email and password for the role you need. - If you use Bash, set `export BOBOS_PORTAL_DEMO=standard` before the base seed and run `curl -X POST http://localhost:3000/api/identity/seed-demo` in place of `Invoke-RestMethod`. +### Deployment configuration -### Optional integrations - -| Integration | Local setup | +| Integration | Configuration | | --- | --- | -| Email | Set the SMTP values in `.env` to send OTP codes. To test probation warning emails in development, also set `PROBATION_WARNINGS_ENABLED=true`. See the [authentication guide](docs/authentication.md). | -| Stripe | Set `STRIPE_SECRET_KEY` to a sandbox key and `WEB_ORIGIN` to the portal origin. Use a Stripe test card through **Pay by card**. | -| Google Calendar | Set `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `GOOGLE_REDIRECT_URI`. Register `http://localhost:3000/api/calendar/oauth/callback` in Google Cloud for the default ports. Generate a separate 32-byte hex value for `CALENDAR_TOKEN_ENCRYPTION_KEY`. Sign in as a student and open **Calendar sync**. | - -For more advising data, run `npm run seed:evaluation --workspace @bobos/api` on a separate local demo database. If you need the dedicated extra-hours payment scenarios, set `EXTRA_HOURS_DEMO_URI` to `mongodb://127.0.0.1:27017/extra_hours_manual?replicaSet=rs0` and run `node scripts/seed-extra-hours-demo.mjs`. To view these accounts, point the local API's `MONGODB_URI` at that database and restart the API, then enter the fixture credentials on the sign-in screen. +| Email | Configure the SMTP sender and provider settings. See the [authentication guide](docs/authentication.md). | +| Card payments | Set `STRIPE_SECRET_KEY` to the deployment’s provisioned credential and set `WEB_ORIGIN` to the Portal origin. | +| Google Calendar | Configure `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `GOOGLE_REDIRECT_URI` and a separate 32-byte hex `CALENDAR_TOKEN_ENCRYPTION_KEY`. Register `http://localhost:3000/api/calendar/oauth/callback` for the default local ports. | -For a static frontend build, run `npm run build`. If frontend and API run on different hosts, set `VITE_API_BASE_URL` at build time to the API origin and `WEB_ORIGIN` on the server to the frontend origin. The API start command is `npm run start --workspace @bobos/api`. +For a static frontend build, run `npm run build`. If the frontend and API run on different hosts, set `VITE_API_BASE_URL` at build time to the API origin and `WEB_ORIGIN` on the server to the frontend origin. Start the API with `npm run start --workspace @bobos/api`. ## API reference @@ -254,29 +250,30 @@ npm run test:regression | Test | What it verifies | Evidence | | --- | --- | --- | -| Login, password reset, profile, inbox, and logout | A student receives an email code, signs in with the updated password, reads their notifications, and signs out. | [Playwright, Req 1–5](tests/browser/portal.spec.mjs#L88) | -| Student directory | Staff search for a matching student and update the student's account status. | [Playwright, Req 6–10](tests/browser/portal.spec.mjs#L176) | -| Staff extra-hours review | Staff open the review dialog, record a decision, and withdraw a pending request when allowed. | [Playwright, Extra-hours staff review](tests/browser/portal.spec.mjs#L568) | -| Deferred payment confirmation and cancellation | A student confirms the installment charge, downloads the confirmation PDF, and the charge goes through cancellation. | [Playwright, Req 92, 94, 102, and 120](tests/browser/portal.spec.mjs#L652) | +| Login, password reset, profile, inbox, and logout | A student receives an email code, signs in with the updated password, reads their notifications, and signs out. | [Playwright, Req 1–5](tests/browser/portal.spec.mjs#L119) | +| Student directory | Staff search for a matching student and update the student's account status. | [Playwright, Req 6–10](tests/browser/portal.spec.mjs#L216) | +| Staff extra-hours review | Staff open the review dialog, record a decision, and withdraw a pending request when allowed. | [Playwright, Extra-hours staff review](tests/browser/portal.spec.mjs#L716) | +| Deferred payment confirmation and cancellation | A student confirms the installment charge, downloads the confirmation PDF, and the charge goes through cancellation. | [Playwright, Req 92, 94, 102, and 120](tests/browser/portal.spec.mjs#L850) | | Credit activation after settlement | Only paid or deferred requests add their approved hours to the available credit allowance. | [Node unit test](apps/api/src/utils/credit-allowance.test.js#L66) | -| Financial date range | Applying changes updates both date filters. Cancelling a subsequent edit preserves the applied range. | [Playwright, financial date filters](tests/browser/portal.spec.mjs#L208) | +| Financial date range | Applying changes updates both date filters. Cancelling a subsequent edit preserves the applied range. | [Playwright, financial date filters](tests/browser/portal.spec.mjs#L307) | ## How to use -Enter one of these seeded accounts on the local sign-in screen. They share the local-only password `Password123!`. -| Role | Local demo email | Start here | -| --- | --- | --- | -| Normal student | `karim.normal@student.guc.edu.eg` | **Home** or **My schedule** | -| Advising student | `layla.advising@student.guc.edu.eg` | **My advisor**, **Academic records**, or **My graduation** | -| Advisor | `sherif.advisor@guc.edu.eg` | **Advising students** or **Extra-hours requests** | -| Coordinator | `nadia.coordinator@guc.edu.eg` | **Extra-hours requests** or **Graduation review** | -| Administrator | `admin@guc.edu.eg` | **Student directory** or **Financial records** | - -1. Sign in as Karim and open **My schedule**. Select a class to view its room and group. -2. Sign out from the profile menu. Sign in as Sherif and open **Advising students**. Search for Layla by name and open **Academic records** from her row. -3. For a payment demo, load the dedicated extra-hours fixtures from **Optional integrations**. Sign in as the seeded coordinator, open **Extra-hours requests**, and review a pending request. Approve it with a response note. -4. Switch to the advising student who owns that request. Open **Extra-hours requests**, choose an available payment option, and download the receipt or installment confirmation from financial history after settlement. +Sign in with your university email and password. Your role determines which workspaces and records you can access. + +| Role | Start here | +| --- | --- | +| Normal student | **Home**, **My schedule**, or **Registered courses** | +| Advising student | **My advisor**, **Academic records**, or **My graduation** | +| Advisor | **Advising students**, **Schedule preferences**, or **Extra-hours requests** | +| Coordinator | **Pending work**, **Extra-hours requests**, or **Graduation review** | +| Administrator | **Student directory**, **Course offerings**, or **Financial records** | + +1. Open **My schedule** as a student and select a class to view its room and group. +2. Open **Advising students** as an advisor. Find an assigned student and open **Academic records**. +3. Open **Extra-hours requests** as a coordinator to review a pending request. Record your decision and response note. +4. The advising student can open the approved request, choose an available payment option, and download the receipt or installment confirmation from financial history. ## Contribute diff --git a/apps/api/src/controllers/extra-hours.controller.js b/apps/api/src/controllers/extra-hours.controller.js index 02c4cc3..ad7ee3b 100644 --- a/apps/api/src/controllers/extra-hours.controller.js +++ b/apps/api/src/controllers/extra-hours.controller.js @@ -6,6 +6,7 @@ import { AcademicTerm, Course, CourseAttempt, + CourseOffering, ExtraHoursRequest, Notification, FinancialTransaction, @@ -13,13 +14,16 @@ import { import { getWallet } from "../models/academics.js"; import { walletDelta, walletKinds } from "../models/finance.js"; import { standardCreditAllowance } from "../utils/credit-allowance.js"; +import { offeringEligibleForStudent } from "../utils/major.js"; import { notifyStudents } from "../services/student-notifications.js"; +import { canGraduateWithExtraHours } from "../services/graduation-planning.js"; import { getNextUniversityInstallment } from "../services/university-installments.js"; import { createStripeCheckout, expireStripeCheckout, getStripeCheckout, stripeCheckoutConfigured } from "../services/stripe-checkout.js"; const { Types } = mongoose; const isProbationStudent = (student) => student.academicStanding === "probation" || student.advisingReason === "probation" || student.gpa >= 3.70; +const lockStudent = (student, session) => StudentProfile.findByIdAndUpdate(student, { $inc: { __v: 1 } }, { session, timestamps: false }); async function creditHoursBefore(student, term, standardAllowance, { session, exclude } = {}) { const requests = await ExtraHoursRequest.find({ @@ -30,6 +34,74 @@ async function creditHoursBefore(student, term, standardAllowance, { session, ex return requests.reduce((total, request) => total + request.requestedHours, standardAllowance); } +async function itemizeCourses(student, courseIds, term, session, status = 404) { + // Course changes and extra-hours writes must not commit against different catalogue versions. + await Course.updateMany({ _id: { $in: courseIds } }, { $inc: { __v: 1 } }, { session, timestamps: false }); + const courses = await Course.find({ _id: { $in: courseIds }, isActive: true }).session(session).lean(); + if (courses.length !== courseIds.length) { + throw Object.assign(new Error("One or more courses were not found or are inactive."), { status }); + } + const unavailable = courses.find((course) => course.offeringSeasons?.length && !course.offeringSeasons.includes(term.season)); + if (unavailable) throw Object.assign(new Error(`${unavailable.code} is not offered in the selected term's season.`), { status: status === 404 ? 400 : status }); + if (status === 409) { + const offeringQuery = { course: { $in: courseIds }, term: term._id }; + await CourseOffering.updateMany(offeringQuery, { $inc: { __v: 1 } }, { session, timestamps: false }); + const offerings = await CourseOffering.find(offeringQuery).session(session).lean(); + const byCourse = new Map(offerings.map((offering) => [String(offering.course), offering])); + for (const course of courses) { + const offering = byCourse.get(String(course._id)); + if (!offering?.isPublished || !offeringEligibleForStudent(offering, student, course)) { + throw Object.assign(new Error(`${course.code} is unpublished or unavailable to this student in the selected term.`), { status }); + } + } + } + const relatedCourseIds = [...courseIds, ...courses.flatMap((course) => course.prerequisites || [])]; + const attempts = await CourseAttempt.find({ student: student._id, course: { $in: relatedCourseIds } }).select("course result").session(session).lean(); + const repeatedCourses = new Set(attempts.map((attempt) => String(attempt.course))); + const passedCourses = new Set(attempts.filter((attempt) => attempt.result === "passed").map((attempt) => String(attempt.course))); + return courses.map((course) => { + if (status === 409 && (passedCourses.has(String(course._id)) || (course.prerequisites || []).some((id) => !passedCourses.has(String(id))))) { + throw Object.assign(new Error(`${course.code} has already been passed or has an unmet prerequisite.`), { status }); + } + const isRepeated = repeatedCourses.has(String(course._id)); + const pricePerHour = isRepeated ? 1000 : 800; + return { course: course._id, hours: course.creditHours, isRepeated, pricePerHour, subtotal: course.creditHours * pricePerHour }; + }); +} + +async function validateCurrentApproval(request, student, session, approving = false) { + if (!student || student.studentType !== "advising" || isProbationStudent(student)) { + throw Object.assign(new Error("The student is no longer eligible for extra hours."), { status: 409 }); + } + const allowance = standardCreditAllowance(student.currentSemester); + if (!allowance) throw Object.assign(new Error("The student's standard credit allowance is unavailable."), { status: 409 }); + const term = await AcademicTerm.findById(request.term).session(session).lean(); + if (!term) throw Object.assign(new Error("The academic term for this request is unavailable."), { status: 409 }); + const lines = await itemizeCourses(student, request.courses.map((line) => line.course), term, session, 409); + const original = new Map(request.courses.map((line) => [String(line.course), line])); + const priceChanged = lines.some((line) => { + const previous = original.get(String(line.course)); + return !previous || line.hours !== previous.hours || line.isRepeated !== previous.isRepeated + || line.pricePerHour !== previous.pricePerHour || line.subtotal !== previous.subtotal; + }); + const hours = lines.reduce((sum, line) => sum + line.hours, 0); + const total = lines.reduce((sum, line) => sum + Math.round(line.subtotal * 100), 0); + if (priceChanged || Math.abs(hours - request.requestedHours) > 1e-9 || total !== Math.round(request.totalCost * 100)) { + throw Object.assign(new Error("Course credits or prices have changed. Ask the Advisor to submit an updated extra-hours request."), { status: 409 }); + } + const before = await creditHoursBefore(student._id, request.term, allowance, { session, exclude: request._id }); + const after = before + hours; + const graduating = after <= 34 && after > allowance + 3 + && await canGraduateWithExtraHours(student, request.term, lines, session); + if (after > 34 || (after > allowance + 3 && !graduating)) { + throw Object.assign(new Error("The request exceeds the student's current credit limit. The one-year graduation exception requires a feasible plan."), { status: 409 }); + } + if (!approving && request.eligibilitySnapshot.standardAllowance !== allowance) { + throw Object.assign(new Error("The student's credit allowance has changed. Ask the Advisor to submit an updated extra-hours request."), { status: 409 }); + } + return { standardAllowance: allowance, hoursBeforeRequest: before, hoursAfterRequest: after, isProbation: false, graduatingWithinOneYear: graduating }; +} + const populatedRequest = (id) => ExtraHoursRequest.findById(id) .populate({ path: "student", populate: { path: "user", select: "fullName email" } }) .populate("advisor", "fullName email") @@ -73,7 +145,6 @@ export async function createExtraHoursRequest(req, res) { studentId, termId, courseIds, - graduatingWithinOneYear, } = req.body; if (!studentId) { @@ -129,79 +200,44 @@ export async function createExtraHoursRequest(req, res) { }); } - // Rule 1: Probation check - // On the GUC scale, GPA 3.70 or above is probation. - const isProbation = isProbationStudent(student); - - if (isProbation) { - return res.status(400).json({ - message: "Probation students cannot receive extra credit hours.", - }); - } - - // Rule 2: Standard credit allowance - const standardAllowance = standardCreditAllowance(student.currentSemester); - if (!standardAllowance) { - return res.status(400).json({ - message: `Standard credit allowance is not configured for semester ${student.currentSemester}.`, - }); - } - - // Determine graduation status: - // If explicitly provided in the request body, use it; otherwise infer from semester >= 9. - const isGraduating = typeof graduatingWithinOneYear === "boolean" - ? graduatingWithinOneYear - : Boolean(student.currentSemester >= 9); - // Rule 3: Validate requested courses and calculate repeated vs new rates const validCourseObjectIds = courseIds.filter((id) => Types.ObjectId.isValid(id)); if (validCourseObjectIds.length !== courseIds.length) { return res.status(400).json({ message: "One or more course IDs are invalid." }); } - const courses = await Course.find({ _id: { $in: validCourseObjectIds }, isActive: true }); - if (courses.length !== courseIds.length) { - return res.status(404).json({ message: "One or more courses were not found or are inactive." }); - } - - // Check course attempt history for this student to determine repeated courses - const studentAttempts = await CourseAttempt.distinct("course", { - student: student._id, - course: { $in: validCourseObjectIds }, - }); - const repeatedCourseIds = new Set(studentAttempts.map(String)); - - const itemizedCourses = courses.map((course) => { - const isRepeated = repeatedCourseIds.has(String(course._id)); - const pricePerHour = isRepeated ? 1000 : 800; - const hours = Number(course.creditHours); - const subtotal = hours * pricePerHour; - return { - course: course._id, - hours, - isRepeated, - pricePerHour, - subtotal, - }; - }); - - const requestedHours = itemizedCourses.reduce((sum, item) => sum + item.hours, 0); - const totalCost = itemizedCourses.reduce((sum, item) => sum + item.subtotal, 0); - const requestId = await mongoose.connection.transaction(async (session) => { // Submissions and approvals for the same student share this write lock. - const locked = await StudentProfile.updateOne({ _id: student._id }, { $inc: { __v: 1 } }, { session, timestamps: false }); - if (!locked.matchedCount) throw Object.assign(new Error("Student profile not found."), { status: 404 }); + const currentStudent = await lockStudent(student._id, session); + if (!currentStudent) throw Object.assign(new Error("Student profile not found."), { status: 404 }); + if (currentStudent.studentType !== "advising") throw Object.assign(new Error("Extra hours can only be requested for advising students."), { status: 400 }); + if (req.user.role === "advisor" && !currentStudent.assignedAdvisor?.equals(req.user._id)) { + throw Object.assign(new Error("You can only request extra hours for your assigned students."), { status: 403 }); + } + if (isProbationStudent(currentStudent)) { + throw Object.assign(new Error("Probation students cannot receive extra credit hours."), { status: 400 }); + } + const standardAllowance = standardCreditAllowance(currentStudent.currentSemester); + if (!standardAllowance) { + throw Object.assign(new Error(`Standard credit allowance is not configured for semester ${currentStudent.currentSemester}.`), { status: 400 }); + } const pending = await ExtraHoursRequest.findOne(pendingRequestQuery).select("_id").session(session).lean(); if (pending) { throw Object.assign(new Error(duplicateMessage), { status: 400, existingRequestId: pending._id }); } + const currentTerm = await AcademicTerm.findById(term._id).session(session).lean(); + if (!currentTerm) throw Object.assign(new Error("Academic term not found."), { status: 404 }); + const itemizedCourses = await itemizeCourses(currentStudent, validCourseObjectIds, currentTerm, session); + const requestedHours = itemizedCourses.reduce((sum, item) => sum + item.hours, 0); + const totalCost = itemizedCourses.reduce((sum, item) => sum + item.subtotal, 0); const hoursBeforeRequest = await creditHoursBefore(student._id, term._id, standardAllowance, { session }); const hoursAfterRequest = hoursBeforeRequest + requestedHours; if (hoursAfterRequest > 34) { throw Object.assign(new Error(`Total credit hours (${hoursAfterRequest}) cannot exceed the 34-hour university maximum.`), { status: 400 }); } + const isGraduating = hoursAfterRequest > standardAllowance + 3 + && await canGraduateWithExtraHours(currentStudent, term._id, itemizedCourses, session); if (!isGraduating && hoursAfterRequest > standardAllowance + 3) { throw Object.assign(new Error(`A student not graduating within one year may add at most 3 hours above standard allowance (${standardAllowance} standard + 3 max extra = ${standardAllowance + 3}). This request would bring the total to ${hoursAfterRequest} hours.`), { status: 400 }); } @@ -343,19 +379,8 @@ export async function decideExtraHoursRequest(req, res) { if (request.decisionStatus !== "pending") throw Object.assign(new Error("Only pending requests can be decided."), { status: 409 }); if (decision === "approved") { // Updating the student serializes approvals that share a credit limit. - const student = await StudentProfile.findByIdAndUpdate(request.student, { $inc: { __v: 1 } }, { session }); - if (!student || student.studentType !== "advising" || isProbationStudent(student)) { - throw Object.assign(new Error("The student is no longer eligible for extra hours."), { status: 409 }); - } - const allowance = standardCreditAllowance(student.currentSemester); - if (!allowance) throw Object.assign(new Error("The student's standard credit allowance is unavailable."), { status: 409 }); - const before = await creditHoursBefore(student._id, request.term, allowance, { session, exclude: request._id }); - const after = before + request.requestedHours; - const limit = request.eligibilitySnapshot.graduatingWithinOneYear ? 34 : Math.min(34, allowance + 3); - if (after > limit) throw Object.assign(new Error(`Approval would exceed the student's ${limit}-hour limit.`), { status: 409 }); - request.eligibilitySnapshot.standardAllowance = allowance; - request.eligibilitySnapshot.hoursBeforeRequest = before; - request.eligibilitySnapshot.hoursAfterRequest = after; + const student = await lockStudent(request.student, session); + request.eligibilitySnapshot = await validateCurrentApproval(request, student, session, true); } request.decisionStatus = decision; request.decisionNote = responseNote.trim(); @@ -396,6 +421,7 @@ export async function listAdvisorExtraHoursRequests(req, res) { /** Req. 91, 93: Pay or retry through hosted card checkout. */ const pendingStripe = { kind: "gatewayPayment", status: "pending", "metadata.stripeCheckout": true }; +const checkoutStatus = (transaction) => transaction.status === "REFUNDED" ? "refunded" : transaction.status; function settlementRequest(request) { if (!request) throw Object.assign(new Error("Extra-hours request not found."), { status: 404 }); @@ -419,13 +445,44 @@ async function reconcileStripeCheckout(attempt, checkout, declinedBeforeClosing try { return await session.withTransaction(async () => { const transaction = await FinancialTransaction.findById(attempt.id).session(session); - if (transaction.status !== "pending") return transaction.status; + if (transaction.status !== "pending") return checkoutStatus(transaction); const request = await ExtraHoursRequest.findById(transaction.extraHoursRequest).session(session); settlementRequest(request); transaction.status = status; transaction.occurredAt = new Date(); if (paid) { transaction.transactionReference = checkout.payment_intent?.id || checkout.id; + try { + const student = await lockStudent(request.student, session); + request.eligibilitySnapshot = await validateCurrentApproval(request, student, session); + } catch (error) { + if (error.status !== 409) throw error; + // Stripe already captured the payment. Compensate in the wallet, using the same + // ledger semantics as a staff refund, and preserve the provider reference. + const refundReason = error.message; + transaction.status = "REFUNDED"; + transaction.refundedAt = transaction.occurredAt; + transaction.refundReason = refundReason; + const [refund] = await FinancialTransaction.create([{ + student: transaction.student, extraHoursRequest: request._id, relatedTransaction: transaction._id, + kind: "refund", type: "REFUND", status: "succeeded", settlementOption: "wallet", + amount: transaction.amount, currency: transaction.currency, + transactionReference: `REF-${transaction._id}`, refundedAt: transaction.refundedAt, + refundReason, idempotencyKey: `extra-hours:${transaction._id}:checkout-refund`, + }], { session }); + request.settlementStatus = "refunded"; + request.settlementOption = "gateway"; + request.history.push({ action: "refunded", actor: attempt.metadata.actor, note: refundReason, + settlementOption: "gateway", settlementStatus: "refunded", amount: transaction.amount }); + await transaction.save({ session }); + await request.save({ session }); + await notifyStudents({ _id: request.student, studentType: "advising" }, { + type: "refundIssued", title: "Extra-hours refund issued", + message: `${refund.amount} ${refund.currency} was refunded to your wallet.`, + relatedModel: "FinancialTransaction", relatedId: refund._id, + }, session); + return "refunded"; + } request.settlementStatus = "paid"; request.settlementOption = "gateway"; } @@ -452,6 +509,8 @@ async function reserveStripeCheckout(id, student, actor) { const request = await ExtraHoursRequest.findOne({ _id: id, student }).session(session); settlementRequest(request); const existing = await FinancialTransaction.findOne({ ...pendingStripe, extraHoursRequest: id }).session(session); + if (existing?.metadata.stripeSessionId) return existing; + await validateCurrentApproval(request, await lockStudent(student, session), session); if (existing) return existing; // Serialize checkout starts with wallet payments and installment deferrals. await ExtraHoursRequest.updateOne({ _id: id }, { $inc: { __v: 1 } }, { session }); @@ -476,8 +535,28 @@ export async function startExtraHoursCheckout(req, res) { if (attempt.metadata.stripeSessionId) { const existing = await getStripeCheckout(attempt.metadata.stripeSessionId); const status = await reconcileStripeCheckout(attempt, existing); - if (status === "pending") return res.json({ checkoutUrl: existing.url }); - if (status === "succeeded") return res.json({ status }); + if (status === "pending") { + // An existing provider session can remain open after a catalogue change. + try { + await mongoose.connection.transaction(async (session) => { + const request = await ExtraHoursRequest.findById(attempt.extraHoursRequest).session(session); + settlementRequest(request); + await validateCurrentApproval(request, await lockStudent(profile.id, session), session); + }); + } catch (error) { + if (error.status !== 409) throw error; + try { + await expireStripeCheckout(existing.id); + } catch (expireError) { + if (expireError.stripeStatus !== 400) throw expireError; + } + const statusAfterExpiry = await reconcileStripeCheckout(attempt, await getStripeCheckout(existing.id)); + if (statusAfterExpiry === "succeeded" || statusAfterExpiry === "refunded") return res.json({ status: statusAfterExpiry }); + throw error; + } + return res.json({ checkoutUrl: existing.url }); + } + if (status === "succeeded" || status === "refunded") return res.json({ status }); attempt = await reserveStripeCheckout(req.params.id, profile.id, req.user._id); } let checkout; @@ -516,7 +595,7 @@ export async function checkExtraHoursCheckout(req, res) { ...(attemptId && { _id: attemptId }), }).sort({ createdAt: -1, _id: -1 }); if (!attempt) return res.status(404).json({ message: "No Stripe checkout found." }); - if (attempt.status !== "pending" || !attempt.metadata.stripeSessionId) return res.json({ status: attempt.status }); + if (attempt.status !== "pending" || !attempt.metadata.stripeSessionId) return res.json({ status: checkoutStatus(attempt) }); let checkout = await getStripeCheckout(attempt.metadata.stripeSessionId); const declinedBeforeClosing = Boolean(checkout.payment_intent?.last_payment_error); if (req.body?.cancel === true && checkout.status === "open") { @@ -570,6 +649,7 @@ export async function chooseExtraHoursSettlement(req, res) { if (await FinancialTransaction.exists({ ...pendingStripe, extraHoursRequest: id }).session(session)) { throw Object.assign(new Error("Finish or cancel the open Stripe checkout first."), { status: 409 }); } + request.eligibilitySnapshot = await validateCurrentApproval(request, await lockStudent(profile._id, session), session); let transaction; if (option === "deferred") { const installment = await getNextUniversityInstallment(profile._id, request.term, session); @@ -586,8 +666,6 @@ export async function chooseExtraHoursSettlement(req, res) { request.history.push({ action: "deferred", actor: req.user._id, note: `Deferred to ${installment.label}.`, settlementOption: "deferred", settlementStatus: "deferred", amount: request.totalCost }); } else if (option === "now") { if (method !== "wallet") throw Object.assign(new Error("Open Stripe Checkout for card payments."), { status: 400 }); - // Payments for different requests share one wallet. - await StudentProfile.updateOne({ _id: profile._id }, { $inc: { __v: 1 } }, { session }); const entries = await FinancialTransaction.find({ student: profile._id, kind: { $in: walletKinds } }).session(session).select("kind amount status").lean(); const balance = entries.reduce((sum, txn) => sum + walletDelta(txn), 0); if (balance < Math.round(request.totalCost * 100)) throw Object.assign(new Error("Your wallet balance is not sufficient for this payment."), { status: 409 }); diff --git a/apps/api/src/controllers/extra-hours.integration.test.js b/apps/api/src/controllers/extra-hours.integration.test.js index 3cdb7c9..2472703 100644 --- a/apps/api/src/controllers/extra-hours.integration.test.js +++ b/apps/api/src/controllers/extra-hours.integration.test.js @@ -10,6 +10,7 @@ import { AcademicTerm, Course, CourseAttempt, + CourseOffering, ExtraHoursRequest, FinancialTransaction, Notification, @@ -125,11 +126,12 @@ before(async () => { // Course 2: 2 credit hours // Course 3: 4 credit hours const [c1, c2, c3] = await Course.create([ - { code: "CSEN501", name: "Databases I", creditHours: 3, courseType: "core", facultyMajors: ["CS"], recommendedSemester: 5, offeringSeasons: ["winter"] }, + { code: "CSEN501", name: "Databases I", creditHours: 3, courseType: "core", facultyMajors: ["CS"], recommendedSemester: 5, offeringSeasons: ["winter", "spring", "summer"] }, { code: "CSEN502", name: "Networks", creditHours: 2, courseType: "core", facultyMajors: ["CS"], recommendedSemester: 5, offeringSeasons: ["winter"] }, { code: "CSEN503", name: "Advanced Algorithms", creditHours: 4, courseType: "core", facultyMajors: ["CS"], recommendedSemester: 5, offeringSeasons: ["winter"] }, ]); courses = [c1, c2, c3]; + await publishCourse(c1, term); // Mark Course 1 as attempted/failed previously by regular student so it's a "repeated" course await CourseAttempt.create({ @@ -143,6 +145,15 @@ before(async () => { }); }); +function publishCourse(course, term) { + return CourseOffering.create({ + course: course._id, term: term._id, isPublished: true, + instructors: [{ fullName: "Test instructor" }], eligibleGroups: [{ major: "CS" }], + slots: [{ componentType: "lecture", groupNumber: "1", day: "Monday", + startMinute: 480, endMinute: 540, room: "Test room", capacity: 20 }], + }); +} + after(async () => { if (server) await new Promise((resolve) => server.close(resolve)); await mongoose.disconnect(); @@ -267,21 +278,38 @@ test("Req 83: Non-graduating student cannot request more than 3 extra hours", as test("Req 83: Graduating student can request more than 3 extra hours up to 34 total", async () => { await ExtraHoursRequest.deleteMany({}); - // Semester 5 standard is 30. Adding 4 credits = 34 total. - // Allowed when graduatingWithinOneYear = true. + const day = 86400000; + const start = Date.now() + 30 * day; + const upcoming = await AcademicTerm.create({ + code: "REQ83-W", season: "winter", academicYear: "2030/2031", termStart: start, termEnd: start + 70 * day, + teachingStart: start, teachingEnd: start + 65 * day, registrationStart: start - 10 * day, registrationEnd: start, + advisingDeadline: start - day, wholeScheduleSwapDeadline: start - day, + }); + await CourseOffering.insertMany(courses.map((course, index) => ({ + course: course._id, term: upcoming._id, isPublished: true, + instructors: [{ fullName: "Test instructor" }], eligibleGroups: [{ major: "CS" }], + slots: [{ componentType: "lecture", groupNumber: "1", day: "Monday", + startMinute: 480 + 60 * index, endMinute: 540 + 60 * index, room: "Test room", capacity: 20 }], + }))); + const electives = await Course.create(Array.from({ length: 4 }, (_, i) => ({ + code: `EL83-${i}`, name: `Completed elective ${i}`, courseType: "elective", creditHours: 4, facultyMajors: ["CS"], + }))); + await CourseAttempt.insertMany(electives.map((course) => ({ + student: profiles.regular._id, course: course._id, term: term._id, result: "passed", attendance: "attended", grade: "A", + }))); const res = await apiCall("/extra-hours", { - method: "POST", - userRole: "advisor", - body: { - studentId: String(profiles.regular._id), - courseIds: [String(courses[2]._id)], // 4 credits - graduatingWithinOneYear: true, - }, + method: "POST", userRole: "advisor", + body: { studentId: String(profiles.regular._id), termId: String(upcoming._id), courseIds: [String(courses[2]._id)] }, }); - assert.equal(res.status, 201); + assert.equal(res.status, 201, res.body.message); assert.equal(res.body.requestedHours, 4); assert.equal(res.body.eligibilitySnapshot.hoursAfterRequest, 34); + assert.equal(res.body.eligibilitySnapshot.graduatingWithinOneYear, true); + const approved = await apiCall(`/extra-hours/${res.body._id}/decision`, { + method: "POST", userRole: "coordinator", body: { decision: "approved", responseNote: "Verified curriculum fit." }, + }); + assert.equal(approved.status, 200, approved.body.message); }); test("Req 83: Probation students cannot receive extra credit hours", async () => { @@ -354,6 +382,7 @@ test("Req 117 delivers extra-hours decisions, payment outcomes, deferred charges const [walletTerm, deferredTerm] = await Promise.all([ alternateTerm("EH-WALLET", "spring"), alternateTerm("EH-DEFERRED", "summer"), ]); + await Promise.all([publishCourse(courses[0], walletTerm), publishCourse(courses[0], deferredTerm)]); const submit = async (termId) => { const response = await apiCall("/extra-hours", { method: "POST", diff --git a/apps/api/src/controllers/group-a.audit.test.js b/apps/api/src/controllers/group-a.audit.test.js index 2949cec..655fd65 100644 --- a/apps/api/src/controllers/group-a.audit.test.js +++ b/apps/api/src/controllers/group-a.audit.test.js @@ -50,13 +50,14 @@ beforeEach(async () => { { code: "ABASE502", name: "Base course", creditHours: 4, courseType: "core", facultyMajors: ["CS"], offeringSeasons: ["winter", "spring", "summer"] }, ]); await Promise.all(courses.map((course, index) => publishFixture(course, index))); + await publishFixture(courses[0], 0, terms[1]); const electives = await Course.create(Array.from({ length: 4 }, (_, index) => ({ code: `AELEC${index}`, name: "Completed elective", creditHours: 4, courseType: "elective", facultyMajors: ["CS"] }))); await CourseAttempt.insertMany(electives.map((course) => ({ student: student._id, course: course._id, term: past._id, result: "passed", attendance: "attended", grade: "A" }))); }); -function publishFixture(course, index = 2) { +function publishFixture(course, index = 2, term = terms[0]) { const startMinute = 480 + index * 60; return CourseOffering.create({ - course: course._id, term: terms[0]._id, isPublished: true, + course: course._id, term: term._id, isPublished: true, instructors: [{ fullName: "Fixture Instructor" }], eligibleGroups: [{ major: "CS" }], slots: [{ componentType: "lecture", groupNumber: "1", day: "Monday", startMinute, endMinute: startMinute + 60, room: "Fixture room", capacity: 20 }], }); @@ -208,6 +209,95 @@ test("A1 Req 91, 93-94: Stripe checkout retries and only verified payment produc assert.equal((await call(receiptPath, { role: "otherStudent" })).status, 404); }); +test("Req 83 and 87: a graduation assertion cannot bypass the academic credit limit", async () => { + await Course.insertMany(Array.from({ length: 16 }, (_, index) => ({ + code: `CLEARWIN${index}`, name: `Remaining course ${index}`, creditHours: 4, + courseType: "core", facultyMajors: ["CS"], offeringSeasons: ["winter"], + }))); + const course = courses[1]; + const result = await call("/extra-hours", { role: "advisor", method: "POST", body: { + ...requestBody(), courseIds: [course.id], graduatingWithinOneYear: true, + } }); + assert.equal(result.status, 400); + assert.match(result.data.message, /at most 3 hours/i); + const legacy = await extra({ + courses: [{ course: course.id, hours: 4, pricePerHour: 800, subtotal: 3200, isRepeated: false }], + requestedHours: 4, totalCost: 3200, + eligibilitySnapshot: { standardAllowance: 30, hoursBeforeRequest: 30, hoursAfterRequest: 34, isProbation: false, graduatingWithinOneYear: true }, + }); + assert.equal((await decide(legacy, { decision: "approved", responseNote: "Confirm" })).status, 409); + assert.equal((await ExtraHoursRequest.findById(legacy.id)).decisionStatus, "pending"); +}); + +test("Req 87: current credits, term availability and repeat pricing gate coordinator approval", async () => { + const request = await extra(); + const approve = () => decide(request, { decision: "approved", responseNote: "Confirm" }); + await Course.updateOne({ _id: courses[0]._id }, { creditHours: 2 }); + let response = await approve(); + assert.equal(response.status, 409); + assert.match(response.data.message, /credits or prices have changed/); + await Course.updateOne({ _id: courses[0]._id }, { creditHours: 3 }); + await CourseOffering.updateOne({ course: courses[0]._id, term: terms[0]._id }, { isPublished: false }); + response = await approve(); + assert.equal(response.status, 409); + assert.match(response.data.message, /unpublished/); + await CourseOffering.deleteOne({ course: courses[0]._id, term: terms[0]._id }); + response = await approve(); + assert.equal(response.status, 409); + assert.match(response.data.message, /unavailable/); + await publishFixture(courses[0], 0); + await CourseAttempt.create({ student: student._id, course: courses[0]._id, term: past._id, result: "failed", attendance: "attended", grade: "F" }); + response = await approve(); + assert.equal(response.status, 409); + assert.match(response.data.message, /credits or prices have changed/); + assert.equal((await ExtraHoursRequest.findById(request.id)).decisionStatus, "pending"); +}); + +test("Req 91–92: stale approval cannot debit a wallet, defer a charge or open Stripe checkout", async (t) => { + mockStripeCheckout(t); + const request = await extra({ decisionStatus: "approved", settlementStatus: "awaitingChoice" }); + await FinancialTransaction.create({ student: student._id, kind: "walletTopUp", amount: 3000, status: "succeeded" }); + await Course.updateOne({ _id: courses[0]._id }, { creditHours: 2 }); + const results = await Promise.all([ + settle(request, { option: "now", method: "wallet" }), + settle(request, { option: "deferred" }), + call(`/extra-hours/${request.id}/checkout`, { role: "student", method: "POST", body: {} }), + ]); + assert.ok(results.every(({ status, data }) => status === 409 && /credits or prices have changed/.test(data.message))); + await Course.updateOne({ _id: courses[0]._id }, { creditHours: 3 }); + await CourseOffering.deleteOne({ course: courses[0]._id, term: terms[0]._id }); + const missingOffering = await settle(request, { option: "deferred" }); + assert.equal(missingOffering.status, 409); + assert.match(missingOffering.data.message, /unavailable/); + assert.equal((await getWallet(student._id)).balance, 3000); + assert.equal(await FinancialTransaction.countDocuments({ extraHoursRequest: request.id }), 0); + assert.equal(await UniversityInstallment.countDocuments(), 0); + assert.equal((await ExtraHoursRequest.findById(request.id)).settlementStatus, "awaitingChoice"); +}); + +test("Req 91: Stripe capture after a course change produces one wallet credit across simultaneous confirmations", async (t) => { + const stripe = mockStripeCheckout(t); + const request = await extra({ decisionStatus: "approved", settlementStatus: "awaitingChoice" }); + const checkout = (suffix = "") => call(`/extra-hours/${request.id}/checkout${suffix}`, { role: "student", method: "POST", body: {} }); + assert.equal((await checkout()).status, 201); + await Course.updateOne({ _id: courses[0]._id }, { creditHours: 2 }); + stripe.pay(); + const results = await Promise.all([checkout("/check"), checkout("/check")]); + assert.deepEqual(results.map(({ data }) => data.status), ["refunded", "refunded"]); + assert.equal((await checkout("/check")).data.status, "refunded"); + const capture = await FinancialTransaction.findOne({ extraHoursRequest: request.id, kind: "gatewayPayment" }); + assert.equal(capture.status, "REFUNDED"); + assert.equal(capture.transactionReference, "pi_receipt"); + const refunded = await FinancialTransaction.find({ extraHoursRequest: request.id, kind: "refund" }); + assert.equal(refunded.length, 1); + assert.equal(String(refunded[0].relatedTransaction), capture.id); + assert.equal((await getWallet(student._id)).balance, 2400); + const state = await ExtraHoursRequest.findById(request.id).populate("courses.course", "creditHours").lean(); + assert.equal(state.settlementStatus, "refunded"); + assert.equal(calculateDraftCreditPolicy(student, [state]).approvedExtraHours, 0); + assert.equal(await Notification.countDocuments({ recipient: users.student._id, type: "refundIssued" }), 1); +}); + test("A1 Req 94: deferred confirmation download is not labelled a paid receipt", async () => { const request = await extra({ decisionStatus: "approved", settlementStatus: "awaitingChoice" }); const result = await settle(request, { option: "deferred" }); @@ -490,6 +580,7 @@ test("Req 92 and 102: distinct deferrals share the next installment and cancella }))); const requests = []; for (const course of shortCourses) { + await publishFixture(course); const created = await call("/extra-hours", { role: "advisor", method: "POST", body: { ...requestBody(), courseIds: [String(course._id)] } }); assert.equal(created.status, 201, JSON.stringify(created.data)); @@ -520,7 +611,12 @@ test("Req 92 and 102: distinct deferrals share the next installment and cancella }); test("Req 92 and 94: existing outstanding charges gain a reusable installment link without changing amounts", async () => { - const request = await extra({ decisionStatus: "approved", settlementStatus: "deferred", settlementOption: "deferred" }); + const legacyCourse = await Course.create({ code: "LEGACY-OLD", name: "Existing course", creditHours: 2, courseType: "core", facultyMajors: ["CS"] }); + const request = await extra({ + courses: [{ course: legacyCourse.id, hours: 2, pricePerHour: 800, subtotal: 1600, isRepeated: false }], + requestedHours: 2, totalCost: 1600, decisionStatus: "approved", settlementStatus: "deferred", settlementOption: "deferred", + eligibilitySnapshot: { standardAllowance: 30, hoursBeforeRequest: 30, hoursAfterRequest: 32, isProbation: false, graduatingWithinOneYear: false }, + }); const old = await FinancialTransaction.create({ student: student._id, extraHoursRequest: request._id, kind: "deferredCharge", status: "PENDING", amount: request.totalCost, settlementOption: "deferred", installment: "Next installment", @@ -534,7 +630,12 @@ test("Req 92 and 94: existing outstanding charges gain a reusable installment li assert.equal(upgraded.installment, old.installment); assert.equal(await UniversityInstallment.countDocuments({ student: student._id, term: terms[0]._id }), 1); - const next = await extra({ decisionStatus: "approved", settlementStatus: "awaitingChoice" }); + const course = await Course.create({ code: "LEGACY-INST", name: "Next installment course", creditHours: 1, courseType: "core", facultyMajors: ["CS"] }); + await publishFixture(course); + const next = await extra({ + courses: [{ course: course.id, hours: 1, pricePerHour: 800, subtotal: 800, isRepeated: false }], + requestedHours: 1, totalCost: 800, decisionStatus: "approved", settlementStatus: "awaitingChoice", + }); const settled = await settle(next, { option: "deferred" }); assert.equal(settled.status, 200); assert.equal(settled.data.transaction.installmentId, String(upgraded.installmentId)); diff --git a/apps/api/src/controllers/scheduling.controller.js b/apps/api/src/controllers/scheduling.controller.js index de39a20..9fcc305 100644 --- a/apps/api/src/controllers/scheduling.controller.js +++ b/apps/api/src/controllers/scheduling.controller.js @@ -8,7 +8,7 @@ import { ScheduleActivity } from "../models/communications.js"; import { loadStudentWorkflows } from "../services/student-workflow-status.js"; import { notifyStudents } from "../services/student-notifications.js"; import { calculateDraftCreditPolicy } from "../utils/credit-allowance.js"; -import { majorMatches } from "../utils/major.js"; +import { majorMatches, offeringEligibleForStudent } from "../utils/major.js"; import { buildWeeklyCalendar } from "../../../../server/src/utils/weeklyCalendar.js"; import { toMinutes, findFirstClash, describeSlot, slotsOverlap } from "../../../../server/src/utils/timetable.js"; import { buildRegisteredCourses } from "../../../../server/src/utils/registeredCourses.js"; @@ -616,15 +616,6 @@ function canManageAdvisingStudent(viewer, student) { return null; } -function offeringEligibleForStudent(offering, student) { - const course = offering.course; - const majorIsEligible = !course.facultyMajors?.length || course.facultyMajors.some((major) => majorMatches(major, student.major)); - return majorIsEligible && (offering.eligibleGroups || []).some((group) => - majorMatches(group.major, student.major) && (group.semester == null || Number(group.semester) === Number(student.currentSemester)) && - (!group.studyGroup || !student.studyGroup || String(group.studyGroup) === String(student.studyGroup)) - ); -} - function groupDraftOffering(offering, preferenceGroups, reservedSlots) { const byComponent = new Map(); for (const slot of offering.slots || []) { diff --git a/apps/api/src/seed/evaluation.js b/apps/api/src/seed/evaluation.js index 9a83166..1344ef0 100644 --- a/apps/api/src/seed/evaluation.js +++ b/apps/api/src/seed/evaluation.js @@ -8,9 +8,21 @@ import { StudentWorkflowState } from '../models/academics.js'; import { parseCurriculumCsv } from '../scripts/importCourses.js'; import { canonicalMajor } from '../utils/major.js'; -const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/bobos'; +const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/bobos_evaluation'; const DEVELOPMENT_PASSWORD = 'Password123!'; const CURRICULUM_URL = new URL('../scripts/courses.csv', import.meta.url); +const electiveCatalogue = [ + ['CSEN905', 'Machine Learning'], + ['CSEN906', 'Cloud Computing'], + ['CSEN907', 'Information Retrieval'], + ['CSEN908', 'Cryptography'], + ['CSEN909', 'Parallel Computing'], + ['DMET905', 'Game Development'], + ['DMET906', 'Virtual Reality'], + ['DMET907', 'Human-Computer Interaction'], + ['DMET908', 'Modelling and Rendering'], + ['DMET909', 'Interactive Media'], +]; async function upsertUser(email, fields) { let user = await User.findOne({ email }); @@ -21,6 +33,7 @@ async function upsertUser(email, fields) { } function assertLocalDatabase(uri) { + if (process.env.NODE_ENV === 'production') throw new Error('Evaluation seeding is disabled in production.'); if (process.env.EVALUATION_SEED_ALLOW_REMOTE === 'true') return; let hostname; try { @@ -81,10 +94,7 @@ async function seedTerms() { async function seedCurriculum() { const csv = await readFile(CURRICULUM_URL, 'utf8'); const { courses: curriculumCourses, mergedListings, skippedPlaceholders } = parseCurriculumCsv(csv); - const electives = []; // Only explicitly coded courses from the supplied curriculum. - const allCourses = [...curriculumCourses, ...electives]; - - for (const course of allCourses) { + for (const course of curriculumCourses) { const { prerequisites, ...fields } = course; await Course.findOneAndUpdate( { code: course.code }, @@ -93,7 +103,7 @@ async function seedCurriculum() { ); } - const idsByCode = new Map((await Course.find({ code: { $in: allCourses.map(({ code }) => code) } }, { code: 1 }).lean()) + const idsByCode = new Map((await Course.find({ code: { $in: curriculumCourses.map(({ code }) => code) } }, { code: 1 }).lean()) .map(({ code, _id }) => [code, _id])); for (const course of curriculumCourses) { await Course.updateOne( @@ -103,7 +113,16 @@ async function seedCurriculum() { ); } - return { curriculumCount: curriculumCourses.length, electiveCount: electives.length, mergedListings, skippedPlaceholders }; + // The Portal catalogue maps these named courses to its existing elective artwork. + for (const [code, name] of electiveCatalogue) { + await Course.updateOne({ code }, { $setOnInsert: { + code, name, creditHours: 4, courseType: 'elective', facultyMajors: ['CS', 'DMET'], + recommendedSemester: 9, lectureHours: 2, tutorialHours: 2, labHours: 0, + offeringSeasons: ['winter', 'spring'], isActive: true, + } }, { upsert: true, runValidators: true, setDefaultsOnInsert: true }); + } + + return { curriculumCount: curriculumCourses.length, electiveCount: electiveCatalogue.length, mergedListings, skippedPlaceholders }; } function evaluationMajors(course) { diff --git a/apps/api/src/services/graduation-planning.js b/apps/api/src/services/graduation-planning.js index 7b55759..9be54fd 100644 --- a/apps/api/src/services/graduation-planning.js +++ b/apps/api/src/services/graduation-planning.js @@ -1,7 +1,7 @@ import { CourseAttempt } from "../models/academics.js"; import { AcademicTerm, Course, CourseOffering } from "../models/catalogue.js"; import { FinancialReversalRequest, FinancialTransaction } from "../models/finance.js"; -import { ExtraHoursRequest } from "../models/requests.js"; +import { ExitExamRequest, ExtraHoursRequest } from "../models/requests.js"; import { calculateDraftCreditPolicy } from "../utils/credit-allowance.js"; import { majorMatches } from "../utils/major.js"; @@ -13,21 +13,31 @@ const idOf = (value) => String(value._id ?? value); const requiredElectiveCount = 4; const requiredElectiveHours = 16; -export async function loadGraduationContext(student, now = new Date()) { +export async function loadGraduationContext(student, now = new Date(), { session, includeTerm } = {}) { const windowEnd = new Date(now); windowEnd.setUTCFullYear(windowEnd.getUTCFullYear() + 1); const windowEndTime = windowEnd.getTime(); - const [catalogue, attempts, futureTerms] = await Promise.all([ + const read = async (queries) => { + if (!session) return Promise.all(queries); + const results = []; + for (const query of queries) results.push(await query.session(session)); + return results; + }; + const upcoming = { termStart: { $gt: now } }; + const termWindow = includeTerm + ? { $or: [upcoming, { _id: includeTerm, teachingEnd: { $gte: now } }] } + : upcoming; + const [catalogue, attempts, futureTerms] = await read([ Course.find().select("code name courseType isActive facultyMajors creditHours prerequisites offeringSeasons recommendedSemester") .sort({ recommendedSemester: 1, code: 1 }).lean(), CourseAttempt.find({ student: student._id }).select("course result term attemptNumber createdAt") .populate("term", "termStart termEnd").lean(), - AcademicTerm.find({ season: { $in: planningSeasons }, termStart: { $gt: now }, termEnd: { $lte: windowEnd } }) + AcademicTerm.find({ season: { $in: planningSeasons }, ...termWindow, termEnd: { $lte: windowEnd } }) .select("code season academicYear termStart termEnd").sort({ termStart: 1, _id: 1 }).lean(), ]); const termsBySeason = new Map(); for (const term of futureTerms) { - if (!termsBySeason.has(term.season)) termsBySeason.set(term.season, term); + if (!termsBySeason.has(term.season) || includeTerm && idOf(term) === idOf(includeTerm)) termsBySeason.set(term.season, term); } const terms = [...termsBySeason.values()]; const termIds = terms.map((term) => term._id); @@ -43,7 +53,7 @@ export async function loadGraduationContext(student, now = new Date()) { if (attempt.result !== "current") continue; const end = attempt.term?.termEnd?.getTime(); // Count a current attempt only when it can still finish in the planning year. - if (end >= Date.now() && end <= windowEndTime) current.set(courseId, end); + if (end >= now.getTime() && end <= windowEndTime) current.set(courseId, end); } const failed = new Set(attempts.filter((attempt) => attempt.result === "failed").map((attempt) => idOf(attempt.course))); const remaining = catalogue.filter((course) => { @@ -58,14 +68,14 @@ export async function loadGraduationContext(student, now = new Date()) { count: Math.max(0, requiredElectiveCount - completedElectives.length), hours: Math.max(0, requiredElectiveHours - completedElectives.reduce((sum, course) => sum + course.creditHours, 0)), }; - const [offerings, requests] = await Promise.all([ + const [offerings, requests] = await read([ CourseOffering.find({ course: { $in: remaining.map((course) => course._id) }, term: { $in: termIds } }) .select("course term isPublished").lean(), ExtraHoursRequest.find({ student: student._id, term: { $in: termIds }, decisionStatus: "approved", settlementStatus: { $in: ["paid", "deferred"] } }) .populate("courses.course", "creditHours").lean(), ]); const requestIds = requests.map((request) => request._id); - const [reversals, reversalEntries] = requestIds.length ? await Promise.all([ + const [reversals, reversalEntries] = requestIds.length ? await read([ FinancialReversalRequest.distinct("extraHoursRequest", { student: student._id, extraHoursRequest: { $in: requestIds }, status: "completed" }), FinancialTransaction.distinct("extraHoursRequest", { student: student._id, extraHoursRequest: { $in: requestIds }, kind: { $in: ["refund", "deferredChargeCancellation"] }, status: "succeeded" }), @@ -230,6 +240,42 @@ function canFitCourses(context, courses) { return search(0); } +function withoutExitExamCourse(context, course) { + return { + ...context, + electiveRequirement: course.elective ? { + count: Math.max(0, context.electiveRequirement.count - 1), + hours: Math.max(0, context.electiveRequirement.hours - course.creditHours), + } : context.electiveRequirement, + courses: context.courses.filter((item) => item._id !== course._id), + }; +} + +export async function canGraduateWithExtraHours(student, termId, lines, session) { + const context = await loadGraduationContext(student, new Date(), { session, includeTerm: termId }); + const target = context.terms.find((term) => term._id === idOf(termId)); + if (!target) return false; + const requested = new Map(lines.map((line) => [idOf(line.course), line.hours])); + const matching = context.courses.filter((course) => requested.has(course._id) + && course.termIds.includes(target._id)); + if (matching.length !== requested.size) return false; + const authorized = new Map(target.creditPolicy.approvedExtraCourses.map((course) => [course.courseId, course.hours])); + for (const [courseId, hours] of requested) authorized.set(courseId, hours); + target.creditPolicy.approvedExtraCourses = [...authorized].map(([courseId, hours]) => ({ courseId, hours })); + target.creditPolicy.maximumCreditHours = Math.min(34, target.creditPolicy.baseAllowance + + target.creditPolicy.approvedExtraCourses.reduce((sum, course) => sum + course.hours, 0)); + context.courses = context.courses.map((course) => requested.has(course._id) + ? { ...course, required: true, termIds: [target._id] } + : course); + if (canFitCourses(context, context.courses) === true) return true; + const failed = context.courses.filter((course) => course.failed); + if (failed.length !== 1 || requested.has(failed[0]._id)) return false; + const approved = await ExitExamRequest.exists({ student: student._id, course: failed[0]._id, status: "approved" }).session(session ?? null); + if (!approved) return false; + const replacement = withoutExitExamCourse(context, failed[0]); + return canFitCourses(replacement, replacement.courses) === true; +} + export function exitExamEligibility(context) { const failed = context.courses.filter((course) => course.failed); if (failed.length !== 1) return { message: "An exit exam requires exactly one remaining failed course." }; @@ -244,14 +290,8 @@ export function exitExamEligibility(context) { if (!course.termIds.length) return { course }; const fit = canFitCourses(context, context.courses); if (fit === true) return { course, message: `${course.code} can be repeated within the planning window.` }; - const replacementContext = { - ...context, - electiveRequirement: course.elective ? { - count: Math.max(0, context.electiveRequirement.count - 1), - hours: Math.max(0, context.electiveRequirement.hours - course.creditHours), - } : context.electiveRequirement, - }; - const withoutFailed = canFitCourses(replacementContext, context.courses.filter((item) => item._id !== course._id)); + const replacementContext = withoutExitExamCourse(context, course); + const withoutFailed = canFitCourses(replacementContext, replacementContext.courses); if (fit === null || withoutFailed !== true) { return { course, message: "Could not establish that the failed course alone prevents a feasible plan. Review course availability and prerequisites." }; } diff --git a/apps/api/src/utils/credit-allowance.js b/apps/api/src/utils/credit-allowance.js index ceb26f8..9560853 100644 --- a/apps/api/src/utils/credit-allowance.js +++ b/apps/api/src/utils/credit-allowance.js @@ -71,8 +71,9 @@ export function calculateDraftCreditPolicy(student, requests = []) { let approvedExtraHours = 0; if (baseAllowance != null && !probation) { const requestedHours = [...authorizedCourses.values()].reduce((sum, hours) => sum + hours, 0); - const allGraduateEligible = activeRequests.length > 0 && activeRequests.every((request) => request.eligibilitySnapshot.graduatingWithinOneYear); - const policyMaximum = allGraduateEligible ? MAXIMUM_TOTAL_HOURS - standardAllowance : 3; + // Only requests that needed a higher cumulative limit carry a verified exception. + const hasGraduateException = activeRequests.some((request) => request.eligibilitySnapshot.graduatingWithinOneYear); + const policyMaximum = hasGraduateException ? MAXIMUM_TOTAL_HOURS - standardAllowance : 3; approvedExtraHours = Math.min(requestedHours, policyMaximum, MAXIMUM_TOTAL_HOURS - standardAllowance); } diff --git a/apps/api/src/utils/major.js b/apps/api/src/utils/major.js index c36ed12..589853f 100644 --- a/apps/api/src/utils/major.js +++ b/apps/api/src/utils/major.js @@ -24,3 +24,11 @@ export function majorLabel(value) { export function majorMatches(left, right) { return canonicalMajor(left) === canonicalMajor(right); } + +export function offeringEligibleForStudent(offering, student, course = offering.course) { + const majorIsEligible = !course.facultyMajors?.length || course.facultyMajors.some((major) => majorMatches(major, student.major)); + return majorIsEligible && (offering.eligibleGroups || []).some((group) => + majorMatches(group.major, student.major) && (group.semester == null || Number(group.semester) === Number(student.currentSemester)) && + (!group.studyGroup || !student.studyGroup || String(group.studyGroup) === String(student.studyGroup)) + ); +} diff --git a/apps/web/public/portal-studio/app.js b/apps/web/public/portal-studio/app.js index 57e2bc1..7d4c720 100644 --- a/apps/web/public/portal-studio/app.js +++ b/apps/web/public/portal-studio/app.js @@ -1,6 +1,7 @@ 'use strict'; // Portal Studio with authenticated calendar and student service integrations. const workspaceSessionKey = 'bobos.token'; +const workspaceNavigationKey = 'portal-navigation-session'; function normalizePortalLocation() { const url = new URL(location.href); normalizePortalRoute(url.searchParams); @@ -65,16 +66,16 @@ async function accountRequest(path, token, method = 'GET') { function loadAccountData(refresh) { const token = localStorage.getItem(workspaceSessionKey); if (!token || authPages.has(page)) { liveProfile = liveInbox = liveAdvisor = termDirectory = coordinatorSchedules = undefined; return; } - if ((page === 'overview' || usesStaffPresentation()) && termDirectory?.token !== token) { + if (termDirectory?.token !== token) { const state = termDirectory = {token}; accountRequest('academic-terms', token).then(data => { if (termDirectory !== state) return; state.data = data; - if (page === 'overview') render(); - else updateSidebarTerm(); + updateSidebarTerm(); + if (page === 'overview') updateHomeTerm(); }).catch(() => { if (termDirectory === state) { state.error = true; updateSidebarTerm(); } }); } - if (['coordinator','advisor'].includes(role) && page === 'overview' && (refresh || coordinatorSchedules?.token !== token)) { + if (usesStaffPresentation() && page === 'overview' && (refresh || coordinatorSchedules?.token !== token)) { const state = coordinatorSchedules = {token}; accountRequest('schedules/students', token).then(data => { state.data = data; }) .catch(error => { @@ -82,6 +83,8 @@ function loadAccountData(refresh) { else state.error = error.message; }).finally(() => { if (coordinatorSchedules !== state || page !== 'overview') return; + const summary = app.querySelector('[data-schedule-summary]'); + if (summary) summary.innerHTML = staffScheduleSummary(); const region = document.querySelector('[data-schedule-folders]'); if (region) { region.innerHTML = scheduleReviewFiles(); @@ -111,8 +114,7 @@ function loadAccountData(refresh) { accountRequest('notifications', token).then(data => { state.data = data.notifications; }) .catch(error => { state.error = error.message; }).finally(() => { if (liveInbox !== state) return; - if (['notifications','overview'].includes(page)) render(); - else updateNotificationBadge(); + updateNotificationsView(); }); } } @@ -337,7 +339,7 @@ function deskCalendar() { return `
-

Academic calendar

${studentDashboard()?link('calendar-sync',icon('calendar')+'Calendar sync','btn calendar-sync-link'):''}
+

Academic calendar

${studentDashboard()?link('calendar-sync',icon('calendar')+'Sync with Google Calendar','btn calendar-sync-link'):''}
${binderRow('feet')}
${binderRow('wires')}
${calendarPage()}
@@ -376,20 +378,26 @@ function studentWeek() { const courses = studentCourses(); return Object.entries(liveStudent.data?.schedule?.week || {}).map(([day,meetings]) => [day, meetings.map(m => [m.startTime, displayStudentCode(m.courseCode), escapeHtml(`${m.type[0].toUpperCase()+m.type.slice(1)} · ${m.room}`), colors[Math.max(0,courses.findIndex(c => c[0]===displayStudentCode(m.courseCode))) % colors.length], m.endTime])]); } -function loadStudentSchedule() { +function loadStudentSchedule(refresh = false) { if (!student() || authPages.has(page)) return; const token = localStorage.getItem(workspaceSessionKey); if (!token) { liveStudent = {token:null, loading:false, error:'Sign in to view your schedule.', data:null}; return; } - if (token === liveStudent.token) return; - liveStudent = {token, loading:true, error:'', data:null}; + if (token === liveStudent.token && (!refresh || liveStudent.loading)) return; + const state = liveStudent = {token, loading:true, error:'', data:token === liveStudent.token ? liveStudent.data : null}; fetch('../api/schedules/me', {headers:{Authorization:'Bearer '+token}}).then(async response => { const data = await response.json(); if (!response.ok) throw new Error(response.status === 401 ? 'Your session has expired. Sign in again to view your schedule.' : data.message || 'Could not load your schedule.'); - if (liveStudent.token !== token) return; - liveStudent.data = data; + if (liveStudent !== state) return; + state.data = data; selectedCourse = resolveCourse(new URLSearchParams(location.search).get('course')); - }).catch(error => { if(liveStudent.token===token) liveStudent.error=error.message; }).finally(() => { - if(liveStudent.token===token) {liveStudent.loading=false; if(student()) render();} + }).catch(error => { + state.data = null; + state.error = error.message; + }).finally(() => { + state.loading = false; + if (liveStudent !== state || localStorage.getItem(workspaceSessionKey) !== token) return; + if (studentDashboard()) updateStudentHomeSchedule(); + else if (student() && ['overview','my-schedule','my-courses','course-detail','my-advisor'].includes(page)) render(); }); } const resolveCourse = code => studentCourses().find(c=>c[0]===code); @@ -452,7 +460,7 @@ function sidebar(){ const isOpen = groupIndex === 0 || items.includes(currentScreen); return ``; }).join('')} - + ${semesterFooter()} `; } @@ -540,10 +548,36 @@ function scheduleReviewFiles() { }).join('')}`; } +function staffScheduleSummary() { + const state = coordinatorSchedules; + if (!state?.data) { + if (role !== 'administrator') return ''; + if (state?.error) return ``; + if (state?.noTerm) return '

No active semester. Open Student schedules to look up a previous term.

'; + return '

Loading schedule coverage…

'; + } + const active = state.data.students.filter(student => student.isActive); + if (role === 'coordinator') { + const advising = active.filter(student => student.studentType === 'advising'); + const statuses = [[null,'Draft needed'],['draft','In draft'],['readyForStudentReview','Ready for student review'],['processed','Processed']]; + return `

Active advising students

${statuses.map(([status,label]) => + `
${label}
${advising.filter(student => student.scheduleStatus === status).length}
`).join('')}
`; + } + return ``; +} + function sidebarTerm() { if (!termDirectory?.data) return termDirectory?.error ? 'Semester unavailable' : 'Loading semester…'; return displayTerm(currentAcademicTerm()) || 'No active semester'; } +function semesterFooter() { + return ``; +} function updateSidebarTerm() { document.querySelectorAll('[data-sidebar-term]').forEach(label => { label.textContent = sidebarTerm(); }); } @@ -553,8 +587,13 @@ function overview(){ if (role === 'advisor') return advisorOverview(); const queueDestination = role==='coordinator' ? 'pending-work' : 'courses'; const queueLabel = role==='coordinator' ? 'All work' : 'Course catalogue'; + const scheduleSummary = `
${staffScheduleSummary()}
`; const reviewFiles = role !== 'administrator' ? `
${scheduleReviewFiles()}
` : - `
${link('student-schedules', desktopFolder + `Student schedules${role === 'administrator' ? 'View schedules and advising overviews' : 'Open schedules and drafts'}`, 'draft-file')}
`; + `
${[ + ['student-schedules','Student schedules','Schedules and advising overviews'], + ['group-assignments','Group assignments','Student placements and group coverage'], + ['schedule-activity','Schedule activity','Processing and reopening history'], + ].map(([route, title, description]) => link(route, desktopFolder + `${title}${description}`, 'draft-file')).join('')}
`; const removalsTask = ['course-removal','rose',null,'Course removals','Course removal requests','Credit load and scheduling decisions','mandatory-removals','Review']; const tasks = role==='coordinator' ? [ removalsTask, @@ -563,6 +602,7 @@ function overview(){ ] : [ ['group-assignment','iris',null,'Course offerings','Course offerings','Review offerings and class groups','offerings','View offerings'], ['advisor-assignment','mint',null,'Academic terms','Academic terms','Review registration dates and deadlines','terms','Manage terms'], + ['course-removal','rose',null,'Course removals','Course removals','Find removal requests and review their decisions','mandatory-removals','View removals'], ]; return `
${workspaceGrid({ columns: '1.5fr 1fr', @@ -570,7 +610,7 @@ function overview(){ }, { intro: head(studyGreeting(), termContext(`${roleNames[role]} workspace`)), queue: workspaceSection('Work queue', queueDestination, queueLabel, workQueue(tasks)), - review: workspaceSection('Schedule review', 'student-schedules', 'All schedules', reviewFiles), + review: workspaceSection(role === 'administrator' ? 'Schedule coverage' : 'Schedule review', 'student-schedules', 'All schedules', scheduleSummary + reviewFiles), calendar: deskCalendar(), })}
`; } @@ -593,12 +633,41 @@ function advisorOverview() { })}`; } +let renderedHomeWeek; +function studentHomeContext() { + return termContext(escapeHtml(liveStudent.data?.student?.major || 'Student workspace')); +} function studentOverview() { - const timetable = `

Teaching week

${weekly()}`; + renderedHomeWeek = weekly(); + const timetable = `

Teaching week

${renderedHomeWeek}`; const view = { columns: '1fr 1fr', rows: ['week week', 'review activity'] }; - return `
${head(studyGreeting(), termContext(escapeHtml(liveStudent.data?.student.major || 'Student workspace')))} + return `
${head(studyGreeting(), studentHomeContext())} ${workspaceGrid(view, { week: timetable, review: studentFeed(), activity: deskCalendar() })}
`; } +function updateStudentHomeSchedule() { + const home = app.querySelector('.student-dashboard'); + if (!home) return; + const nextWeek = weekly(); + const heading = home.querySelector('.timetable-heading'); + if (nextWeek !== renderedHomeWeek) { + heading.nextElementSibling.querySelectorAll('[data-arriving]').forEach(finishArrival); + heading.nextElementSibling.outerHTML = renderedHomeWeek = nextWeek; + heading.nextElementSibling.dispatchEvent(new Event('student-week-loaded', {bubbles:true})); + } + home.querySelector('.page-head p').innerHTML = studentHomeContext(); + home.querySelector('.student-upcoming').outerHTML = studentUpcoming(); +} +function updateHomeTerm() { + const home = app.querySelector('[data-screen="overview"]'); + if (!home) return; + const context = home.querySelector('.page-head p'); + if (context) context.innerHTML = student() ? studentHomeContext() : termContext(`${roleNames[role]} workspace`); + const calendar = home.querySelector('.desk-calendar'); + if (!calendar) return; + const paper = calendar.querySelector('.folio-paper:not(.binder-waiting-sheet) .folio-inner'); + if (paper) paper.outerHTML = calendarPage(); + calendar.querySelector('.folio-agenda').innerHTML = calendarAgenda(); +} function profile(){ const token = localStorage.getItem(workspaceSessionKey); @@ -697,19 +766,31 @@ function upcomingClasses(now = new Date()){ return meetings.slice(0,2); } -function studentFeed(){ +function studentUpcoming(){ const meetings = upcomingClasses(); - return `
-
+ return `

Coming up

    ${meetings.map(({time,code,detail,date,day})=>`
  • ${courseEmblem(code)}

    ${resolveCourse(code)?.[1] || escapeHtml(code)}

    ${detail}

  • `).join('')}
-
- ${studentNotificationPanel()} -
`; +
`; +} +function studentFeed(){ + return `
${studentUpcoming()}${studentNotificationPanel()}
`; +} +function updateNotificationsView() { + if (studentDashboard()) { + const feed = app.querySelector('.student-feed'); + feed.querySelector('.home-notifications').outerHTML = studentNotificationPanel(); + const panel = feed.querySelector('.home-notifications'); + window.addStaffArt?.('overview',panel); + drawInputEdges(panel); + observeNotificationPlate(panel.querySelector('.notification-plate')); + updateNotificationBadge(); + } else if (page === 'notifications') render(); + else updateNotificationBadge(); } function notificationViews(unreadCount) { @@ -732,7 +813,11 @@ function notifications(){ const token = localStorage.getItem(workspaceSessionKey); const state = token && liveInbox?.token === token ? liveInbox : null; const inboxStatus = token && !state?.data - ? state?.error ? `

${escapeHtml(state.error)}

` : '

Loading notifications…

' + ? state?.error ? `
+ ${notificationScenes('coffee',false)} +

Notifications couldn’t load

Try again to check your inbox.

+ ${button('Try again','retry-notifications','btn')} +
` : '

Loading notifications…

' : ''; return head('Notifications', '', (unread.length ? button('Mark all as read','read-all','btn primary') : ''), '')+strip+ @@ -751,12 +836,12 @@ async function markPortalNotifications(ids, control) { .map(({value}) => [value.notification._id, value.notification])); state.data = state.data.map(entry => updated.has(entry._id) ? { ...entry, ...updated.get(entry._id) } : entry); if (results.some(result => result.status === 'rejected')) { - render(); + updateNotificationsView(); toast('Some notifications could not be marked as read.', 'error'); return; } } - render(); + updateNotificationsView(); document.querySelector('[aria-selected=true][aria-controls="notice-results"]')?.focus(); toast(ids.length === 1 ? 'Notification marked as read.' : 'All notifications marked as read.'); } @@ -924,12 +1009,16 @@ function advisor(){ const token = localStorage.getItem(workspaceSessionKey); const state = token && liveAdvisor?.token === token ? liveAdvisor : null; const person = state?.data; + const unassigned = person === null; const status = !token ? '

Sign in to see your assigned advisor.

' : state?.error ? '

Could not load your advisor. Refresh the page to try again.

' - : person === null ? '

You don’t have an assigned advisor yet.

' : '

Loading your advisor…

'; - const deadline = liveStudent.token === token && liveStudent.data?.term.advisingDeadline; - const deadlineLabel = deadline ? formatCalendarDay(campusDay(new Date(deadline)), {day:'numeric', month:'long', year:'numeric'}) : ''; + const deadline = liveStudent.token === token && liveStudent.data?.term?.advisingDeadline; + const deadlineDay = deadline ? campusDay(new Date(deadline)) : ''; + const preferenceAction = `
+ ${deadlineDay ? `

Preferences due

` : ''} + ${link('preferences','Set course preferences'+icon('chevron'),'btn advisor-preferences-link')} +
`; return heading + `
@@ -937,11 +1026,16 @@ function advisor(){
University email
${escapeHtml(person.email)}

Before you meet

${['Review remaining credits','Choose preferred course groups','Write down questions'].map(item => ``).join('')} -
` : status} +
` : unassigned ? `
+ ${queueSketch('advisor-assignment')} +

You don’t have an assigned advisor yet.

+

While you wait, share the days, times and class groups that work for you.

+ ${preferenceAction} +
` : status}
`; } @@ -1061,6 +1155,14 @@ function mountLiveCalendar(panel) { } function calendarSync() { if (!student()) return head('Calendar sync') + '

Sign in with a student account to access Calendar sync.

'; + const periods = [['09:00','10:30'], ['10:45','12:15'], ['13:00','14:30']]; + const exampleWeek = [ + ['Sunday', [[0,'CSEN501','Database I'], [2,'CSEN503','Networks Lab']]], + ['Monday', [[1,'CSEN703','Algorithms']]], + ['Tuesday', [[0,'CSEN401','Programming Lab'], [1,'CSEN601','Computer Architecture']]], + ['Wednesday', [[1,'CSEN603','Software Engineering'], [2,'CSEN501','Database Tutorial']]], + ['Thursday', [[0,'CSEN503','Computer Networks'], [2,'CSEN602','Systems Lab']]], + ]; return `
@@ -1073,31 +1175,20 @@ function calendarSync() {

-
Example weekCairo time
-
-
-

Sun

-
Database I09:00–10:30
-
Networks Lab13:00–14:30
-
-

Mon

-
Algorithms10:45–12:15
-
-

Tue

-
Programming Lab09:00–10:30
-
Computer Architecture10:45–12:15
-
-

Wed

-
Software Engineering10:45–12:15
-
Database Tutorial13:00–14:30
-
-

Thu

-
Computer Networks09:00–10:30
-
Systems Lab13:00–14:30
-
-
+

Example week

Cairo time
+
+ ${exampleWeek.map(([day, meetings]) => `
+

${day}

+
    + ${meetings.map(([period, code, title]) => { + const [start, end] = periods[period]; + return `
  • + ${courseDrawing(code)}${title} +
  • `; + }).join('')} +
+
`).join('')}
-

Scroll to see the full week

`; } @@ -1111,7 +1202,7 @@ function auth(){

${title}

${page==='login' ? (returnAfterSignIn !== 'overview' ? `

Sign in as ${roleNames[role]} to open ${navigationLabel(returnAfterSignIn)}.

` : '') : `

${page==='forgot'?'We’ll send a reset code to your university email.':'Enter the six-digit code from your email.'}

`}
- ${page==='login' ? ` + ${page==='login' ? `
${link('forgot','Forgot password?','auth-recovery')}
` : ` @@ -1140,6 +1231,15 @@ function portalService(screen, section = '') { return `

Loading…

`; } +function roleUnavailable() { + return `
+ +

This page is unavailable for your role.

+

${escapeHtml(navigationLabel(page))} is outside the ${escapeHtml(roleNames[role])} workspace.

+ ${link('overview','Back to home','btn row-control')} +
`; +} + function academicServices() { return head('Academic services') + '

This page is unavailable.

'; } @@ -1203,6 +1303,7 @@ function accountControls(){ let arrivalObserver; let overviewOpened = false; +let stagedStudentWeekToken; const revealedOverviewItems = new Set(); const motionPreference=matchMedia('(prefers-reduced-motion: reduce)'); @@ -1249,17 +1350,10 @@ function playOverviewPose(el,kind,index,order){ origin=ordinal%2?'85% 95%':'15% 95%'; anchors=[P(0,x,y,sign*9,0),P(.05,x,y,sign*9,1),P(.16,x*.78,y,sign*4),P(.23,x*.78,y,sign*4),P(.31,x*.78,y*.48,-sign*6),P(.38,x*.78,y*.48,-sign*6),P(.5,x*.28,y*.48,sign*8),P(.56,x*.28,y*.48,sign*8),P(.65,x*.28,-17,-sign*5),P(.72,x*.28,-17,-sign*5),P(.81,-sign*12,-17,sign*3),P(.87,-sign*12,4,-sign*2),P(.94,sign*4,4,sign),finalPose()]; }else if(kind==='chrome'){ - // A book opens, then four groups of index tabs tug free of the binding. - // The shell, layout and navigation hit targets never change position. + // Keep sidebar link targets stationary while their labels are exposed. if(el.classList.contains('brand')){ duration=650;delay=15;origin='12% 52%'; anchors=[P(0,-25,-5,-5,0,.97),P(.12,-25,-5,-5,.45,.97),P(.29,-13,1,2,.9),P(.45,-13,1,2,1),P(.60,4,-1,-1.5),P(.74,4,-1,-1.5),P(.85,-2,0,.5),finalPose()]; - }else if(el.classList.contains('study-nav-group')){ - const i=Math.max(0,index-1); - duration=710+(i%2)*55;delay=105+i*115;origin='8% 35%'; - anchors=[P(0,-26+(i%2)*5,6,-2.8,0),P(.10,-26+(i%2)*5,6,-2.8,0), - P(.19,-18,0,-1.7,.75),P(.31,-18,0,-1.7,1),P(.49,-5,-2,1.3), - P(.61,-5,-2,1.3),P(.74,3,1,-.65),P(.85,3,1,-.65),P(.93,-1,0,.3),finalPose()]; }else if(el.classList.contains('sidebar-foot')){ duration=640;delay=605;origin='15% 60%'; anchors=[P(0,-10,6,-1,0),P(.2,-10,6,-1,0),P(.44,2,-1,.6,.83),P(.62,2,-1,.6,1),P(.85,-1,0,-.25),finalPose()]; @@ -1337,11 +1431,13 @@ function stageOverview(main){ overviewOpened=true; const shell=main.closest('.shell'); const units=new Map(); + const studentHome=studentDashboard(); + const weekUnits={day:'.week-day>h2',course:'.week-class',empty:'.week-day-off'}; const groups={ - chrome:'.brand,.study-nav-group,.sidebar-foot,.topbar', + chrome:'.brand,.sidebar-foot,.topbar', greeting:'.page-head h1',meta:'.page-head p',decoration:'.greeting-sun', heading:'.section-head,.timetable-heading',queue:'.queue-entry',upcoming:'.desk-calendar', - day:'.week-day>h2',course:'.week-class',empty:'.week-day-off', + ...(studentHome ? {} : weekUnits), note:'.module-review .review-person,.module-activity :is(.event,.activity-impression)', folder:'.module-review .draft-file' }; @@ -1349,10 +1445,10 @@ function stageOverview(main){ shell.querySelectorAll(selector).forEach((el,index)=>units.set(el,{kind,index})); } function reveal(el,order,scroll){ - const {kind,index}=units.get(el); + const {kind,index,studentWeek}=units.get(el); el.removeAttribute('data-arriving'); const key=kind==='folder' ? el.href : role+'-'+kind+'-'+index; - if(revealedOverviewItems.has(key) || el.matches(':focus-within')) return; + if((!studentWeek && revealedOverviewItems.has(key)) || el.matches(':focus-within')) return; if(kind==='folder'){ el.style.setProperty('--folder-duration',`${590+index*24}ms`); el.dataset.paperReveal='folder'; @@ -1363,9 +1459,9 @@ function stageOverview(main){ },{once:true}); return; } - revealedOverviewItems.add(key); + if(!studentWeek) revealedOverviewItems.add(key); if(kind==='empty'){ - if(opening || scroll){ + if(studentWeek || opening || scroll){ el.classList.add('coffee-wait'); // Let the last visible class card give the saucer its entrance cue. const arrivals=Array.from(main.querySelectorAll('.week-class')).flatMap(card=>card.getAnimations()) @@ -1381,7 +1477,7 @@ function stageOverview(main){ return; } if(!scroll){ - if(opening) playOverviewPose(el,kind,index,order); + if(studentWeek || opening) playOverviewPose(el,kind,index,order); return; } // The pencil-settle drawing from the scroll study, at one fifth amplitude. @@ -1399,14 +1495,31 @@ function stageOverview(main){ }); }); let order=0; - function stageUnit(el,{kind,index}){ + function stageUnit(el,{kind,index,studentWeek}){ const key=kind==='folder' ? el.href : role+'-'+kind+'-'+index; - if(revealedOverviewItems.has(key)) return; + if(!studentWeek && revealedOverviewItems.has(key)) return; const rect=el.getBoundingClientRect(); if(kind==='chrome'||(rect.top0)) reveal(el,order++,false); else {el.setAttribute('data-arriving','');arrivalObserver.observe(el);} } units.forEach((unit,el)=>stageUnit(el,unit)); + function stageStudentWeek(week){ + if(motionPreference.matches || !week?.firstElementChild || stagedStudentWeekToken===liveStudent.token) return; + stagedStudentWeekToken=liveStudent.token; + for(const [kind,selector] of Object.entries(weekUnits)){ + week.querySelectorAll(selector).forEach((el,index)=>{ + const unit={kind,index,studentWeek:true}; + units.set(el,unit); + stageUnit(el,unit); + }); + } + } + if(studentHome){ + stageStudentWeek(main.querySelector('.module-week .week-columns')); + main.addEventListener('student-week-loaded',event=>{ + if(event.target.matches('.week-columns')) stageStudentWeek(event.target); + }); + } main.addEventListener('schedule-folders-loaded',event=>{ if(motionPreference.matches) return; event.target.querySelectorAll('.draft-file').forEach((el,index)=>{ @@ -1416,8 +1529,8 @@ function stageOverview(main){ }); }); if(opening) shell.querySelectorAll('.study-nav-group').forEach((group,i)=>{ - group.querySelectorAll('a').forEach((link,j)=>{ - link.animate([ + group.querySelectorAll('a > span').forEach((label,j)=>{ + label.animate([ {offset:0,opacity:0,clipPath:'inset(0 100% 0 0)'}, {offset:.18,opacity:.5,clipPath:'inset(0 50% 0 0)'}, {offset:.38,opacity:.85,clipPath:'inset(0 15% 0 0)'}, @@ -1426,14 +1539,17 @@ function stageOverview(main){ }); }); shell.addEventListener('focusin',event=>{ + if(!event.target.matches(':focus-visible')) return; + const label = event.target.querySelector('.navlink > span'); + if(label) finishArrival(label); for(let el=event.target;el && el!==shell;el=el.parentElement) finishArrival(el); }); } motionPreference.addEventListener('change',()=>{ if(!motionPreference.matches) return; - if(pendingExposure) pendingExposure.finish(); arrivalObserver?.disconnect(); document.querySelectorAll('[data-arriving],[data-paper-reveal]').forEach(finishArrival); + document.querySelectorAll('.coffee-wait').forEach(el=>el.classList.remove('coffee-wait')); document.getAnimations().filter(animation=>animation.id==='overview-arrival').forEach(animation=>animation.cancel()); }); @@ -1467,7 +1583,8 @@ function render(focus=false){ document.body.dataset.portalRole = authPages.has(page) ? '' : role; document.title = `Portal · ${pageLabel}`; document.body.classList.toggle('auth-screen',authPages.has(page)); - const body=authPages.has(page)?auth():`
${sidebar()}
${link('overview',portalWordmark(),'mobile-nav wordmark')}${workspaces[lab.layout].name==='Claude Study'?'Academic workspace   /  ':''}${pageLabel}${escapeHtml(displayTerm(currentAcademicTerm()))}
${button(icon('menu')+'Menu','mobile-menu','mobile-menu')}${themeControl()}${accountControls()}
${renderers[page]()}
`; + const back = page === 'overview' ? '' : button(icon('chevron')+'Back', 'page-back', 'portal-page-back'); + const body=authPages.has(page)?auth():`
${sidebar()}
${link('overview',portalWordmark(),'mobile-nav wordmark')}${workspaces[lab.layout].name==='Claude Study'?'Academic workspace   /  ':''}${pageLabel}${escapeHtml(displayTerm(currentAcademicTerm()))}
${button(icon('menu')+'Menu','mobile-menu','mobile-menu')}${themeControl()}${accountControls()}
${back}${roleCanOpen(role, page) ? renderers[page]() : roleUnavailable()}
`; arrivalObserver?.disconnect(); disposePortalService?.(); disposePortalService = undefined; @@ -1501,19 +1618,49 @@ function render(focus=false){ } if(focus)document.querySelector('#content')?.focus({preventScroll:true}); } -function navigate(target, url, state = {}) { +function portalNavigationSession() { + let session = localStorage.getItem(workspaceNavigationKey); + if (!session) { + session = String(Date.now()); + localStorage.setItem(workspaceNavigationKey, session); + } + return session; +} +function portalNavigationPath(session) { + const navigation = history.state?.portalNavigation; + return navigation?.session === session && navigation.role === role ? navigation.path : []; +} +function goToPreviousPage() { + const path = portalNavigationPath(portalNavigationSession()); + const previous = path.at(-1); + if (previous && roleCanOpen(role, previous.page)) { + navigate(previous.page, previous.url, previous.context, {path: path.slice(0,-1), scrollTop: previous.scrollTop}); + } else navigate('overview', undefined, {}, {path: []}); +} +function navigate(target, url, state = {}, back) { if (dialog.open) dialog.close(); - page = pageKey(target); - tab = ''; - const destination = new URL(url || href(page), location.href); + const destination = new URL(url || href(pageKey(target)), location.href); if (authPages.has(target)) BobosPortalRoutes.normalize(destination.searchParams); else normalizePortalRoute(destination.searchParams); - page = pageKey(destination.searchParams.get('page')); - if (Object.hasOwn(roleNames, destination.searchParams.get('role'))) role = destination.searchParams.get('role'); + const next = pageKey(destination.searchParams.get('page')); + const requestedRole = destination.searchParams.get('role'); + const nextRole = Object.hasOwn(roleNames, requestedRole) ? requestedRole : role; + if (signedIn() && !authPages.has(next) && nextRole === role) { + const session = portalNavigationSession(); + const path = back?.path ?? (next === 'overview' ? [] : portalNavigationPath(session)); + const {portalScreen, portalContext} = history.state || {}; + const isNewDestination = destination.href !== location.href || portalContext !== state.portalContext; + const remember = !back && next !== 'overview' && roleCanOpen(role, page) && isNewDestination; + const previous = { page, url: location.search + location.hash, context: {portalScreen, portalContext}, scrollTop: window.scrollY }; + state = {...state, portalNavigation: {session, role, path: remember ? [...path.slice(-24), previous] : path}}; + } + page = next; + role = nextRole; + tab = ''; selectedCourse = resolveCourse(destination.searchParams.get('course')); history.pushState(state, '', destination); render(true); - window.scrollTo(0, 0); + window.scrollTo(0, back?.scrollTop || 0); } document.addEventListener('portal:open-service', ({detail: {screen, context}}) => { const target = BobosPortalRoutes.screenPage(screen, role); @@ -1548,6 +1695,7 @@ async function signInWorkspace(credentials){ } localStorage.setItem(workspaceSessionKey,data.token); localStorage.setItem('portal-account-role', data.user.role); + localStorage.setItem(workspaceNavigationKey, String(Date.now())); sessionStorage.setItem(workspaceAccountNameKey, data.user.fullName || roleNames[data.user.role]); return data.user.role; } @@ -1579,11 +1727,13 @@ function action(name,el){ return; } switch(name){ + case 'page-back': goToPreviousPage(); break; case 'sign-out': document.querySelector('portal-action-feedback').clear(); { const token = localStorage.getItem(workspaceSessionKey); localStorage.removeItem(workspaceSessionKey); + localStorage.removeItem(workspaceNavigationKey); localStorage.removeItem('portal-account-role'); sessionStorage.removeItem(workspaceAccountNameKey); if (token) { @@ -1604,10 +1754,10 @@ function action(name,el){ const menu = sections.map(([name,items])=>`
${name ? `

${name}

` : ''}
`).join(''); - const semester = usesStaffPresentation() ? `` : ''; - modal('Menu',``,null,'navigation'); + modal('Menu',``,null,'navigation'); break; } + case 'retry-notifications': loadAccountData(true); el.disabled = true; el.textContent = 'Trying again…'; break; case 'read-all':void markPortalNotifications(notificationEntries().filter(item => !item.isRead).map(item => item._id), el);break; case 'read-one':void markPortalNotifications([el.dataset.notification], el);break; case 'close-dialog':closeDialog();break; @@ -1835,8 +1985,7 @@ if (page === 'calendar-sync' && ['connected', 'error'].includes(params.get('cale } function refreshStudentSchedule() { if (student() && ['overview','my-schedule','my-courses','course-detail'].includes(page) && !document.hidden && !liveStudent.loading) { - liveStudent.token = null; - loadStudentSchedule(); + loadStudentSchedule(true); } } window.addEventListener('focus', refreshStudentSchedule); diff --git a/apps/web/public/portal-studio/coordinator.css b/apps/web/public/portal-studio/coordinator.css index 5356825..2e392c8 100644 --- a/apps/web/public/portal-studio/coordinator.css +++ b/apps/web/public/portal-studio/coordinator.css @@ -73,16 +73,32 @@ body.portal-studio[data-workspace=claude-study] .dashboard-edition[data-edition= } } body:is([data-portal-role=coordinator],[data-portal-role=advisor],[data-portal-role=administrator]) { - .sidebar nav { flex: 1; min-height: 0; overflow-y: auto; } - .sidebar-foot { flex: none; padding-top: 14px; } #notice-results .empty .notification-plate { width: min(220px, 80%); height: auto; margin: 0 auto 16px; } - .menu-semester { margin: 0 9px 16px; color: var(--muted); font-size: 13px; } :is(a,button,summary,input,textarea,select,[tabindex="0"]):focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; } #content:focus { outline: none; } } +.staff-schedule-summary { container: schedule-summary / inline-size; } +.staff-schedule-caption { margin: 0 0 9px; color: var(--muted); font-size: 13px; } +.schedule-status-strip { + display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); gap: 1px; + margin: 0 0 14px; padding: 1px; border-radius: 10px; overflow: hidden; background: var(--line); +} +.schedule-status-strip > div { display: grid; align-content: start; gap: 5px; padding: 11px 12px; background: var(--canvas); } +.schedule-status-strip dt { color: var(--muted); font-size: 12px; line-height: 1.4; } +.schedule-status-strip dd { order: -1; margin: 0; font: 500 23px/1.2 Styrene,system-ui,sans-serif; font-variant-numeric: tabular-nums; } +@container schedule-summary (max-width: 465px) { + .schedule-status-strip { grid-template-columns: repeat(2,minmax(0,1fr)); } +} +.schedule-coverage { display: grid; gap: 12px; margin: 0 0 18px; padding: 0; list-style: none; } +.schedule-coverage li { display: grid; gap: 6px; padding: 10px 14px 12px; border: 1px solid var(--line); border-radius: 9px; } +.schedule-coverage li > div { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 4px 12px; } +.schedule-coverage strong { font-size: 14px; font-weight: 500; } +.schedule-coverage span { color: var(--muted); font-size: 13px; font-variant-numeric: tabular-nums; } +.schedule-coverage progress { display: block; width: 100%; height: 6px; border: 0; overflow: hidden; border-radius: 8px; accent-color: #8aab99; } + @keyframes coordinator-folder-hinge { 0% { transform: none; } 10% { transform: scaleY(1.02); } diff --git a/apps/web/public/portal-studio/images/preference-teaching-times.svg b/apps/web/public/portal-studio/images/preference-teaching-times.svg new file mode 100644 index 0000000..d7f1d7b --- /dev/null +++ b/apps/web/public/portal-studio/images/preference-teaching-times.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/apps/web/public/portal-studio/images/preference-week.svg b/apps/web/public/portal-studio/images/preference-week.svg new file mode 100644 index 0000000..de9c3e5 --- /dev/null +++ b/apps/web/public/portal-studio/images/preference-week.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/apps/web/public/portal-studio/index.html b/apps/web/public/portal-studio/index.html index 5add4be..224c17f 100644 --- a/apps/web/public/portal-studio/index.html +++ b/apps/web/public/portal-studio/index.html @@ -12,15 +12,15 @@ - + - - + + @@ -45,6 +45,6 @@ - + diff --git a/apps/web/public/portal-studio/student-pages.css b/apps/web/public/portal-studio/student-pages.css index d18b14e..8753995 100644 --- a/apps/web/public/portal-studio/student-pages.css +++ b/apps/web/public/portal-studio/student-pages.css @@ -74,8 +74,28 @@ & [data-screen="my-advisor"] .advisor-callout h2, & .student-calendar h2{font:500 17px/1.3 Styrene,system-ui,sans-serif;letter-spacing:-.025em} & [data-screen="my-advisor"] .advisor-callout p {color:var(--muted);margin:6px 0 14px} - & [data-screen="my-advisor"] .advisor-deadline{margin-top:17px} & [data-screen="my-advisor"] .advisor-checklist{margin-top:25px} + & [data-screen="my-advisor"] .advisor-empty { + display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;column-gap:14px; + border:1px solid var(--line);border-radius:14px;background:var(--paper);padding:clamp(18px,2.4vw,32px); + } + & [data-screen="my-advisor"] .advisor-empty .queue-sketch { + display:block;grid-column:2;grid-row:1 / span 2;width:clamp(58px,8vw,108px);height:auto; + } + & [data-screen="my-advisor"] .advisor-empty h2 { + font:500 clamp(18px,2vw,24px)/1.3 Styrene,system-ui,sans-serif;letter-spacing:-.035em; + } + & [data-screen="my-advisor"] .advisor-empty-copy p { + margin-top:8px;font-size:14px;line-height:1.65;color:var(--muted);max-width:36ch; + } + & [data-screen="my-advisor"] .advisor-preference-action { + display:grid;grid-column:1 / -1;justify-items:start;gap:8px;margin-top:18px; + } + & [data-screen="my-advisor"] .advisor-deadline {margin:0;font-size:13px;line-height:1.5;color:var(--muted)} + & [data-screen="my-advisor"] .advisor-deadline time {color:var(--ink);font-weight:500} + & [data-screen="my-advisor"] .advisor-preferences-link {min-height:44px;border-color:var(--control);color:var(--ink);font-weight:500} + & [data-screen="my-advisor"] .advisor-preferences-link:not(:is(:hover,:focus-visible)) {background:var(--raised)} + & [data-screen="my-advisor"] .advisor-preferences-link .icon {width:15px;height:15px} & .student-calendar{display:grid;gap:30px;max-width:740px} & .calendar-provider {display:flex;align-items:center;gap:14px;flex-wrap:wrap} & .calendar-provider>.icon{width:29px;height:29px;color:var(--signal-sky)} @@ -157,6 +177,7 @@ font-size:clamp(24px,2.6vw,32px); } .student-dashboard .timetable-heading {margin-bottom:22px} +.student-overview-calendar .calendar-heading {row-gap:9px} .student-overview-calendar .calendar-sync-link { min-height:44px;padding-inline:12px;gap:8px;font-size:14px; background:transparent;color:var(--ink);border:1px solid var(--control); @@ -382,32 +403,53 @@ width: 48px; height: auto; } -.calendar-sync-preview { margin: 0; min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 12px; background: var(--paper); } +.calendar-sync-preview { container-type: inline-size; margin: 0; min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 12px; background: var(--paper); } .calendar-sync-preview figcaption { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; padding: 14px 16px; border-bottom: 1px solid var(--line); } -.calendar-sync-preview figcaption strong { font-size: 14px; font-weight: 500; } +.calendar-sync-preview figcaption h2 { margin: 0; font: 550 14px/1.4 Styrene, system-ui, sans-serif; } .calendar-sync-preview figcaption span { font-size: 12px; color: var(--muted); } -.calendar-sync-preview-scroll { overflow-x: auto; } -.calendar-sync-preview-scroll:focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; } -.calendar-sync-week { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); min-inline-size: 550px; } -.calendar-sync-day { --preview-heading-height: 40px; --preview-slot-height: 82px; display: grid; grid-template-rows: var(--preview-heading-height) repeat(3, var(--preview-slot-height)); align-items: start; min-width: 0; background: repeating-linear-gradient(to bottom, var(--line) 0 1px, transparent 1px var(--preview-slot-height)) 0 var(--preview-heading-height) / 100% 100% no-repeat; } -.calendar-sync-day + .calendar-sync-day { border-inline-start: 1px solid var(--line); } -.calendar-sync-day h2 { margin: 0; align-self: stretch; display: grid; place-items: center; background: var(--paper); color: var(--muted); font: 500 12px/1.2 Styrene, system-ui, sans-serif; } -.calendar-sync-event { grid-row: 2; display: grid; gap: 4px; margin: 6px; padding: 7px 8px; border-radius: 5px; background: #dbe7fa; color: #263f61; font-size: 12px; line-height: 1.4; } -.calendar-sync-event strong { font-weight: 600; overflow-wrap: anywhere; } -.calendar-sync-event span { font-size: 11px; font-variant-numeric: tabular-nums; white-space: nowrap; } -.calendar-sync-event[data-period="mid"] { grid-row: 3; } -.calendar-sync-event[data-period="late"] { grid-row: 4; } -.calendar-sync-event.event-tutorial { background: #f0e1c8; color: #604725; } -.calendar-sync-event.event-lab { background: #dcebe1; color: #2e5141; } -.calendar-sync-scroll-hint { display: none; } +.calendar-sync-day { display: grid; grid-template-columns: 4.6rem minmax(0, 1fr); gap: 8px; min-width: 0; padding: 10px 12px; } +.calendar-sync-day + .calendar-sync-day { border-block-start: 1px solid var(--line); } +.calendar-sync-day h3 { margin: 0; padding-block-start: 12px; color: var(--muted); font: 550 12px/1.4 Styrene, system-ui, sans-serif; } +.calendar-sync-day-events { display: grid; gap: 5px; min-width: 0; margin: 0; padding: 0; list-style: none; } +.calendar-sync-event { + display: grid; + grid-template-columns: 28px minmax(0, 1fr); + align-items: center; + gap: 1px 8px; + min-width: 0; + padding: 6px 8px; + border-radius: 6px; + background: color-mix(in srgb, var(--course-emblem, #e5decd) 55%, var(--paper)); + color: #28302c; + line-height: 1.35; +} +[data-theme="dark"] .calendar-sync-event { background: color-mix(in srgb, var(--course-emblem, #e5decd) 86%, var(--paper)); } +.calendar-sync-event .course-drawing { position: static; grid-row: span 2; width: 28px; height: 24px; max-width: none; margin: 0; opacity: 1; object-fit: contain; } +.calendar-sync-event time { grid-column: 2; grid-row: 2; font-size: 11px; font-variant-numeric: tabular-nums; white-space: nowrap; } +.calendar-sync-event strong { grid-column: 2; grid-row: 1; font-size: 12px; font-weight: 600; overflow-wrap: anywhere; } +@container (min-width: 450px) and (max-width: 609px) { + .calendar-sync-day-events { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} +@container (min-width: 610px) { + .calendar-sync-week { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); } + .calendar-sync-day { --slot-height: 82px; display: block; padding: 0; } + .calendar-sync-day + .calendar-sync-day { border-block-start: 0; border-inline-start: 1px solid var(--line); } + .calendar-sync-day h3 { padding: 10px 6px; text-align: center; } + .calendar-sync-day-events { + grid-template-rows: repeat(3, var(--slot-height)); + gap: 0; + background: repeating-linear-gradient(to bottom, var(--line) 0 1px, transparent 1px var(--slot-height)); + } + .calendar-sync-event { grid-row: var(--period); align-content: start; gap: 3px 5px; margin: 5px; } + .calendar-sync-event .course-drawing { grid-row: 1; } + .calendar-sync-event time { grid-row: 1; } + .calendar-sync-event strong { grid-column: 1 / -1; grid-row: 2; } +} .calendar-sync-account:not([data-connected]) .calendar-sync-account-heading, .calendar-sync-account[data-connected] :is(.calendar-sync-art,.calendar-sync-preview) { display: none; } @media (max-width: 900px) { [data-screen="calendar-sync"] .calendar-sync-account:not([data-connected]) { grid-template-columns: minmax(0, 1fr); gap: 24px; padding-block-start: 24px; max-inline-size: 720px; } } -@media (max-width: 620px) { - .calendar-sync-scroll-hint { display: block; margin: 0; padding: 8px 14px; border-top: 1px solid var(--line); color: var(--muted); font-size: 12px; } -} .calendar-sync-account-heading { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; } .calendar-sync-account-heading h1 { margin: 0; font: 600 26px/1.3 Styrene, system-ui, sans-serif; } .calendar-sync-account[data-connected] .calendar-sync-entry { @@ -440,3 +482,21 @@ padding-inline: 15px; font-size: 14px; } + +.notification-load-error { min-height: 285px; display: grid; align-content: center; justify-items: center; gap: 12px; } +.notification-load-error h2 { margin: 0 0 5px; } +.notification-load-error p { margin: 0; } + +.portal-role-unavailable { + min-height: min(620px, 68dvh); + display: grid; + place-content: center; + justify-items: center; + gap: 13px; + padding: 28px 20px; + text-align: center; +} +.portal-role-unavailable img { object-fit: contain; } +.portal-role-unavailable h1 { margin: 3px 0 0; font-size: clamp(22px, 3.4vw, 38px); letter-spacing: -.035em; } +.portal-role-unavailable p { margin: 0; max-width: 43ch; color: var(--muted); } +.portal-role-unavailable a { margin-block-start: 9px; } diff --git a/apps/web/public/portal-studio/workspace-pages.css b/apps/web/public/portal-studio/workspace-pages.css index 5d9d73c..fa19f6a 100644 --- a/apps/web/public/portal-studio/workspace-pages.css +++ b/apps/web/public/portal-studio/workspace-pages.css @@ -580,6 +580,29 @@ dialog .menu-close:hover {background:var(--raised);color:var(--ink)} .workspace-menu a:focus-visible,dialog .menu-close:focus-visible {outline:2px solid currentColor;outline-offset:-3px} @media(pointer:coarse) {.workspace-menu a {min-height:44px}} +[data-workspace=claude-study] .sidebar nav {flex:1;min-height:0;overflow-y:auto} +[data-workspace=claude-study] .sidebar-foot { + display:flex;align-items:center;flex:none;gap:10px;margin:12px 3px 0; + padding:10px 5px 0;border-top:1px solid var(--line);color:var(--ink); +} +[data-workspace=claude-study] .sidebar-foot > .icon { + width:28px;height:28px;padding:6px;flex:none;border-radius:6px;background:var(--raised);color:var(--muted); +} +[data-workspace=claude-study] .sidebar-foot :is(small,strong) {display:block;line-height:1.45} +[data-workspace=claude-study] .sidebar-foot small {color:var(--muted);font-size:11px} +[data-workspace=claude-study] .sidebar-foot strong {font-size:12px;font-weight:600} +[data-workspace=claude-study] .workspace-menu .sidebar-foot {margin-inline:9px;padding-inline:0} + +.portal-page-back { + display:inline-flex;align-items:center;gap:5px;min-height:34px;margin:-6px 0 11px -5px;padding:4px 8px 4px 5px; + border:0;border-radius:6px;background:transparent;color:var(--muted);cursor:pointer;font-weight:500; +} +.portal-page-back .icon {width:16px;height:16px;transform:rotate(180deg)} +.portal-page-back:is(:hover,:focus-visible) {background:var(--raised);color:var(--ink)} +.portal-page-back:focus-visible {outline:2px solid var(--ink);outline-offset:-2px} +@media (max-width:810px) {.portal-page-back {min-height:44px;margin-bottom:6px}} +@media print {.portal-page-back {display:none}} + /* API timetables can contain Saturday–Thursday; keep every day in one row. */ .portal-studio .week-columns.live-student-week { display: grid; diff --git a/apps/web/src/api.js b/apps/web/src/api.js index 9f47130..f0dcc92 100644 --- a/apps/web/src/api.js +++ b/apps/web/src/api.js @@ -13,9 +13,9 @@ const API_BASE_URL = (import.meta.env.VITE_API_BASE_URL || "").replace(/\/+$/, " function requestFailureMessage(status, data) { if (data?.message) return data.message; if ([502, 503, 504].includes(status)) { - return `The API service is unavailable (${status}). Check the configured API URL and that the backend is running.`; + return "This service is temporarily unavailable. Please try again in a few minutes."; } - return `Request failed (${status}).`; + return "We couldn’t complete your request. Please try again."; } export async function api(path, { token, method = "GET", body, signal, responseType = "json" } = {}) { @@ -33,7 +33,7 @@ export async function api(path, { token, method = "GET", body, signal, responseT }); } catch (error) { if (error.name === "AbortError") throw error; - throw new ApiError("The API could not be reached. Check that the backend is running.", 0, path); + throw new ApiError("We couldn’t connect to the portal. Check your internet connection and try again.", 0, path); } if (responseType === "blob") { @@ -51,9 +51,9 @@ export async function api(path, { token, method = "GET", body, signal, responseT return data; } -export function explainApiError(error, feature) { +export function explainApiError(error) { if (error?.status === 404 && !error?.data?.message) { - return `${feature} is not available on the current Development backend yet (${error.path}).`; + return "We couldn’t find what you requested."; } return error?.data?.message || error?.message || "Something went wrong. Please try again."; } diff --git a/apps/web/src/components/AcademicWorkspace.jsx b/apps/web/src/components/AcademicWorkspace.jsx index 8c7ef22..85b5ed9 100644 --- a/apps/web/src/components/AcademicWorkspace.jsx +++ b/apps/web/src/components/AcademicWorkspace.jsx @@ -74,6 +74,7 @@ function CoursesWorkspace({ token, role, notify }) { finally { setDeleting(false); } }; const [viewing, setViewing] = useState(null); + const [directCourseDismissed, setDirectCourseDismissed] = useState(false); const initialCourse = useRef(new URLSearchParams(window.location.search).get("course")); useEffect(() => { if (!courses.length || !initialCourse.current) return; @@ -89,7 +90,7 @@ function CoursesWorkspace({ token, role, notify }) { const prerequisites = form.getAll("prerequisites"); const payload = { code: form.get("code"), name: form.get("name"), creditHours: Number(form.get("creditHours")), courseType: form.get("courseType"), - facultyMajors: splitLines(form.get("facultyMajors")), offeringSeasons: form.getAll("offeringSeasons"), + facultyMajors: form.getAll("facultyMajors"), offeringSeasons: form.getAll("offeringSeasons"), prerequisites, recommendedSemester: form.get("recommendedSemester") ? Number(form.get("recommendedSemester")) : undefined, lectureHours: form.get("lectureHours") ? Number(form.get("lectureHours")) : undefined, tutorialHours: form.get("tutorialHours") ? Number(form.get("tutorialHours")) : undefined, @@ -102,6 +103,12 @@ function CoursesWorkspace({ token, role, notify }) { } catch (e) { setEditError(e.message); } finally { setSaving(false); } }; + const routeCourse = new URLSearchParams(location.search); + const directCode = routeCourse.get("page") === "course-detail" ? routeCourse.get("course") : null; + const directCourse = directCode && courses.find(course => course.code.replace(/\s/g, "").toUpperCase() === directCode.replace(/\s/g, "").toUpperCase()); + const activeCourse = viewing || (directCourseDismissed ? null : directCourse); + const closeCourse = () => { setViewing(null); setDirectCourseDismissed(true); }; + return
@@ -129,7 +136,7 @@ function CoursesWorkspace({ token, role, notify }) { )} : } - {viewing && setViewing(null)} onEdit={canManage ? () => { setViewing(null); openCourseEditor(viewing); } : undefined} />} + {activeCourse && { closeCourse(); openCourseEditor(activeCourse); } : undefined} />} {editing && !saving && setEditing(null)} saving={saving} error={editError} />} {importOpen && @@ -215,7 +222,6 @@ function TermCalendar({ term }) { const events = milestones.filter(item => monthOf(item.date) === month); return
-

{monthName}

@@ -226,7 +232,9 @@ function TermCalendar({ term }) { {Array.from({length:days}, (_,i) => { const day = i + 1; const labels = events.filter(item => item.date.getUTCDate() === day).map(item => item.label); return {day}; })}
- {events.length > 0 &&

{events.sort((a,b) => a.date-b.date).map(item => `${item.date.getUTCDate()} · ${item.label}`).join(" / ")}

} +

Dates this month

+ {events.length ?
    {events.sort((a,b) => a.date-b.date).map(item =>
  • {item.label}
  • )}
:

No term dates this month.

} +
; } @@ -350,14 +358,22 @@ function TermsWorkspace({ token, role, notify }) {
-

Terms

{matching.length} of {terms.length}
+

{filters.status === 'inactive' ? 'Inactive terms' : filters.status === 'active' ? 'Active terms' : 'Terms'}

{matching.length} of {terms.length}
{fetchingTerms && !terms.length ? : matching.length ? {matching.map(term => {term.isActive ? 'Active' : 'Inactive'} )} :

{terms.length ? 'No matching terms' : 'No academic terms yet'}

{terms.length ? 'Try another search or clear the filters.' : 'Add your first term to set up its dates.'}

}
- {viewing && setViewing(null)} wide>
{Object.entries(termDateGroups).map(([label, fields]) =>
{label}
viewing[field])} />
)}
} + {viewing && setViewing(null)} wide> +
+

Dates and deadlines

{viewing.isActive ? 'Active' : 'Inactive'}
+
{Object.entries(termDateGroups).map(([label, fields]) =>
{label}
viewing[field])} />
)}
+
+ +
+
+
} {editing && { if (!loading) setEditing(false); }} wide> {attempt > 0 && Object.keys(validation).length > 0 &&
Complete {Object.keys(validation).length} highlighted {Object.keys(validation).length === 1 ? 'field' : 'fields'} before saving.
} @@ -464,8 +480,9 @@ function OfferingsWorkspace({ token, notify }) { const togglePublish = async (offering) => { try { await api(`/api/catalogue/offerings/${offering._id}/publish`, { token, method: "PATCH", body: { isPublished: !offering.isPublished } }); notify("success", `${offering.course?.code || "Offering"} ${offering.isPublished ? "unpublished" : "published"}.`); load(); } catch (e) { setError(e.message); } }; const removeOffering = async () => { if (!confirmingDelete) return; setDeleting(true); setDeleteError(""); try { await waitForPaperToss(); await api(`/api/catalogue/offerings/${confirmingDelete._id}`, { token, method: "DELETE" }); notify("success", `${confirmingDelete.course?.code || "Offering"} deleted.`); setConfirmingDelete(null); load(); } catch (e) { setDeleteError(e.message); } finally { setDeleting(false); } }; const afterSave = (message) => { notify("success", message); setCreating(false); setDetails(null); load(); }; + const majors = [...courses.flatMap(catalogueMajors), ...offeringMajors(offerings)]; return

OFFERINGS

Course offerings

Create term offerings, manage course groups, and publish the catalogue.

-

Offerings load automatically for the selected term. Choose a previous source term below to duplicate courses.

+

Choose the term whose offerings you want to manage.

{termSummary && duplicating && setDuplicating(false)} onCopied={() => load(undefined, termSummary.code)} />} {error &&
{error}
}

TERM OFFERINGS

Course groups

{loading ? "Loading" : `${offerings.length} offerings`}
{loading ? : offerings.length === 0 ?

No offerings yet

This term’s course register is empty. Use Create offering or Duplicate offerings above to get started.

:
{offerings.map(offering => @@ -474,10 +491,11 @@ function OfferingsWorkspace({ token, notify }) { )}
CourseCreditsGroupsInstructorsStatusActions
{offering.isPublished ? "Published" : "Draft"}
{ setDeleteError(""); setConfirmingDelete(offering); }}>Delete
}
- {creating && setCreating(false)} onSaved={() => afterSave("Course offering created.")} />} - {details && setDetails(null)} onChanged={afterSave} />} - {confirmingDelete && !deleting && setConfirmingDelete(null)}> -

Remove {confirmingDelete.course?.code || "this course"} from {termLabel(confirmingDelete.term || termSummary)}?

This also removes its lecture, tutorial, and lab groups. The API will block deletion if the offering is still referenced by schedules or templates.

+ {creating && setCreating(false)} onSaved={() => afterSave("Course offering created.")} />} + {details && setDetails(null)} onChanged={afterSave} />} + {confirmingDelete && setConfirmingDelete(null)}> +
{confirmingDelete.course?.name || confirmingDelete.course?.code || "Course offering"}{confirmingDelete.course?.code} · {termLabel(confirmingDelete.term || termSummary)}
+

Deleting this offering removes its meeting groups. You can delete it once it is no longer used in schedules or templates.

{deleteError &&
{deleteError}
}
{deleting ? "Deleting…" : "Delete offering"}
} @@ -537,8 +555,8 @@ function DuplicateOfferings({ token, target, targetOfferings, loading, onCopied, finally { setCopying(false); } } - return !copying && onClose()} wide>
-

Choose which courses to copy as unpublished drafts. Existing offerings are skipped.

+ return
+

Select a previous academic term to copy its course offerings as drafts. Courses already in {termLabel(target)} are skipped.

@@ -1061,10 +1091,21 @@ function TemplatesWorkspace({ token, notify }) {
} - {confirmingDelete && !deleting && setConfirmingDelete(null)}> -

Delete the template for {confirmingDelete.major}, semester {confirmingDelete.semester}, group {confirmingDelete.studyGroup}?

Reassign any student schedules using this template before deleting it.

+ {confirmingDelete && !deleting && setConfirmingDelete(null)}> +
+
+ Group {confirmingDelete.studyGroup} + {confirmingDelete.major} · Semester {confirmingDelete.semester} + {termLabel(confirmingDelete.term || selectedTerm)} +
+ +
+

Students assigned to this template must be moved to another group or unassigned before it can be deleted.

{deleteError &&
{deleteError}
} -
{deleting ? "Deleting…" : "Delete template"}
+
+ + {deleting ? "Deleting…" : "Delete template"} +
}
; } @@ -1073,7 +1114,62 @@ function offeringComponentTypes(offering) { return [...new Set((offering?.slots || []).map((slot) => slot.componentType))]; } -function OfferingModal({ token, courses, termId, term, onClose, onSaved }) { +function offeringMajors(offerings) { + return offerings.flatMap(offering => [ + ...(offering.eligibleGroups || []).map(group => group.major), + ...catalogueMajors(offering.course), + ]); +} + +function majorOptionLabel(major) { + const programme = programmes.find(({ code }) => majorsMatch(code, major)); + return programme ? `${programme.name} (${programme.code})` : major; +} + +function MajorSelect({ value, available, excluded = [], placeholder = "Choose a major", ...props }) { + const options = [value, ...programmes.map(({ code }) => code), ...available].reduce((result, major) => { + if (major && !result.some(option => majorsMatch(option, major)) && !excluded.some(option => majorsMatch(option, major))) result.push(major); + return result; + }, []); + return ; +} + +function EligibleGroupFields({ groups, onChange, available, disabled }) { + const update = (index, values) => onChange(groups.map((group, position) => position === index ? { ...group, ...values } : group)); + return
+ Eligible student groups + {groups.map((group, index) =>
+ update(index, { major: event.target.value })} /> + update(index, { semester: event.target.value })} /> + update(index, { studyGroup: event.target.value })} /> + +
)} + +
; +} + +function offeringInstructors(form) { + return splitLines(form.get("instructors")).map(line => { + const [fullName, email] = line.split("|").map(part => part.trim()); + return { fullName, ...(email ? { email } : {}) }; + }); +} + +function eligibleGroupsPayload(groups) { + return groups.map(({ major, semester, studyGroup }) => ({ + major, ...(semester ? { semester: Number(semester) } : {}), + ...(studyGroup?.trim() ? { studyGroup: studyGroup.trim() } : {}), + })); +} + +function OfferingModal({ token, courses, majors, termId, term, onClose, onSaved }) { + const [groups, setGroups] = useState([]); const [slots, setSlots] = useState([emptySlot("1")]); const [isPublished, setIsPublished] = useState(false); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); const setSlot = (index, key, value) => setSlots((current) => current.map((slot, position) => { if (position !== index) return slot; @@ -1082,16 +1178,77 @@ function OfferingModal({ token, courses, termId, term, onClose, onSaved }) { return { ...slot, [key]: value }; })); const addSlot = () => setSlots((current) => [...current, emptySlot(nextGroupNumber(current, -1, "lecture"))]); - const submit = async (event) => { event.preventDefault(); setSaving(true); setError(""); const form = new FormData(event.currentTarget); const instructors = splitLines(form.get("instructors")).map((line) => { const [fullName, email] = line.split("|").map((part) => part.trim()); return { fullName, ...(email ? { email } : {}) }; }); const eligibleGroups = splitLines(form.get("eligibleGroups")).map((line) => { const [major, semester, studyGroup] = line.split("|").map((part) => part.trim()); return { major, ...(semester ? { semester: Number(semester) } : {}), ...(studyGroup ? { studyGroup } : {}) }; }); const payload = { course: form.get("course"), term: termId.trim(), instructors, eligibleGroups, isPublished, slots: slots.map((slot) => ({ componentType: slot.componentType, groupNumber: slot.groupNumber.trim(), day: slot.day, startMinute: timeToMinutes(slot.startTime), endMinute: timeToMinutes(slot.endTime), room: slot.room.trim(), capacity: Number(slot.capacity) })) }; try { await api("/api/catalogue/offerings", { token, method: "POST", body: payload }); onSaved(); } catch (e) { setError(e.message); } finally { setSaving(false); } }; - return